Skip to content

Commit 187ecf2

Browse files
authored
fix encoding of control characters (#117)
These use hex, per json.org.
1 parent bc49ad8 commit 187ecf2

File tree

2 files changed

+13
-15
lines changed

2 files changed

+13
-15
lines changed

json_serialization/writer.nim

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -419,25 +419,20 @@ proc writeValue*[V: not void](w: var JsonWriter, value: V) {.raises: [IOError].}
419419
template addPrefixSlash(c) =
420420
s.write '\\'
421421
s.write c
422-
422+
const hexChars = "0123456789abcde"
423423
for c in value:
424424
case c
425-
of '\L': addPrefixSlash 'n'
426-
of '\b': addPrefixSlash 'b'
427-
of '\f': addPrefixSlash 'f'
428-
of '\t': addPrefixSlash 't'
429-
of '\r': addPrefixSlash 'r'
425+
of '\b': addPrefixSlash 'b' # \x08
426+
of '\t': addPrefixSlash 't' # \x09
427+
of '\n': addPrefixSlash 'n' # \x0a
428+
of '\f': addPrefixSlash 'f' # \x0c
429+
of '\r': addPrefixSlash 'r' # \x0d
430430
of '"' : addPrefixSlash '\"'
431-
of '\0'..'\7':
432-
s.write "\\u000"
433-
s.write char(ord('0') + ord(c))
434-
of '\14'..'\31':
431+
of '\x00'..'\x07', '\x0b', '\x0e'..'\x1f':
435432
s.write "\\u00"
436-
# TODO: Should this really use a decimal representation?
437-
# Or perhaps $ord(c) returns hex?
438-
# This is potentially a bug in Nim's json module.
439-
s.write $ord(c)
440-
of '\\': addPrefixSlash '\\'
433+
s.write hexChars[(uint8(c) shr 4) and 0x0f]
434+
s.write hexChars[uint8(c) and 0x0f]
435+
441436
else: s.write c
442437

443438
s.write '"'

tests/test_writer.nim

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,6 @@ suite "Test writer":
290290
checkExp("0.0E+1", "0.0e1")
291291
checkExp("+0.1e+2", "0.1e2")
292292
checkExp("-0.2e+9", "-0.2e9")
293+
294+
test "escapes":
295+
check Json.encode("\x12") == """"\u0012""""

0 commit comments

Comments
 (0)