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 // All other bytes, including multi-byte UTF-8 sequences, are copied
44 // verbatim. dst must not alias s: the output is longer than the input (at
45 // minimum by the surrounding quotes), so in-place encoding is impossible
46 // and an aliased dst would overwrite bytes before they are read. Clean
47 // spans are located with a SWAR scan and copied wholesale, so typical log
48 // or header values cost one scan and one copy — with none of
49 // encoding/json.Marshal's reflection or allocation.
50 func AppendJSONString[S byteSeq](dst []byte, s S) []byte {
51 bs := unsafeconv.Bytes(s)
52 n := len(bs)
53 dst = append(dst, '"')
54 start, i := 0, 0
55 for i < n {
56 // Skip to the next byte needing attention. Like nonQuotableMask,
57 // the combined mask is exact in and below its first set lane, which
58 // is all this first-match scan consumes.
59 if i+8 <= n {
60 m := jsonUnsafeMask(swar.Load8(bs, i))
61 if m == 0 {
62 i += 8
63 continue
64 }
65 i += swar.FirstLane(m)
66 } else if c := bs[i]; jsonSafeTable[c] {
67 i++
68 continue
69 }
70 c := bs[i]
71 if c < utf8.RuneSelf {
72 dst = append(dst, bs[start:i]...)
73 dst = append(dst, '\\')
74 switch c {
75 case '"', '\\':
76 dst = append(dst, c)
77 case '\b':
78 dst = append(dst, 'b')
79 case '\f':
80 dst = append(dst, 'f')
81 case '\n':
82 dst = append(dst, 'n')
83 case '\r':
84 dst = append(dst, 'r')
85 case '\t':
86 dst = append(dst, 't')
87 default:
88 // Other control bytes and the HTML characters '<', '>', '&'.
89 dst = append(dst, 'u', '0', '0', jsonHexDigits[c>>4], jsonHexDigits[c&0x0F])
90 }
91 i++
92 start = i
93 continue
94 }
95 r, size := utf8.DecodeRune(bs[i:])
96 switch {
97 case r == utf8.RuneError && size == 1:
98 dst = append(dst, bs[start:i]...)
99 dst = append(dst, '\\', 'u', 'f', 'f', 'f', 'd')
100 i++
101 start = i
102 case r == '\u2028' || r == '\u2029':
103 dst = append(dst, bs[start:i]...)
104 dst = append(dst, '\\', 'u', '2', '0', '2', byte('8'+r-'\u2028'))
105 i += size
106 start = i
107 default:
108 i += size
109 }
110 }
111 dst = append(dst, bs[start:]...)
112 return append(dst, '"')
113 }
114
115 // jsonUnsafeMask flags the lanes of w holding bytes a JSON string encoder
116 // cannot copy verbatim: controls below 0x20 (exact range mask), the five
117 // escaped ASCII characters (ZeroLanes needle matches, exact in and below
118 // their first hit), and all bytes >= 0x80, which the caller inspects as
119 // UTF-8.
120 func jsonUnsafeMask(w uint64) uint64 {
121 return swar.MatchRangeMask(w, 0x00, 0x1F) | w&swar.HighBits |
122 swar.ZeroLanes(w^quoteLanes) | swar.ZeroLanes(w^backslashLanes) |
123 swar.ZeroLanes(w^ltLanes) | swar.ZeroLanes(w^gtLanes) | swar.ZeroLanes(w^ampLanes)
124 }