Skip to content

Commit 55cc618

Browse files
committed
Correctly escape ASCII control characters in strings
This patch escapes ASCII control characters in the range 0x00...0x1f, in accordance with the JSON spec. Fixes #58
1 parent 7bc9b0a commit 55cc618

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

json/src/ser.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,7 @@ pub fn escape_bytes<W>(wr: &mut W, bytes: &[u8]) -> Result<()>
504504
b'\n' => b"\\n",
505505
b'\r' => b"\\r",
506506
b'\t' => b"\\t",
507+
b'\x00' ... b'\x1F' => b"\\u",
507508
_ => { continue; }
508509
};
509510

@@ -512,6 +513,9 @@ pub fn escape_bytes<W>(wr: &mut W, bytes: &[u8]) -> Result<()>
512513
}
513514

514515
try!(wr.write_all(escaped));
516+
if escaped[1] == b'u' {
517+
try!(write!(wr, "{:04x}", *byte));
518+
}
515519

516520
start = i + 1;
517521
}

json_tests/tests/test_json.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,7 @@ fn test_write_object() {
461461

462462
let complex_obj = Value::Object(treemap!(
463463
"b".to_string() => Value::Array(vec![
464-
Value::Object(treemap!("c".to_string() => Value::String("\x0c\r".to_string()))),
464+
Value::Object(treemap!("c".to_string() => Value::String("\x0c\x1f\r".to_string()))),
465465
Value::Object(treemap!("d".to_string() => Value::String("".to_string())))
466466
])
467467
));
@@ -471,7 +471,7 @@ fn test_write_object() {
471471
complex_obj.clone(),
472472
"{\
473473
\"b\":[\
474-
{\"c\":\"\\f\\r\"},\
474+
{\"c\":\"\\f\\u001f\\r\"},\
475475
{\"d\":\"\"}\
476476
]\
477477
}"
@@ -485,7 +485,7 @@ fn test_write_object() {
485485
"{\n",
486486
" \"b\": [\n",
487487
" {\n",
488-
" \"c\": \"\\f\\r\"\n",
488+
" \"c\": \"\\f\\u001f\\r\"\n",
489489
" },\n",
490490
" {\n",
491491
" \"d\": \"\"\n",

0 commit comments

Comments
 (0)