Debian Codegraph @

escape.go

raw symbols SCIP
1 // SYS-REQ-014, SYS-REQ-060, SYS-REQ-061, SYS-REQ-062, SYS-REQ-063: string escape and Unicode handling
2 package jsonparser
3
4 import (
5 "bytes"
6 "unicode/utf8"
7 )
8
9 // JSON Unicode stuff: see https://tools.ietf.org/html/rfc7159#section-7
10
11 const supplementalPlanesOffset = 0x10000
12 const highSurrogateOffset = 0xD800
13 const lowSurrogateOffset = 0xDC00
14
15 const basicMultilingualPlaneReservedOffset = 0xDFFF
16 const basicMultilingualPlaneOffset = 0xFFFF
17
18 func combineUTF16Surrogates(high, low rune) rune {
19 return supplementalPlanesOffset + (high-highSurrogateOffset)<<10 + (low - lowSurrogateOffset)
20 }
21
22 const badHex = -1
23
24 func h2I(c byte) int {
25 switch {
26 case c >= '0' && c <= '9':
27 return int(c - '0')
28 case c >= 'A' && c <= 'F':
29 return int(c - 'A' + 10)
30 case c >= 'a' && c <= 'f':
31 return int(c - 'a' + 10)
32 }
33 return badHex
34 }
35
36 // decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and
37 // is not checked.
38 // In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together.
39 // This function only handles one; decodeUnicodeEscape handles this more complex case.
40 func decodeSingleUnicodeEscape(in []byte) (rune, bool) {
41 // We need at least 6 characters total
42 if len(in) < 6 {
43 return utf8.RuneError, false
44 }
45
46 // Convert hex to decimal
47 h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5])
48 if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {
49 return utf8.RuneError, false
50 }
51
52 // Compose the hex digits
53 return rune(h1<<12 + h2<<8 + h3<<4 + h4), true
54 }
55
56 // isUTF16EncodedRune checks if a rune is in the range for non-BMP characters,
57 // which is used to describe UTF16 chars.
58 // Source: https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
59 func isUTF16EncodedRune(r rune) bool {
60 return highSurrogateOffset <= r && r <= basicMultilingualPlaneReservedOffset
61 }
62
63 func decodeUnicodeEscape(in []byte) (rune, int) {
64 if r, ok := decodeSingleUnicodeEscape(in); !ok {
65 // Invalid Unicode escape
66 return utf8.RuneError, -1
67 } else if !isUTF16EncodedRune(r) {
68 // Valid Unicode escape in Basic Multilingual Plane.
69 // Note: a single \uXXXX escape produces r in [0, 0xFFFF], so r is always
70 // within the BMP. The former r <= basicMultilingualPlaneOffset guard was
71 // tautological and has been removed — the real discriminator is whether r
72 // falls in the UTF-16 surrogate range.
73 return r, 6
74 } else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok { // Note: previous decodeSingleUnicodeEscape success guarantees at least 6 bytes remain
75 // UTF16 "high surrogate" without manditory valid following Unicode escape for the "low surrogate"
76 return utf8.RuneError, -1
77 } else if r2 < lowSurrogateOffset {
78 // Invalid UTF16 "low surrogate"
79 return utf8.RuneError, -1
80 } else {
81 // Valid UTF16 surrogate pair
82 return combineUTF16Surrogates(r, r2), 12
83 }
84 }
85
86 // backslashCharEscapeTable: when '\X' is found for some byte X, it is to be replaced with backslashCharEscapeTable[X]
87 var backslashCharEscapeTable = [...]byte{
88 '"': '"',
89 '\\': '\\',
90 '/': '/',
91 'b': '\b',
92 'f': '\f',
93 'n': '\n',
94 'r': '\r',
95 't': '\t',
96 }
97
98 // unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns
99 // how many characters were consumed from 'in' and emitted into 'out'.
100 // If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error.
101 func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
102 if len(in) < 2 || in[0] != '\\' {
103 // Invalid escape due to insufficient characters for any escape or no initial backslash
104 return -1, -1
105 }
106
107 // https://tools.ietf.org/html/rfc7159#section-7
108 switch e := in[1]; e {
109 case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
110 // Valid basic 2-character escapes (use lookup table)
111 out[0] = backslashCharEscapeTable[e]
112 return 2, 1
113 case 'u':
114 // Unicode escape
115 if r, inLen := decodeUnicodeEscape(in); inLen == -1 {
116 // Invalid Unicode escape
117 return -1, -1
118 } else {
119 // Valid Unicode escape; re-encode as UTF8
120 outLen := utf8.EncodeRune(out, r)
121 return inLen, outLen
122 }
123 }
124
125 return -1, -1
126 }
127
128 // unescape unescapes the string contained in 'in' and returns it as a slice.
129 // If 'in' contains no escaped characters:
130 // Returns 'in'.
131 // Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)):
132 // 'out' is used to build the unescaped string and is returned with no extra allocation
133 // Else:
134 // A new slice is allocated and returned.
135 func Unescape(in, out []byte) ([]byte, error) {
136 firstBackslash := bytes.IndexByte(in, '\\')
137 if firstBackslash == -1 {
138 return in, nil
139 }
140
141 // Get a buffer of sufficient size (allocate if needed)
142 if cap(out) < len(in) {
143 out = make([]byte, len(in))
144 } else {
145 out = out[0:len(in)]
146 }
147
148 // Copy the first sequence of unescaped bytes to the output and obtain a buffer pointer (subslice)
149 copy(out, in[:firstBackslash])
150 in = in[firstBackslash:]
151 buf := out[firstBackslash:]
152
153 // The loop always exits via break: either on error (MalformedStringEscapeError)
154 // or after copying the final non-escaped tail. The former `for len(in) > 0`
155 // guard was structurally always true on re-entry since the else branch always
156 // leaves at least the backslash character in `in`.
157 for {
158 // Unescape the next escaped character
159 inLen, bufLen := unescapeToUTF8(in, buf)
160 if inLen == -1 {
161 return nil, MalformedStringEscapeError
162 }
163
164 in = in[inLen:]
165 buf = buf[bufLen:]
166
167 // Copy everything up until the next backslash
168 nextBackslash := bytes.IndexByte(in, '\\')
169 if nextBackslash == -1 {
170 copy(buf, in)
171 buf = buf[len(in):]
172 break
173 } else {
174 copy(buf, in[:nextBackslash])
175 buf = buf[nextBackslash:]
176 in = in[nextBackslash:]
177 }
178 }
179
180 // Trim the out buffer to the amount that was actually emitted
181 return out[:len(out)-len(buf)], nil
182 }