Debian Codegraph @

internal/encoder/string.go

raw
1 // This files's string processing codes are inspired by https://github.com/segmentio/encoding.
2 // The license notation is as follows.
3 //
4 // # MIT License
5 //
6 // Copyright (c) 2019 Segment.io, Inc.
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a copy
9 // of this software and associated documentation files (the "Software"), to deal
10 // in the Software without restriction, including without limitation the rights
11 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 // copies of the Software, and to permit persons to whom the Software is
13 // furnished to do so, subject to the following conditions:
14 //
15 // The above copyright notice and this permission notice shall be included in all
16 // copies or substantial portions of the Software.
17 //
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 // SOFTWARE.
25 package encoder
26
27 import (
28 "encoding/binary"
29 "math/bits"
30 "unicode/utf8"
31 "unsafe"
32 )
33
34 const (
35 lsb = 0x0101010101010101
36 msb = 0x8080808080808080
37 )
38
39 var hex = "0123456789abcdef"
40
41 // stringEscape is what decides whether a string has a byte to escape, for a combination of the options.
42 type stringEscape struct {
43 // chars are three characters to escape in addition to the control characters, '"' and '\\',
44 // repeated in every byte of a word. They are '<', '>' and '&', or '"' for nothing more.
45 chars [3]uint64
46 // high is msb if a byte which is not ASCII is to be looked at, to normalize UTF-8, or 0.
47 high uint64
48 // table is whether a byte may need an escape.
49 table *[256]bool
50 // tables is table as the tables of the scan by SIMD.
51 tables nibbleTables
52 // appendEscaped appends a string which may have a byte to escape.
53 appendEscaped func(buf []byte, s string) []byte
54 }
55
56 const (
57 stringEscapeNormalize = 1 << iota
58 stringEscapeHTML
59 )
60
61 // stringEscapes is indexed by the combination of stringEscapeNormalize and stringEscapeHTML.
62 var stringEscapes = [4]stringEscape{
63 0: {
64 chars: [3]uint64{lsb * '"', lsb * '"', lsb * '"'},
65 table: &needEscape,
66 appendEscaped: appendString,
67 },
68 stringEscapeNormalize: {
69 chars: [3]uint64{lsb * '"', lsb * '"', lsb * '"'},
70 high: msb,
71 table: &needEscapeNormalizeUTF8,
72 appendEscaped: appendNormalizedString,
73 },
74 stringEscapeHTML: {
75 chars: [3]uint64{lsb * '<', lsb * '>', lsb * '&'},
76 table: &needEscapeHTML,
77 appendEscaped: appendHTMLString,
78 },
79 stringEscapeHTML | stringEscapeNormalize: {
80 chars: [3]uint64{lsb * '<', lsb * '>', lsb * '&'},
81 high: msb,
82 table: &needEscapeHTMLNormalizeUTF8,
83 appendEscaped: appendNormalizedHTMLString,
84 },
85 }
86
87 // escapeSequences are the escapes of the bytes which the loop of the escapes by SIMD writes ( see
88 // appendEscapedSIMD ): the bytes of the escape of a byte, in the order of a little-endian word, and its length in
89 // the top byte. They are the ones of the appendString functions. A byte which is not ASCII is 0: it is left to
90 // the caller, which escapes it if UTF-8 is normalized.
91 var escapeSequences = func() [256]uint64 {
92 var seqs [256]uint64
93 for c := 0; c < 0x80; c++ {
94 var seq string
95 switch c {
96 case '"', '\\':
97 seq = string([]byte{'\\', byte(c)})
98 case '\n':
99 seq = `\n`
100 case '\r':
101 seq = `\r`
102 case '\t':
103 seq = `\t`
104 case '\b':
105 seq = backspaceEscape
106 case '\f':
107 seq = formFeedEscape
108 case '<', '>', '&':
109 seq = `\u00` + string([]byte{hex[c>>4], hex[c&0xF]})
110 default:
111 if c < 0x20 {
112 seq = `\u00` + string([]byte{hex[c>>4], hex[c&0xF]})
113 }
114 }
115 var w uint64
116 for i := len(seq) - 1; i >= 0; i-- {
117 w = w<<8 | uint64(seq[i])
118 }
119 seqs[c] = w | uint64(len(seq))<<56
120 }
121 return seqs
122 }()
123
124 // escapeTables are the tables of stringEscapes, which the functions of the escapes refer to by this array:
125 // stringEscapes refers to the functions, so they can't refer to it.
126 var escapeTables [4]*nibbleTables
127
128 func init() {
129 for i := range stringEscapes {
130 stringEscapes[i].tables = newNibbleTables(stringEscapes[i].table)
131 escapeTables[i] = &stringEscapes[i].tables
132 }
133 }
134
135 // The functions below return the mask of the bytes of a word which may need an escape: the most significant bit
136 // of such a byte is set. A byte after one to escape may be set too, because of the borrow of the subtractions.
137 // A mask is made of parts, each of which is small enough to be inlined: a call for every word costs more than
138 // the mask itself.
139 //
140 // `x - lsb` sets the most significant bit of a byte of x which is zero, and of one which already has it.
141 // If UTF-8 is normalized, a byte which is not ASCII is looked at anyway, so the latter doesn't matter and the
142 // loose masks are enough. Otherwise `&^ x` leaves only the former, so that a string which is not ASCII is not
143 // taken for one to escape.
144
145 // looseCommonMask is the mask of the control characters, '"', '\\' and the bytes which are not ASCII.
146 func looseCommonMask(n uint64) uint64 {
147 return n | (n - lsb*0x20) | ((n ^ (lsb * '"')) - lsb) | ((n ^ (lsb * '\\')) - lsb)
148 }
149
150 // looseCharsMask is the mask of chars, and of the bytes which are not ASCII.
151 func (e *stringEscape) looseCharsMask(n uint64) uint64 {
152 return ((n ^ e.chars[0]) - lsb) | ((n ^ e.chars[1]) - lsb) | ((n ^ e.chars[2]) - lsb)
153 }
154
155 // exactCommonMask is the mask of the control characters, '"' and '\\'.
156 func exactCommonMask(n uint64) uint64 {
157 quote := n ^ (lsb * '"')
158 backslash := n ^ (lsb * '\\')
159 return ((n - lsb*0x20) &^ n) | ((quote - lsb) &^ quote) | ((backslash - lsb) &^ backslash)
160 }
161
162 // exactCharsMask is the mask of chars.
163 func (e *stringEscape) exactCharsMask(n uint64) uint64 {
164 c0, c1, c2 := n^e.chars[0], n^e.chars[1], n^e.chars[2]
165 return ((c0 - lsb) &^ c0) | ((c1 - lsb) &^ c1) | ((c2 - lsb) &^ c2)
166 }
167
168 // hasExactEscape is whether a word of the string has a byte to escape, not counting the bytes which are not
169 // ASCII. The string is 8 bytes or longer.
170 func (e *stringEscape) hasExactEscape(src unsafe.Pointer, n int) bool {
171 i := 0
172 for ; i+8 <= n; i += 8 {
173 if w := *(*uint64)(unsafe.Add(src, i)); (exactCommonMask(w)|e.exactCharsMask(w))&msb != 0 {
174 return true
175 }
176 }
177 if i < n {
178 w := *(*uint64)(unsafe.Add(src, n-8))
179 return (exactCommonMask(w)|e.exactCharsMask(w))&msb != 0
180 }
181 return false
182 }
183
184 // hasLooseEscape is whether a word of the string may have a byte to escape, or has a byte which is not ASCII.
185 // The string is 8 bytes or longer. It is cheaper than hasExactEscape, and it is exact for a string of ASCII,
186 // which most of the strings are.
187 func (e *stringEscape) hasLooseEscape(src unsafe.Pointer, n int) bool {
188 i := 0
189 for ; i+8 <= n; i += 8 {
190 if w := *(*uint64)(unsafe.Add(src, i)); (looseCommonMask(w)|e.looseCharsMask(w))&msb != 0 {
191 return true
192 }
193 }
194 if i < n {
195 // the last word overlaps the previous one.
196 w := *(*uint64)(unsafe.Add(src, n-8))
197 return (looseCommonMask(w)|e.looseCharsMask(w))&msb != 0
198 }
199 return false
200 }
201
202 // maxInlineCopySize is the size of the longest string which is copied without calling memmove.
203 const maxInlineCopySize = 16
204
205 // growForString returns buf which has the capacity to append n bytes, growing as append does.
206 //
207 //go:noinline
208 func growForString(buf []byte, n int) []byte {
209 grown := make([]byte, len(buf), 2*cap(buf)+n)
210 copy(grown, buf)
211 return grown
212 }
213
214 // AppendString appends the string as a JSON string.
215 //
216 // Most of the strings have nothing to escape and are short, so that case is handled here. A string of up to
217 // maxOnePassLength bytes is looked at and written to the capacity of the buffer in one pass, by bytes, by the
218 // halves of a word or by words, and nothing is called; a longer one is looked at by SIMD ( or by words ) and
219 // then copied. A string which may have a byte to escape is left to the function for the options, and what was
220 // written for it is left out of the buffer.
221 func AppendString(ctx *RuntimeContext, buf []byte, s string) []byte {
222 n := len(s)
223 if n == 0 {
224 // no byte to escape: the options are not looked at.
225 return append(buf, '"', '"')
226 }
227 index := 0
228 if ctx.Option.Flag&HTMLEscapeOption != 0 {
229 index = stringEscapeHTML
230 }
231 if ctx.Option.Flag&NormalizeUTF8Option != 0 {
232 index |= stringEscapeNormalize
233 }
234 escape := &stringEscapes[index]
235
236 src := unsafe.Pointer(unsafe.StringData(s))
237 if n < 4 {
238 table := escape.table
239 for i := 0; i < n; i++ {
240 if table[*(*byte)(unsafe.Add(src, i))] {
241 return escape.appendEscaped(buf, s)
242 }
243 }
244 if l := len(buf); cap(buf)-l >= n+2 {
245 // the first, the middle and the last byte are every byte of 1 to 3 bytes.
246 buf = buf[:l+n+2]
247 p := unsafe.Pointer(unsafe.SliceData(buf))
248 *(*byte)(unsafe.Add(p, l)) = '"'
249 *(*byte)(unsafe.Add(p, l+1)) = *(*byte)(src)
250 *(*byte)(unsafe.Add(p, l+1+(n>>1))) = *(*byte)(unsafe.Add(src, n>>1))
251 *(*byte)(unsafe.Add(p, l+n)) = *(*byte)(unsafe.Add(src, n-1))
252 *(*byte)(unsafe.Add(p, l+n+1)) = '"'
253 return buf
254 }
255 } else if n < 8 {
256 // the two halves overlap, so that the word has every byte of the string and nothing else.
257 w := uint64(*(*uint32)(src)) | uint64(*(*uint32)(unsafe.Add(src, n-4)))<<32
258 if (looseCommonMask(w)|escape.looseCharsMask(w))&msb != 0 &&
259 (escape.high != 0 || (exactCommonMask(w)|escape.exactCharsMask(w))&msb != 0) {
260 return escape.appendEscaped(buf, s)
261 }
262 if l := len(buf); cap(buf)-l >= n+2 {
263 // the halves of the word are written where they were read from.
264 buf = buf[:l+n+2]
265 p := unsafe.Pointer(unsafe.SliceData(buf))
266 *(*byte)(unsafe.Add(p, l)) = '"'
267 *(*uint32)(unsafe.Add(p, l+1)) = uint32(w)
268 *(*uint32)(unsafe.Add(p, l+n-3)) = uint32(w >> 32)
269 *(*byte)(unsafe.Add(p, l+n+1)) = '"'
270 return buf
271 }
272 } else if l := len(buf); n <= maxOnePassLength && cap(buf)-l >= n+2 {
273 // the first and the last word and the ones between them, which overlap: 8 to maxOnePassLength bytes, 31
274 // at most, are 2 to 4 words. A buffer without the capacity is grown below.
275 dst := unsafe.Add(unsafe.Pointer(unsafe.SliceData(buf)), l+1)
276 first, last := *(*uint64)(src), *(*uint64)(unsafe.Add(src, n-8))
277 *(*uint64)(dst) = first
278 *(*uint64)(unsafe.Add(dst, n-8)) = last
279 mask := looseCommonMask(first) | escape.looseCharsMask(first) | looseCommonMask(last) | escape.looseCharsMask(last)
280 if n > 16 {
281 w := *(*uint64)(unsafe.Add(src, 8))
282 *(*uint64)(unsafe.Add(dst, 8)) = w
283 mask |= looseCommonMask(w) | escape.looseCharsMask(w)
284 if n > 24 {
285 w := *(*uint64)(unsafe.Add(src, 16))
286 *(*uint64)(unsafe.Add(dst, 16)) = w
287 mask |= looseCommonMask(w) | escape.looseCharsMask(w)
288 }
289 }
290 if mask&msb != 0 && (escape.high != 0 || escape.hasExactEscape(src, n)) {
291 // a byte which is not ASCII is to be looked at only if UTF-8 is normalized.
292 return escape.appendEscaped(buf, s)
293 }
294 // the position is taken from buf again, which is kept across the call above, so that nothing more is.
295 l := len(buf)
296 buf = buf[:l+n+2]
297 p := unsafe.Pointer(unsafe.SliceData(buf))
298 *(*byte)(unsafe.Add(p, l)) = '"'
299 *(*byte)(unsafe.Add(p, l+n+1)) = '"'
300 return buf
301 } else if found, ok := scanBytesSIMD(src, n, &escape.tables); ok {
302 if found {
303 return escape.appendEscaped(buf, s)
304 }
305 } else if escape.hasLooseEscape(src, n) && (escape.high != 0 || escape.hasExactEscape(src, n)) {
306 // a byte which is not ASCII is to be looked at only if UTF-8 is normalized.
307 return escape.appendEscaped(buf, s)
308 }
309
310 l := len(buf)
311 if cap(buf)-l < n+2 {
312 buf = growForString(buf, n+2)
313 }
314 buf = buf[:l+n+2]
315 dst := unsafe.Pointer(unsafe.SliceData(buf[l:]))
316 *(*byte)(dst) = '"'
317 dst = unsafe.Add(dst, 1)
318 switch {
319 case n > maxInlineCopySize:
320 copy(buf[l+1:], s)
321 case n >= 8:
322 // the two words overlap.
323 *(*uint64)(dst) = *(*uint64)(src)
324 *(*uint64)(unsafe.Add(dst, n-8)) = *(*uint64)(unsafe.Add(src, n-8))
325 case n >= 4:
326 *(*uint32)(dst) = *(*uint32)(src)
327 *(*uint32)(unsafe.Add(dst, n-4)) = *(*uint32)(unsafe.Add(src, n-4))
328 case n > 0:
329 // the first, the middle and the last byte are every byte of 1 to 3 bytes.
330 *(*byte)(dst) = *(*byte)(src)
331 *(*byte)(unsafe.Add(dst, n>>1)) = *(*byte)(unsafe.Add(src, n>>1))
332 *(*byte)(unsafe.Add(dst, n-1)) = *(*byte)(unsafe.Add(src, n-1))
333 }
334 *(*byte)(unsafe.Add(dst, n)) = '"'
335 return buf
336 }
337
338 // skipPlainRunes returns the index of the first byte of s from j which may need an escape by table, or len(s),
339 // taking the characters of commonRuneSize as bytes which need none: the characters of a text of CJK are skipped by
340 // this loop, called once for a run of them, and not one by one by the loop of the escapes, which then keeps its
341 // layout for the bytes of ASCII. The loop of the escapes passes s up to its limit, so that it gives the rest of a
342 // long string back to the loop by SIMD as before.
343 //
344 //go:noinline
345 func skipPlainRunes(s string, j int, table *[256]bool) int {
346 for j < len(s) {
347 c := s[j]
348 if !table[c] {
349 j++
350 continue
351 }
352 size := commonRuneSize(s, j)
353 if size == 0 {
354 break
355 }
356 j += size
357 }
358 return j
359 }
360
361 // commonRuneSize returns the size of the character at s[j] if it is one of two bytes, or one of three bytes whose
362 // first byte is 0xE3 to 0xEC, 0xEE or 0xEF, as the characters of CJK are, and its next bytes are continuation
363 // bytes, or 0. Such a character is valid UTF-8 and is not escaped whatever its continuation bytes are, so it is
364 // written as it is without decodeRuneInString, which is not inlined.
365 func commonRuneSize(s string, j int) int {
366 c := s[j]
367 if c-0xc2 < 0xe0-0xc2 {
368 if j+1 < len(s) && s[j+1]^0x80 < 0x40 {
369 return 2
370 }
371 } else if c-0xe3 < 0xed-0xe3 || c-0xee < 2 {
372 if j+2 < len(s) && (s[j+1]^0x80)|(s[j+2]^0x80) < 0x40 {
373 return 3
374 }
375 }
376 return 0
377 }
378
379 func appendNormalizedHTMLString(buf []byte, s string) []byte {
380 valLen := len(s)
381 if valLen == 0 {
382 return append(buf, `""`...)
383 }
384 buf = append(buf, '"')
385 var i int
386 // the bytes up to the first one which may need an escape are skipped by SIMD, or by words.
387 j := 0
388 // limit is where the loop of the bytes gives the rest of a long string back to the loop of the escapes by
389 // SIMD, which stops at a block of 32 bytes with invalid UTF-8, U+2028 or U+2029: the loop of the bytes
390 // escapes that block, so that the loop by SIMD is called once for 32 bytes at most.
391 limit := valLen
392 if valLen >= 32 && hasEscapeLoop {
393 // a long string is escaped by SIMD, up to a byte which is left to this loop
394 buf, j = appendEscapedSIMD(buf, s, escapeTables[stringEscapeHTML], true)
395 i = j
396 limit = min(valLen, j+32)
397 } else if valLen >= 8 {
398 // the last word overlaps the one before it: the first byte which may need an escape is in the word at
399 // k, or it is none if the mask of the last word is 0, and j is then valLen.
400 k := 0
401 m := maskNormalizedHTML(wordAt(s, 0))
402 for m == 0 && k+16 <= valLen {
403 k += 8
404 m = maskNormalizedHTML(wordAt(s, k))
405 }
406 if m == 0 && k+8 < valLen {
407 k = valLen - 8
408 m = maskNormalizedHTML(wordAt(s, k))
409 }
410 j = k + bits.TrailingZeros64(m)/8
411 }
412 for {
413 for j < limit {
414 c := s[j]
415
416 if !needEscapeHTMLNormalizeUTF8[c] {
417 // fast path: most of the time, printable ascii characters are used
418 j++
419 continue
420 }
421
422 if seq := escapeSequences[c]; seq != 0 {
423 // a byte of ASCII, escaped by its sequence ( see escapeSequences ): the bytes of the word after
424 // its length are written over by what follows.
425 buf = append(buf, s[i:j]...)
426 l := len(buf)
427 buf = binary.LittleEndian.AppendUint64(buf, seq)[:l+int(seq>>56)]
428 i = j + 1
429 j = j + 1
430 continue
431 }
432 if c >= utf8.RuneSelf {
433 if k := skipPlainRunes(s[:limit], j, &needEscapeHTMLNormalizeUTF8); k != j {
434 j = k
435 continue
436 }
437 }
438 state, size := decodeRuneInString(s[j:])
439 switch state {
440 case runeErrorState:
441 buf = append(buf, s[i:j]...)
442 buf = append(buf, invalidUTF8...)
443 i = j + 1
444 j = j + 1
445 continue
446 // U+2028 is LINE SEPARATOR.
447 // U+2029 is PARAGRAPH SEPARATOR.
448 // They are both technically valid characters in JSON strings,
449 // but don't work in JSONP, which has to be evaluated as JavaScript,
450 // and can lead to security holes there. It is valid JSON to
451 // escape them, so we do so unconditionally.
452 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
453 case lineSepState:
454 buf = append(buf, s[i:j]...)
455 buf = append(buf, `\u2028`...)
456 i = j + 3
457 j = j + 3
458 continue
459 case paragraphSepState:
460 buf = append(buf, s[i:j]...)
461 buf = append(buf, `\u2029`...)
462 i = j + 3
463 j = j + 3
464 continue
465 }
466 j += size
467 }
468 if j >= valLen {
469 break
470 }
471 buf = append(buf, s[i:j]...)
472 var n int
473 buf, n = appendEscapedSIMD(buf, s[j:], escapeTables[stringEscapeHTML], true)
474 j += n
475 i = j
476 limit = min(valLen, j+32)
477 }
478
479 return append(append(buf, s[i:]...), '"')
480 }
481
482 func appendHTMLString(buf []byte, s string) []byte {
483 valLen := len(s)
484 if valLen == 0 {
485 return append(buf, `""`...)
486 }
487 buf = append(buf, '"')
488 var i int
489 // the bytes up to the first one which may need an escape are skipped by SIMD, or by words.
490 j := 0
491 if valLen >= 32 && hasEscapeLoop {
492 // a long string is escaped by SIMD, up to a byte which is left to this loop
493 buf, j = appendEscapedSIMD(buf, s, escapeTables[stringEscapeHTML], false)
494 i = j
495 } else if valLen >= 8 {
496 // the last word overlaps the one before it: the first byte which may need an escape is in the word at
497 // k, or it is none if the mask of the last word is 0, and j is then valLen.
498 k := 0
499 m := maskNormalizedHTML(wordAt(s, 0))
500 for m == 0 && k+16 <= valLen {
501 k += 8
502 m = maskNormalizedHTML(wordAt(s, k))
503 }
504 if m == 0 && k+8 < valLen {
505 k = valLen - 8
506 m = maskNormalizedHTML(wordAt(s, k))
507 }
508 j = k + bits.TrailingZeros64(m)/8
509 }
510 for j < valLen {
511 c := s[j]
512
513 if !needEscapeHTML[c] {
514 // fast path: most of the time, printable ascii characters are used
515 j++
516 continue
517 }
518
519 // a byte of ASCII, escaped by its sequence ( see escapeSequences ): the bytes of the word after its
520 // length are written over by what follows.
521 seq := escapeSequences[c]
522 buf = append(buf, s[i:j]...)
523 l := len(buf)
524 buf = binary.LittleEndian.AppendUint64(buf, seq)[:l+int(seq>>56)]
525 i = j + 1
526 j = j + 1
527 }
528
529 return append(append(buf, s[i:]...), '"')
530 }
531
532 func appendNormalizedString(buf []byte, s string) []byte {
533 valLen := len(s)
534 if valLen == 0 {
535 return append(buf, `""`...)
536 }
537 buf = append(buf, '"')
538 var i int
539 // the bytes up to the first one which may need an escape are skipped by SIMD, or by words.
540 j := 0
541 // limit is where the loop of the bytes gives the rest of a long string back to the loop of the escapes by
542 // SIMD, which stops at a block of 32 bytes with invalid UTF-8, U+2028 or U+2029: the loop of the bytes
543 // escapes that block, so that the loop by SIMD is called once for 32 bytes at most.
544 limit := valLen
545 if valLen >= 32 && hasEscapeLoop {
546 // a long string is escaped by SIMD, up to a byte which is left to this loop
547 buf, j = appendEscapedSIMD(buf, s, escapeTables[0], true)
548 i = j
549 limit = min(valLen, j+32)
550 } else if valLen >= 8 {
551 // the last word overlaps the one before it: the first byte which may need an escape is in the word at
552 // k, or it is none if the mask of the last word is 0, and j is then valLen.
553 k := 0
554 m := maskNormalized(wordAt(s, 0))
555 for m == 0 && k+16 <= valLen {
556 k += 8
557 m = maskNormalized(wordAt(s, k))
558 }
559 if m == 0 && k+8 < valLen {
560 k = valLen - 8
561 m = maskNormalized(wordAt(s, k))
562 }
563 j = k + bits.TrailingZeros64(m)/8
564 }
565 for {
566 for j < limit {
567 c := s[j]
568
569 if !needEscapeNormalizeUTF8[c] {
570 // fast path: most of the time, printable ascii characters are used
571 j++
572 continue
573 }
574
575 if seq := escapeSequences[c]; seq != 0 {
576 // a byte of ASCII, escaped by its sequence ( see escapeSequences ): the bytes of the word after
577 // its length are written over by what follows.
578 buf = append(buf, s[i:j]...)
579 l := len(buf)
580 buf = binary.LittleEndian.AppendUint64(buf, seq)[:l+int(seq>>56)]
581 i = j + 1
582 j = j + 1
583 continue
584 }
585 if c >= utf8.RuneSelf {
586 if k := skipPlainRunes(s[:limit], j, &needEscapeNormalizeUTF8); k != j {
587 j = k
588 continue
589 }
590 }
591 state, size := decodeRuneInString(s[j:])
592 switch state {
593 case runeErrorState:
594 buf = append(buf, s[i:j]...)
595 buf = append(buf, invalidUTF8...)
596 i = j + 1
597 j = j + 1
598 continue
599 // U+2028 is LINE SEPARATOR.
600 // U+2029 is PARAGRAPH SEPARATOR.
601 // They are both technically valid characters in JSON strings,
602 // but don't work in JSONP, which has to be evaluated as JavaScript,
603 // and can lead to security holes there. It is valid JSON to
604 // escape them, so we do so unconditionally.
605 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
606 case lineSepState:
607 buf = append(buf, s[i:j]...)
608 buf = append(buf, `\u2028`...)
609 i = j + 3
610 j = j + 3
611 continue
612 case paragraphSepState:
613 buf = append(buf, s[i:j]...)
614 buf = append(buf, `\u2029`...)
615 i = j + 3
616 j = j + 3
617 continue
618 }
619 j += size
620 }
621 if j >= valLen {
622 break
623 }
624 buf = append(buf, s[i:j]...)
625 var n int
626 buf, n = appendEscapedSIMD(buf, s[j:], escapeTables[0], true)
627 j += n
628 i = j
629 limit = min(valLen, j+32)
630 }
631
632 return append(append(buf, s[i:]...), '"')
633 }
634
635 func appendString(buf []byte, s string) []byte {
636 valLen := len(s)
637 if valLen == 0 {
638 return append(buf, `""`...)
639 }
640 buf = append(buf, '"')
641 var i int
642 // the bytes up to the first one which may need an escape are skipped by SIMD, or by words.
643 j := 0
644 if valLen >= 32 && hasEscapeLoop {
645 // a long string is escaped by SIMD, up to a byte which is left to this loop
646 buf, j = appendEscapedSIMD(buf, s, escapeTables[0], false)
647 i = j
648 } else if valLen >= 8 {
649 // the last word overlaps the one before it: the first byte which may need an escape is in the word at
650 // k, or it is none if the mask of the last word is 0, and j is then valLen.
651 k := 0
652 m := maskPlain(wordAt(s, 0))
653 for m == 0 && k+16 <= valLen {
654 k += 8
655 m = maskPlain(wordAt(s, k))
656 }
657 if m == 0 && k+8 < valLen {
658 k = valLen - 8
659 m = maskPlain(wordAt(s, k))
660 }
661 j = k + bits.TrailingZeros64(m)/8
662 }
663 for j < valLen {
664 c := s[j]
665
666 if !needEscape[c] {
667 // fast path: most of the time, printable ascii characters are used
668 j++
669 continue
670 }
671
672 // a byte of ASCII, escaped by its sequence ( see escapeSequences ): the bytes of the word after its
673 // length are written over by what follows.
674 seq := escapeSequences[c]
675 buf = append(buf, s[i:j]...)
676 l := len(buf)
677 buf = binary.LittleEndian.AppendUint64(buf, seq)[:l+int(seq>>56)]
678 i = j + 1
679 j = j + 1
680 }
681
682 return append(append(buf, s[i:]...), '"')
683 }
684
685 // The masks of a word of the options: the top bit of the first byte which may need an escape is set, and maybe
686 // the ones of the bytes after it ( see looseCommonMask ). They are small enough to be inlined. The masks of HTML
687 // are loose even if UTF-8 is not normalized: the exact one costs more for every word than it saves by skipping
688 // the bytes which are not ASCII, which the loop of appendHTMLString goes over one by one instead.
689
690 func maskNormalizedHTML(w uint64) uint64 {
691 return (looseCommonMask(w) | ((w ^ (lsb * '<')) - lsb) | ((w ^ (lsb * '>')) - lsb) | ((w ^ (lsb * '&')) - lsb)) & msb
692 }
693
694 func maskNormalized(w uint64) uint64 {
695 return looseCommonMask(w) & msb
696 }
697
698 func maskPlain(w uint64) uint64 {
699 return exactCommonMask(w) & msb
700 }
701
702 // wordAt returns the eight bytes of the string at k as a little-endian word: the string has k+8 bytes or more.
703 func wordAt(s string, k int) uint64 {
704 return binary.LittleEndian.Uint64(unsafe.Slice((*byte)(unsafe.Add(unsafe.Pointer(unsafe.StringData(s)), k)), 8))
705 }