MCPcopy Index your code
hub / github.com/segmentio/encoding / parseString

Method parseString

json/parse.go:405–475  ·  view source on GitHub ↗
(b []byte)

Source from the content-addressed store, hash-verified

403}
404
405func (d decoder) parseString(b []byte) ([]byte, []byte, Kind, error) {
406 if len(b) < 2 {
407 return nil, b[len(b):], Undefined, unexpectedEOF(b)
408 }
409 if b[0] != '"' {
410 return nil, b, Undefined, syntaxError(b, "expected '\"' at the beginning of a string value")
411 }
412
413 var n int
414 if len(b) >= 9 {
415 // This is an optimization for short strings. We read 8/16 bytes,
416 // and XOR each with 0x22 (") so that these bytes (and only
417 // these bytes) are now zero. We use the hasless(u,1) trick
418 // from https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
419 // to determine whether any bytes are zero. Finally, we CTZ
420 // to find the index of that byte.
421 const mask1 = 0x2222222222222222
422 const mask2 = 0x0101010101010101
423 const mask3 = 0x8080808080808080
424 u := binary.LittleEndian.Uint64(b[1:]) ^ mask1
425 if mask := (u - mask2) & ^u & mask3; mask != 0 {
426 n = bits.TrailingZeros64(mask)/8 + 2
427 goto found
428 }
429 if len(b) >= 17 {
430 u = binary.LittleEndian.Uint64(b[9:]) ^ mask1
431 if mask := (u - mask2) & ^u & mask3; mask != 0 {
432 n = bits.TrailingZeros64(mask)/8 + 10
433 goto found
434 }
435 }
436 }
437 n = bytes.IndexByte(b[1:], '"') + 2
438 if n <= 1 {
439 return nil, b[len(b):], Undefined, syntaxError(b, "missing '\"' at the end of a string value")
440 }
441found:
442 if (d.flags.has(noBackslash) || bytes.IndexByte(b[1:n], '\\') < 0) &&
443 (d.flags.has(validAsciiPrint) || ascii.ValidPrint(b[1:n])) {
444 return b[:n], b[n:], Unescaped, nil
445 }
446
447 for i := 1; i < len(b); i++ {
448 switch b[i] {
449 case '\\':
450 if i++; i < len(b) {
451 switch b[i] {
452 case '"', '\\', '/', 'n', 'r', 't', 'f', 'b':
453 case 'u':
454 _, n, err := d.parseUnicode(b[i+1:])
455 if err != nil {
456 return nil, b[i+1+n:], Undefined, err
457 }
458 i += n
459 default:
460 return nil, b, Undefined, syntaxError(b, "invalid character '%c' in string escape code", b[i])
461 }
462 }

Callers 6

TestParseStringFunction · 0.95
BenchmarkParseStringFunction · 0.95
parseStringUnquoteMethod · 0.95
parseObjectMethod · 0.95
parseValueMethod · 0.95
NextMethod · 0.80

Calls 6

parseUnicodeMethod · 0.95
ValidPrintFunction · 0.92
unexpectedEOFFunction · 0.85
syntaxErrorFunction · 0.85
Uint64Method · 0.80
hasMethod · 0.45

Tested by 2

TestParseStringFunction · 0.76
BenchmarkParseStringFunction · 0.76