Skip to content

Commit f87578d

Browse files
committed
fix repr of strings/chars with quotes
Closes #8743
1 parent aa1d4ef commit f87578d

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/libstd/repr.rs

+22-5
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ impl<'self> ReprVisitor<'self> {
178178
pub fn write_escaped_slice(&mut self, slice: &str) {
179179
self.writer.write(['"' as u8]);
180180
for ch in slice.iter() {
181-
self.write_escaped_char(ch);
181+
self.write_escaped_char(ch, true);
182182
}
183183
self.writer.write(['"' as u8]);
184184
}
@@ -230,14 +230,26 @@ impl<'self> ReprVisitor<'self> {
230230
v.fill, inner)
231231
}
232232

233-
fn write_escaped_char(&mut self, ch: char) {
233+
fn write_escaped_char(&mut self, ch: char, is_str: bool) {
234234
match ch {
235235
'\t' => self.writer.write("\\t".as_bytes()),
236236
'\r' => self.writer.write("\\r".as_bytes()),
237237
'\n' => self.writer.write("\\n".as_bytes()),
238238
'\\' => self.writer.write("\\\\".as_bytes()),
239-
'\'' => self.writer.write("\\'".as_bytes()),
240-
'"' => self.writer.write("\\\"".as_bytes()),
239+
'\'' => {
240+
if is_str {
241+
self.writer.write("'".as_bytes())
242+
} else {
243+
self.writer.write("\\'".as_bytes())
244+
}
245+
}
246+
'"' => {
247+
if is_str {
248+
self.writer.write("\\\"".as_bytes())
249+
} else {
250+
self.writer.write("\"".as_bytes())
251+
}
252+
}
241253
'\x20'..'\x7e' => self.writer.write([ch as u8]),
242254
_ => {
243255
do char::escape_unicode(ch) |c| {
@@ -274,7 +286,7 @@ impl<'self> TyVisitor for ReprVisitor<'self> {
274286
fn visit_char(&mut self) -> bool {
275287
do self.get::<char> |this, &ch| {
276288
this.writer.write(['\'' as u8]);
277-
this.write_escaped_char(ch);
289+
this.write_escaped_char(ch, false);
278290
this.writer.write(['\'' as u8]);
279291
}
280292
}
@@ -684,6 +696,11 @@ fn test_repr() {
684696
exact_test(&(10u64, ~"hello"),
685697
"(10u64, ~\"hello\")");
686698

699+
exact_test(&'\'', "'\\''");
700+
exact_test(&'"', "'\"'");
701+
exact_test(&("'"), "\"'\"");
702+
exact_test(&("\""), "\"\\\"\"");
703+
687704
exact_test(&println, "fn(&str)");
688705
exact_test(&swap::<int>, "fn(&mut int, &mut int)");
689706
exact_test(&is_alphabetic, "fn(char) -> bool");

0 commit comments

Comments
 (0)