Skip to content

Commit fc30518

Browse files
Escape control characters in JSON output.
1 parent 34d6800 commit fc30518

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/libserialize/json.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -331,21 +331,22 @@ pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError
331331

332332
for (i, byte) in bytes.iter().enumerate() {
333333
let escaped = match *byte {
334-
b'"' => "\\\"",
335-
b'\\' => "\\\\",
336-
b'\x08' => "\\b",
337-
b'\x0c' => "\\f",
338-
b'\n' => "\\n",
339-
b'\r' => "\\r",
340-
b'\t' => "\\t",
334+
b'"' => "\\\"".into_cow(),
335+
b'\\' => "\\\\".into_cow(),
336+
b'\x08' => "\\b".into_cow(),
337+
b'\x0c' => "\\f".into_cow(),
338+
b'\n' => "\\n".into_cow(),
339+
b'\r' => "\\r".into_cow(),
340+
b'\t' => "\\t".into_cow(),
341+
b'\x00'...b'\x1f' | b'\x7f' => format!("\\u00{:0>2x}", *byte).into_cow(),
341342
_ => { continue; }
342343
};
343344

344345
if start < i {
345346
try!(wr.write(bytes[start..i]));
346347
}
347348

348-
try!(wr.write_str(escaped));
349+
try!(wr.write_str(escaped.deref()));
349350

350351
start = i + 1;
351352
}
@@ -2731,6 +2732,9 @@ mod tests {
27312732
fn test_write_char() {
27322733
check_encoder_for_simple!('a', "\"a\"");
27332734
check_encoder_for_simple!('\t', "\"\\t\"");
2735+
check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
2736+
check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
2737+
check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
27342738
check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
27352739
check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
27362740
check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");

0 commit comments

Comments
 (0)