gojay

high performance JSON encoder/decoder with stream API for Golang
git clone git://git.lair.cx/gojay
Log | Files | Refs | README | LICENSE

commit decd89fcdfff5aaaf90781c12c7020a6364393a1
parent 737b8672e52a7ecb717de160eb2739debe56783d
Author: francoispqt <francois@parquet.ninja>
Date:   Sun, 20 May 2018 13:37:55 +0800

add proper encoding of control char

Diffstat:
Mencode_builder.go | 16++++++++++++----
Mencode_string_test.go | 12++++++++++++
2 files changed, 24 insertions(+), 4 deletions(-)

diff --git a/encode_builder.go b/encode_builder.go @@ -1,5 +1,7 @@ package gojay +const hex = "0123456789abcdef" + // grow grows b's capacity, if necessary, to guarantee space for // another n bytes. After grow(n), at least n bytes can be written to b // without another allocation. If n is negative, grow panics. @@ -36,9 +38,14 @@ func (enc *Encoder) writeString(s string) { func (enc *Encoder) writeStringEscape(s string) { l := len(s) for i := 0; i < l; i++ { - switch s[i] { + c := s[i] + if c >= 0x20 && c != '\\' && c != '"' { + enc.writeByte(c) + continue + } + switch c { case '\\', '"': - enc.writeTwoBytes('\\', s[i]) + enc.writeTwoBytes('\\', c) case '\n': enc.writeTwoBytes('\\', 'n') case '\f': @@ -50,8 +57,9 @@ func (enc *Encoder) writeStringEscape(s string) { case '\t': enc.writeTwoBytes('\\', 't') default: - enc.writeByte(s[i]) + enc.writeString(`\u00`) + enc.writeTwoBytes(hex[c>>4], hex[c&0xF]) } + continue } - } diff --git a/encode_string_test.go b/encode_string_test.go @@ -92,6 +92,18 @@ func TestEncoderStringEncodeAPI(t *testing.T) { builder.String(), "Result of marshalling is different as the one expected") }) + t.Run("escaped-control-char", func(t *testing.T) { + str := "\u001b" + builder := &strings.Builder{} + enc := NewEncoder(builder) + err := enc.EncodeString(str) + assert.Nil(t, err, "Error should be nil") + assert.Equal( + t, + `"\u001b"`, + builder.String(), + "Result of marshalling is different as the one expected") + }) t.Run("escaped-sequence3", func(t *testing.T) { str := "hello \f world 𝄞" builder := &strings.Builder{}