Skip to content

Commit 656593a

Browse files
committed
Updated escapeString to be compatible with RFC4627
and `encoding/json` from standard library
1 parent 93f67d9 commit 656593a

File tree

1 file changed

+26
-19
lines changed

1 file changed

+26
-19
lines changed

parser.go

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -267,28 +267,35 @@ func parseObject(s string, c *cache, depth int) (*Value, string, error) {
267267
}
268268

269269
func escapeString(dst []byte, s string) []byte {
270-
if !hasSpecialChars(s) {
271-
// Fast path - nothing to escape.
272-
dst = append(dst, '"')
273-
dst = append(dst, s...)
274-
dst = append(dst, '"')
275-
return dst
276-
}
277-
278-
// Slow path.
279-
return strconv.AppendQuote(dst, s)
280-
}
281-
282-
func hasSpecialChars(s string) bool {
283-
if strings.IndexByte(s, '"') >= 0 || strings.IndexByte(s, '\\') >= 0 {
284-
return true
285-
}
286270
for i := 0; i < len(s); i++ {
287-
if s[i] < 0x20 {
288-
return true
271+
c := s[i]
272+
switch {
273+
case c == 0x22:
274+
// quotation mark
275+
dst = append(dst, []byte{92, 34}...)
276+
case c == 0x5c:
277+
// reverse solidus
278+
dst = append(dst, []byte{92, 92}...)
279+
case c >= 0x20:
280+
// default, rest are control chars
281+
dst = append(dst, c)
282+
case c < 0x09:
283+
dst = append(dst, []byte{92, 117, 48, 48, 48 + c, 48}...)
284+
case c == 0x09:
285+
dst = append(dst, []byte{92, 116}...)
286+
case c == 0x0a:
287+
dst = append(dst, []byte{92, 110}...)
288+
case c == 0x0d:
289+
dst = append(dst, []byte{92, 114}...)
290+
case c < 0x10:
291+
dst = append(dst, []byte{92, 117, 48, 48, 87 + c, 48}...)
292+
case c < 0x1a:
293+
dst = append(dst, []byte{92, 117, 48, 49, 32 + c, 48}...)
294+
case c < 0x20:
295+
dst = append(dst, []byte{92, 117, 48, 49, 71 + c, 48}...)
289296
}
290297
}
291-
return false
298+
return dst
292299
}
293300

294301
func unescapeStringBestEffort(s string) string {

0 commit comments

Comments
 (0)