zlog/json.go

45 lines
901 B
Go
Raw Normal View History

2017-05-12 05:24:39 +00:00
package zerolog
import "unicode/utf8"
2017-05-12 05:24:39 +00:00
const hex = "0123456789abcdef"
func appendJSONString(dst []byte, s string) []byte {
dst = append(dst, '"')
2017-05-12 05:24:39 +00:00
for i := 0; i < len(s); {
if b := s[i]; b < utf8.RuneSelf {
switch b {
case '"', '\\':
dst = append(dst, '\\', b)
2017-05-12 05:24:39 +00:00
case '\b':
dst = append(dst, '\\', 'b')
2017-05-12 05:24:39 +00:00
case '\f':
dst = append(dst, '\\', 'f')
2017-05-12 05:24:39 +00:00
case '\n':
dst = append(dst, '\\', 'n')
2017-05-12 05:24:39 +00:00
case '\r':
dst = append(dst, '\\', 'r')
2017-05-12 05:24:39 +00:00
case '\t':
dst = append(dst, '\\', 't')
2017-05-12 05:24:39 +00:00
default:
if b >= 0x20 {
dst = append(dst, b)
2017-05-12 05:24:39 +00:00
} else {
dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF])
2017-05-12 05:24:39 +00:00
}
}
i++
continue
}
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
dst = append(dst, `\ufffd`...)
2017-05-12 05:24:39 +00:00
i++
continue
}
dst = append(dst, s[i:i+size]...)
2017-05-12 05:24:39 +00:00
i += size
}
return append(dst, '"')
}