MCPcopy Create free account
hub / github.com/cockroachdb/cockroachdb-parser / encodeJSONString

Function encodeJSONString

pkg/util/json/json.go:852–908  ·  view source on GitHub ↗

encodeJSONString writes a string literal to buf as a JSON string. Cribbed from https://github.com/golang/go/blob/7badae85f20f1bce4cc344f9202447618d45d414/src/encoding/json/encode.go.

(buf *bytes.Buffer, s string)

Source from the content-addressed store, hash-verified

850// encodeJSONString writes a string literal to buf as a JSON string.
851// Cribbed from https://github.com/golang/go/blob/7badae85f20f1bce4cc344f9202447618d45d414/src/encoding/json/encode.go.
852func encodeJSONString(buf *bytes.Buffer, s string) {
853 buf.Grow(len(s) + 2)
854 buf.WriteByte('"')
855 start := 0
856 for i := 0; i < len(s); {
857 if b := s[i]; b < utf8.RuneSelf {
858 if safeSet[b] {
859 i++
860 continue
861 }
862 if start < i {
863 buf.WriteString(s[start:i])
864 }
865 switch b {
866 case '\\', '"':
867 buf.WriteByte('\\')
868 buf.WriteByte(b)
869 case '\n':
870 buf.WriteByte('\\')
871 buf.WriteByte('n')
872 case '\r':
873 buf.WriteByte('\\')
874 buf.WriteByte('r')
875 case '\t':
876 buf.WriteByte('\\')
877 buf.WriteByte('t')
878 default:
879 // This encodes bytes < 0x20 except for \t, \n and \r.
880 // If escapeHTML is set, it also escapes <, >, and &
881 // because they can lead to security holes when
882 // user-controlled strings are rendered into JSON
883 // and served to some browsers.
884 buf.WriteString(`\u00`)
885 buf.WriteByte(hexAlphabet[b>>4])
886 buf.WriteByte(hexAlphabet[b&0xF])
887 }
888 i++
889 start = i
890 continue
891 }
892 c, size := utf8.DecodeRuneInString(s[i:])
893 if c == utf8.RuneError && size == 1 {
894 if start < i {
895 buf.WriteString(s[start:i])
896 }
897 buf.WriteString(`\ufffd`)
898 i += size
899 start = i
900 continue
901 }
902 i += size
903 }
904 if start < len(s) {
905 buf.WriteString(s[start:])
906 }
907 buf.WriteByte('"')
908}
909

Callers 2

FormatMethod · 0.85
FormatMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…