Skip to content

Commit

Permalink
add proper encoding of control char
Browse files Browse the repository at this point in the history
  • Loading branch information
francoispqt committed May 20, 2018
1 parent 737b867 commit decd89f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
16 changes: 12 additions & 4 deletions 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.
Expand Down Expand Up @@ -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':
Expand All @@ -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
}

}
12 changes: 12 additions & 0 deletions encode_string_test.go
Expand Up @@ -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{}
Expand Down

0 comments on commit decd89f

Please sign in to comment.