Debian Codegraph @

jsonstring.go

raw
1 package utils
2
3 import (
4 "unicode/utf8"
5
6 "github.com/gofiber/utils/v2/internal/unsafeconv"
7 "github.com/gofiber/utils/v2/swar"
8 )
9
10 // ltLanes, gtLanes, and ampLanes broadcast the HTML-escaped characters to
11 // every lane; quoteLanes and backslashLanes live in ascii.go.
12 const (
13 ltLanes = uint64('<') * swar.Ones
14 gtLanes = uint64('>') * swar.Ones
15 ampLanes = uint64('&') * swar.Ones
16 )
17
18 // jsonHexDigits is the escape alphabet for \u00XX sequences, matching
19 // encoding/json.
20 const jsonHexDigits = "0123456789abcdef"
21
22 // jsonSafeTable flags the ASCII bytes that pass through a JSON string
23 // encoder verbatim: 0x20..0x7E minus '"', '\\', and the HTML-escaped
24 // '<', '>', '&'. Bytes >= 0x80 are false so the scalar loop routes them
25 // to the UTF-8 path.
26 var jsonSafeTable = buildJSONSafeTable()
27
28 func buildJSONSafeTable() [256]bool {
29 var t [256]bool
30 for c := byte(0x20); c < utf8.RuneSelf; c++ {
31 t[c] = c != '"' && c != '\\' && c != '<' && c != '>' && c != '&'
32 }
33 return t
34 }
35
36 // AppendJSONString appends s to dst as a double-quoted JSON string and
37 // returns the extended slice. The output is byte-identical to
38 // encoding/json.Marshal of the same string value, including its default
39 // HTML escaping: '"' and '\\' get backslash escapes; control bytes below
40 // 0x20 become \b, \f, \n, \r, \t, or \u00XX; '<', '>', '&' become \u00XX; each
41 // invalid UTF-8 byte becomes the six literal characters \ufffd; and the
42 // line separators U+2028/U+2029 become the \u2028 and \u2029 escapes.
43 // Go 1.27's json/v2 writes that replacement raw, so for invalid UTF-8 the two
44 // encodings differ from 1.27 on; both still decode to the same string.
45 // All other bytes, including multi-byte UTF-8 sequences, are copied
46 // verbatim. dst must not alias s: the output is longer than the input (at
47 // minimum by the surrounding quotes), so in-place encoding is impossible
48 // and an aliased dst would overwrite bytes before they are read. Clean
49 // spans are located with a SWAR scan and copied wholesale, so typical log
50 // or header values cost one scan and one copy — with none of
51 // encoding/json.Marshal's reflection or allocation.
52 func AppendJSONString[S byteSeq](dst []byte, s S) []byte {
53 bs := unsafeconv.Bytes(s)
54 n := len(bs)
55 dst = append(dst, '"')
56 start, i := 0, 0
57 for i < n {
58 // Skip to the next byte needing attention. Like nonQuotableMask,
59 // the combined mask is exact in and below its first set lane, which
60 // is all this first-match scan consumes.
61 if i+8 <= n {
62 m := jsonUnsafeMask(swar.Load8(bs, i))
63 if m == 0 {
64 i += 8
65 continue
66 }
67 i += swar.FirstLane(m)
68 } else if c := bs[i]; jsonSafeTable[c] {
69 i++
70 continue
71 }
72 c := bs[i]
73 if c < utf8.RuneSelf {
74 dst = append(dst, bs[start:i]...)
75 dst = append(dst, '\\')
76 switch c {
77 case '"', '\\':
78 dst = append(dst, c)
79 case '\b':
80 dst = append(dst, 'b')
81 case '\f':
82 dst = append(dst, 'f')
83 case '\n':
84 dst = append(dst, 'n')
85 case '\r':
86 dst = append(dst, 'r')
87 case '\t':
88 dst = append(dst, 't')
89 default:
90 // Other control bytes and the HTML characters '<', '>', '&'.
91 dst = append(dst, 'u', '0', '0', jsonHexDigits[c>>4], jsonHexDigits[c&0x0F])
92 }
93 i++
94 start = i
95 continue
96 }
97 r, size := utf8.DecodeRune(bs[i:])
98 switch {
99 case r == utf8.RuneError && size == 1:
100 dst = append(dst, bs[start:i]...)
101 dst = append(dst, '\\', 'u', 'f', 'f', 'f', 'd')
102 i++
103 start = i
104 case r == '\u2028' || r == '\u2029':
105 dst = append(dst, bs[start:i]...)
106 dst = append(dst, '\\', 'u', '2', '0', '2', byte('8'+r-'\u2028'))
107 i += size
108 start = i
109 default:
110 i += size
111 }
112 }
113 dst = append(dst, bs[start:]...)
114 return append(dst, '"')
115 }
116
117 // jsonUnsafeMask flags the lanes of w holding bytes a JSON string encoder
118 // cannot copy verbatim: controls below 0x20 (exact range mask), the five
119 // escaped ASCII characters (ZeroLanes needle matches, exact in and below
120 // their first hit), and all bytes >= 0x80, which the caller inspects as
121 // UTF-8.
122 func jsonUnsafeMask(w uint64) uint64 {
123 return swar.MatchRangeMask(w, 0x00, 0x1F) | w&swar.HighBits |
124 swar.ZeroLanes(w^quoteLanes) | swar.ZeroLanes(w^backslashLanes) |
125 swar.ZeroLanes(w^ltLanes) | swar.ZeroLanes(w^gtLanes) | swar.ZeroLanes(w^ampLanes)
126 }