| 1 |
package encoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/binary" |
| 6 |
"math/bits" |
| 7 |
"unsafe" |
| 8 |
) |
| 9 |
|
| 10 |
// The output of a marshaler is compacted and validated, as encoding/json does. Most of the outputs are compact |
| 11 |
// already, so they are copied as they are after being checked: a scan by SIMD finds the bytes which would have |
| 12 |
// to be rewritten or looked at, and a walk of the structure without a write validates the rest, the escapes of |
| 13 |
// the strings included. The characters which compact escapes for HTML are escaped as the output is copied. |
| 14 |
// Anything else is left to compact, which rewrites and reports the errors. |
| 15 |
|
| 16 |
// byteClass is a set of bytes, as a table of the bytes and as the tables of the scan by SIMD. |
| 17 |
type byteClass struct { |
| 18 |
table [256]bool |
| 19 |
tables nibbleTables |
| 20 |
} |
| 21 |
|
| 22 |
func newByteClass(bytes ...byte) *byteClass { |
| 23 |
c := &byteClass{} |
| 24 |
for _, b := range bytes { |
| 25 |
c.table[b] = true |
| 26 |
} |
| 27 |
for b := 0; b < 0x20; b++ { |
| 28 |
c.table[b] = true |
| 29 |
} |
| 30 |
c.tables = newNibbleTables(&c.table) |
| 31 |
return c |
| 32 |
} |
| 33 |
|
| 34 |
// has is whether a byte of src is in the class. |
| 35 |
func (c *byteClass) has(src []byte) bool { |
| 36 |
n := len(src) |
| 37 |
if n == 0 { |
| 38 |
return false |
| 39 |
} |
| 40 |
p := unsafe.Pointer(unsafe.SliceData(src)) |
| 41 |
if found, ok := scanBytesSIMD(p, n, &c.tables); ok { |
| 42 |
return found |
| 43 |
} |
| 44 |
for _, b := range src { |
| 45 |
if c.table[b] { |
| 46 |
return true |
| 47 |
} |
| 48 |
} |
| 49 |
return false |
| 50 |
} |
| 51 |
|
| 52 |
// controlChars are the control characters, which compact removes as white space or reports as errors: an output |
| 53 |
// with one is left to compact. lookedAtByCompact are those and the bytes which the check must look at: an |
| 54 |
// escape, whose sequence is validated, and, if HTML is escaped, the characters which compact escapes then: |
| 55 |
// '<', '>', '&' and the first byte of U+2028 and U+2029, which starts other characters as well. Most of the |
| 56 |
// outputs have none of them: their strings are walked to the next quote at once and they are copied as they are. |
| 57 |
var ( |
| 58 |
controlChars = newByteClass() |
| 59 |
lookedAtByCompact = [2]*byteClass{ |
| 60 |
newByteClass('\\'), |
| 61 |
newByteClass('\\', '<', '>', '&', 0xe2), |
| 62 |
} |
| 63 |
) |
| 64 |
|
| 65 |
// The walks of the strings of an output, as the type argument of isCompactJSON: each walk is compiled into a |
| 66 |
// function of its own, so that the walk of the plain strings, which most of the outputs have, has neither a |
| 67 |
// branch nor a call for the escapes in its loop. The types differ by their sizes, which the compiler knows for |
| 68 |
// each of them: the branch on the size is resolved when the function of a walk is compiled. |
| 69 |
type ( |
| 70 |
// plainStrings have no escape: a string ends at the next quote. |
| 71 |
plainStrings struct{} |
| 72 |
// escapedStrings may have escapes, which are validated. |
| 73 |
escapedStrings struct{ _ byte } |
| 74 |
) |
| 75 |
|
| 76 |
// maxDepthOfCompactCheck is the nesting up to which the output is checked here: a deeper one is compacted. |
| 77 |
const maxDepthOfCompactCheck = 64 |
| 78 |
|
| 79 |
// appendCompactOutput appends src, the output of a marshaler, to dst as compact appends it, if src is compact |
| 80 |
// and valid JSON, and returns false without appending if it may not be: then src is to be compacted. The output |
| 81 |
// of a trusted marshaler, valid and compact, is appended as it is if compact leaves it so. |
| 82 |
func appendCompactOutput(dst, src []byte, escape, trusted bool) ([]byte, bool) { |
| 83 |
if len(src) == 0 { |
| 84 |
return dst, false |
| 85 |
} |
| 86 |
option := 0 |
| 87 |
if escape { |
| 88 |
option = 1 |
| 89 |
} |
| 90 |
if !lookedAtByCompact[option].has(src) { |
| 91 |
if !trusted && !isCompactJSON[plainStrings](src) { |
| 92 |
return dst, false |
| 93 |
} |
| 94 |
return append(dst, src...), true |
| 95 |
} |
| 96 |
if controlChars.has(src) || !isCompactJSON[escapedStrings](src) { |
| 97 |
return dst, false |
| 98 |
} |
| 99 |
if escape { |
| 100 |
return appendHTMLEscaped(dst, src), true |
| 101 |
} |
| 102 |
return append(dst, src...), true |
| 103 |
} |
| 104 |
|
| 105 |
// htmlOfCompact are the bytes which compact escapes for HTML in valid JSON, '<', '>' and '&', and the first byte |
| 106 |
// of U+2028 and U+2029, as a table and as the tables of the loop of the escapes by SIMD, which stops at that byte |
| 107 |
// since it has no sequence ( see escapeSequences ). |
| 108 |
var ( |
| 109 |
htmlOfCompact = [256]bool{'<': true, '>': true, '&': true, 0xe2: true} |
| 110 |
htmlOfCompactTables = newNibbleTables(&htmlOfCompact) |
| 111 |
) |
| 112 |
|
| 113 |
// appendHTMLEscaped appends src, valid JSON, to dst with the characters which compact escapes for HTML escaped as |
| 114 |
// it escapes them. |
| 115 |
func appendHTMLEscaped(dst, src []byte) []byte { |
| 116 |
s := unsafe.String(unsafe.SliceData(src), len(src)) |
| 117 |
n := len(s) |
| 118 |
i, j := 0, 0 |
| 119 |
// limit is where the loop of the bytes gives the rest back to the loop by SIMD, which stops at the first byte |
| 120 |
// of U+2028 and U+2029, as appendNormalizedString does. |
| 121 |
limit := n |
| 122 |
if n >= 32 && hasEscapeLoop { |
| 123 |
dst, j = appendEscapedSIMD(dst, s, &htmlOfCompactTables, false) |
| 124 |
i = j |
| 125 |
limit = min(n, j+32) |
| 126 |
} |
| 127 |
for { |
| 128 |
for j < limit { |
| 129 |
c := s[j] |
| 130 |
if !htmlOfCompact[c] { |
| 131 |
j++ |
| 132 |
continue |
| 133 |
} |
| 134 |
if c == 0xe2 { |
| 135 |
// U+2028 and U+2029 are E2 80 A8 and E2 80 A9. |
| 136 |
if j+2 < n && s[j+1] == 0x80 && s[j+2]&^1 == 0xa8 { |
| 137 |
dst = append(dst, s[i:j]...) |
| 138 |
dst = append(dst, `\u202`...) |
| 139 |
dst = append(dst, hex[s[j+2]&0xf]) |
| 140 |
j += 3 |
| 141 |
i = j |
| 142 |
continue |
| 143 |
} |
| 144 |
j++ |
| 145 |
continue |
| 146 |
} |
| 147 |
dst = append(dst, s[i:j]...) |
| 148 |
seq := escapeSequences[c] |
| 149 |
l := len(dst) |
| 150 |
dst = binary.LittleEndian.AppendUint64(dst, seq)[:l+int(seq>>56)] |
| 151 |
j++ |
| 152 |
i = j |
| 153 |
} |
| 154 |
if j >= n { |
| 155 |
break |
| 156 |
} |
| 157 |
dst = append(dst, s[i:j]...) |
| 158 |
var consumed int |
| 159 |
dst, consumed = appendEscapedSIMD(dst, s[j:], &htmlOfCompactTables, false) |
| 160 |
j += consumed |
| 161 |
i = j |
| 162 |
limit = min(n, j+32) |
| 163 |
} |
| 164 |
return append(dst, s[i:]...) |
| 165 |
} |
| 166 |
|
| 167 |
// isCompactJSON is whether src, which has no control character, is valid JSON without a byte to remove, whose |
| 168 |
// strings are walked as S tells. |
| 169 |
func isCompactJSON[S plainStrings | escapedStrings](src []byte) bool { |
| 170 |
var walk S |
| 171 |
plain := unsafe.Sizeof(walk) == unsafe.Sizeof(plainStrings{}) |
| 172 |
var stack [maxDepthOfCompactCheck]byte // the closing brackets of the values being read |
| 173 |
depth := 0 |
| 174 |
n := len(src) |
| 175 |
i := 0 |
| 176 |
for { |
| 177 |
// a value. |
| 178 |
if i >= n { |
| 179 |
return false |
| 180 |
} |
| 181 |
switch c := src[i]; { |
| 182 |
case c == '"': |
| 183 |
if plain { |
| 184 |
i = quoteEnd(src, i+1) |
| 185 |
} else { |
| 186 |
i = escapedQuoteEnd(src, i+1) |
| 187 |
} |
| 188 |
if i < 0 { |
| 189 |
return false |
| 190 |
} |
| 191 |
case c == '{': |
| 192 |
if depth == maxDepthOfCompactCheck { |
| 193 |
return false |
| 194 |
} |
| 195 |
stack[depth] = '}' |
| 196 |
depth++ |
| 197 |
i++ |
| 198 |
if i < n && src[i] == '}' { |
| 199 |
i++ |
| 200 |
depth-- |
| 201 |
break |
| 202 |
} |
| 203 |
// a key. |
| 204 |
if i >= n || src[i] != '"' { |
| 205 |
return false |
| 206 |
} |
| 207 |
if plain { |
| 208 |
i = quoteEnd(src, i+1) |
| 209 |
} else { |
| 210 |
i = escapedQuoteEnd(src, i+1) |
| 211 |
} |
| 212 |
if i < 0 { |
| 213 |
return false |
| 214 |
} |
| 215 |
if i >= n || src[i] != ':' { |
| 216 |
return false |
| 217 |
} |
| 218 |
i++ |
| 219 |
continue |
| 220 |
case c == '[': |
| 221 |
if depth == maxDepthOfCompactCheck { |
| 222 |
return false |
| 223 |
} |
| 224 |
stack[depth] = ']' |
| 225 |
depth++ |
| 226 |
i++ |
| 227 |
if i < n && src[i] == ']' { |
| 228 |
i++ |
| 229 |
depth-- |
| 230 |
break |
| 231 |
} |
| 232 |
continue |
| 233 |
case c == 't': |
| 234 |
if !bytes.HasPrefix(src[i:], []byte("true")) { |
| 235 |
return false |
| 236 |
} |
| 237 |
i += 4 |
| 238 |
case c == 'f': |
| 239 |
if !bytes.HasPrefix(src[i:], []byte("false")) { |
| 240 |
return false |
| 241 |
} |
| 242 |
i += 5 |
| 243 |
case c == 'n': |
| 244 |
if !bytes.HasPrefix(src[i:], []byte("null")) { |
| 245 |
return false |
| 246 |
} |
| 247 |
i += 4 |
| 248 |
case c == '-' || ('0' <= c && c <= '9'): |
| 249 |
j := numberEnd(src, i) |
| 250 |
if j < 0 { |
| 251 |
return false |
| 252 |
} |
| 253 |
i = j |
| 254 |
default: |
| 255 |
return false |
| 256 |
} |
| 257 |
// after a value. |
| 258 |
for { |
| 259 |
if depth == 0 { |
| 260 |
return i == n |
| 261 |
} |
| 262 |
if i >= n { |
| 263 |
return false |
| 264 |
} |
| 265 |
switch src[i] { |
| 266 |
case ',': |
| 267 |
i++ |
| 268 |
if stack[depth-1] == '}' { |
| 269 |
// a key. |
| 270 |
if i >= n || src[i] != '"' { |
| 271 |
return false |
| 272 |
} |
| 273 |
if plain { |
| 274 |
i = quoteEnd(src, i+1) |
| 275 |
} else { |
| 276 |
i = escapedQuoteEnd(src, i+1) |
| 277 |
} |
| 278 |
if i < 0 { |
| 279 |
return false |
| 280 |
} |
| 281 |
if i >= n || src[i] != ':' { |
| 282 |
return false |
| 283 |
} |
| 284 |
i++ |
| 285 |
} |
| 286 |
case stack[depth-1]: |
| 287 |
depth-- |
| 288 |
i++ |
| 289 |
continue |
| 290 |
default: |
| 291 |
return false |
| 292 |
} |
| 293 |
break |
| 294 |
} |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
// quoteEnd returns the index after the quote which ends the string whose content starts at i, or -1. |
| 299 |
// The string has no escape, so the quote is the next one. Most of the strings are short, so the quote is |
| 300 |
// looked for by words here, not by a call. The words are read as little-endian ones, so that the lowest byte |
| 301 |
// found by bits.TrailingZeros64 is the first one in memory on a big-endian machine too; on a little-endian one |
| 302 |
// the read is a load as it is. |
| 303 |
func quoteEnd(src []byte, i int) int { |
| 304 |
n := len(src) |
| 305 |
p := unsafe.Pointer(unsafe.SliceData(src)) |
| 306 |
for ; i+8 <= n; i += 8 { |
| 307 |
w := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(p, i))[:]) ^ (lsb * '"') |
| 308 |
if mask := (w - lsb) &^ w & msb; mask != 0 { |
| 309 |
return i + bits.TrailingZeros64(mask)/8 + 1 |
| 310 |
} |
| 311 |
} |
| 312 |
for ; i < n; i++ { |
| 313 |
if src[i] == '"' { |
| 314 |
return i + 1 |
| 315 |
} |
| 316 |
} |
| 317 |
return -1 |
| 318 |
} |
| 319 |
|
| 320 |
// escapedQuoteEnd is quoteEnd for a string which may have escapes, which are validated. |
| 321 |
func escapedQuoteEnd(src []byte, i int) int { |
| 322 |
n := len(src) |
| 323 |
p := unsafe.Pointer(unsafe.SliceData(src)) |
| 324 |
for { |
| 325 |
for ; i+8 <= n; i += 8 { |
| 326 |
w := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(p, i))[:]) |
| 327 |
q := w ^ (lsb * '"') |
| 328 |
b := w ^ (lsb * '\\') |
| 329 |
// the lowest bit of the mask of each byte is exact, so the lowest one of both is. |
| 330 |
if mask := ((q-lsb)&^q | (b-lsb)&^b) & msb; mask != 0 { |
| 331 |
i += bits.TrailingZeros64(mask) / 8 |
| 332 |
break |
| 333 |
} |
| 334 |
} |
| 335 |
for ; i < n && src[i] != '"' && src[i] != '\\'; i++ { |
| 336 |
} |
| 337 |
if i >= n { |
| 338 |
return -1 |
| 339 |
} |
| 340 |
if src[i] == '"' { |
| 341 |
return i + 1 |
| 342 |
} |
| 343 |
i = escapeEnd(src, i+1) |
| 344 |
if i < 0 { |
| 345 |
return -1 |
| 346 |
} |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
// escapeEnd returns the index after the escape of a string whose backslash is before i, or -1 if it is not an |
| 351 |
// escape of JSON. |
| 352 |
func escapeEnd(src []byte, i int) int { |
| 353 |
if i >= len(src) { |
| 354 |
return -1 |
| 355 |
} |
| 356 |
switch src[i] { |
| 357 |
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': |
| 358 |
return i + 1 |
| 359 |
case 'u': |
| 360 |
if i+5 > len(src) { |
| 361 |
return -1 |
| 362 |
} |
| 363 |
for _, c := range src[i+1 : i+5] { |
| 364 |
if !('0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F') { |
| 365 |
return -1 |
| 366 |
} |
| 367 |
} |
| 368 |
return i + 5 |
| 369 |
} |
| 370 |
return -1 |
| 371 |
} |
| 372 |
|
| 373 |
// numberEnd returns the index after the number which starts at i, or -1 if it is not a number of JSON. |
| 374 |
func numberEnd(src []byte, i int) int { |
| 375 |
n := len(src) |
| 376 |
if src[i] == '-' { |
| 377 |
i++ |
| 378 |
if i >= n { |
| 379 |
return -1 |
| 380 |
} |
| 381 |
} |
| 382 |
switch { |
| 383 |
case src[i] == '0': |
| 384 |
i++ |
| 385 |
case '1' <= src[i] && src[i] <= '9': |
| 386 |
i++ |
| 387 |
for i < n && '0' <= src[i] && src[i] <= '9' { |
| 388 |
i++ |
| 389 |
} |
| 390 |
default: |
| 391 |
return -1 |
| 392 |
} |
| 393 |
if i < n && src[i] == '.' { |
| 394 |
i++ |
| 395 |
if i >= n || src[i] < '0' || src[i] > '9' { |
| 396 |
return -1 |
| 397 |
} |
| 398 |
for i < n && '0' <= src[i] && src[i] <= '9' { |
| 399 |
i++ |
| 400 |
} |
| 401 |
} |
| 402 |
if i < n && (src[i] == 'e' || src[i] == 'E') { |
| 403 |
i++ |
| 404 |
if i < n && (src[i] == '+' || src[i] == '-') { |
| 405 |
i++ |
| 406 |
} |
| 407 |
if i >= n || src[i] < '0' || src[i] > '9' { |
| 408 |
return -1 |
| 409 |
} |
| 410 |
for i < n && '0' <= src[i] && src[i] <= '9' { |
| 411 |
i++ |
| 412 |
} |
| 413 |
} |
| 414 |
return i |
| 415 |
} |