Skip to content

fix repr of strings/chars with quotes #9046

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions src/libstd/repr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ impl<'self> ReprVisitor<'self> {
pub fn write_escaped_slice(&mut self, slice: &str) {
self.writer.write(['"' as u8]);
for ch in slice.iter() {
self.write_escaped_char(ch);
self.write_escaped_char(ch, true);
}
self.writer.write(['"' as u8]);
}
Expand Down Expand Up @@ -230,14 +230,26 @@ impl<'self> ReprVisitor<'self> {
v.fill, inner)
}

fn write_escaped_char(&mut self, ch: char) {
fn write_escaped_char(&mut self, ch: char, is_str: bool) {
match ch {
'\t' => self.writer.write("\\t".as_bytes()),
'\r' => self.writer.write("\\r".as_bytes()),
'\n' => self.writer.write("\\n".as_bytes()),
'\\' => self.writer.write("\\\\".as_bytes()),
'\'' => self.writer.write("\\'".as_bytes()),
'"' => self.writer.write("\\\"".as_bytes()),
'\'' => {
if is_str {
self.writer.write("'".as_bytes())
} else {
self.writer.write("\\'".as_bytes())
}
}
'"' => {
if is_str {
self.writer.write("\\\"".as_bytes())
} else {
self.writer.write("\"".as_bytes())
}
}
'\x20'..'\x7e' => self.writer.write([ch as u8]),
_ => {
do char::escape_unicode(ch) |c| {
Expand Down Expand Up @@ -274,7 +286,7 @@ impl<'self> TyVisitor for ReprVisitor<'self> {
fn visit_char(&mut self) -> bool {
do self.get::<char> |this, &ch| {
this.writer.write(['\'' as u8]);
this.write_escaped_char(ch);
this.write_escaped_char(ch, false);
this.writer.write(['\'' as u8]);
}
}
Expand Down Expand Up @@ -684,6 +696,11 @@ fn test_repr() {
exact_test(&(10u64, ~"hello"),
"(10u64, ~\"hello\")");

exact_test(&'\'', "'\\''");
exact_test(&'"', "'\"'");
exact_test(&("'"), "\"'\"");
exact_test(&("\""), "\"\\\"\"");

exact_test(&println, "fn(&str)");
exact_test(&swap::<int>, "fn(&mut int, &mut int)");
exact_test(&is_alphabetic, "fn(char) -> bool");
Expand Down