package encoderimport ()// The output of a marshaler is compacted and validated, as encoding/json does. Most of the outputs are compact// already, so they are copied as they are after being checked: a scan by SIMD finds the bytes which would have// to be rewritten or looked at, and a walk of the structure without a write validates the rest, the escapes of// the strings included. The characters which compact escapes for HTML are escaped as the output is copied.// Anything else is left to compact, which rewrites and reports the errors.// controlChars are the control characters, which compact removes as white space or reports as errors: an output// with one is left to compact. lookedAtByCompact are those and the bytes which the check must look at: an// escape, whose sequence is validated, and, if HTML is escaped, the characters which compact escapes then:// '<', '>', '&' and the first byte of U+2028 and U+2029, which starts other characters as well. Most of the// outputs have none of them: their strings are walked to the next quote at once and they are copied as they are.var ( controlChars = jsonstring.NewByteClass() lookedAtByCompact = [2]*jsonstring.ByteClass{jsonstring.NewByteClass('\\'),jsonstring.NewByteClass('\\', '<', '>', '&', 0xe2), })// The walks of the strings of an output, as the type argument of isCompactJSON: each walk is compiled into a// function of its own, so that the walk of the plain strings, which most of the outputs have, has neither a// branch nor a call for the escapes in its loop. The types differ by their sizes, which the compiler knows for// each of them: the branch on the size is resolved when the function of a walk is compiled.type (// plainStrings have no escape: a string ends at the next quote. plainStrings struct{}// escapedStrings may have escapes, which are validated. escapedStrings struct{ _ byte })// maxDepthOfCompactScan is the nesting up to which isCompactJSON scans the output: a deeper one is compacted.const maxDepthOfCompactScan = 64// appendCompactOutput appends src, the output of a marshaler, to dst as compact appends it, if src is compact// and valid JSON, and returns false without appending if it may not be: then src is to be compacted. The output// of a trusted marshaler, valid and compact, is appended as it is if compact leaves it so.func appendCompactOutput(, []byte, , bool) ([]byte, bool) {iflen() == 0 {return , false } := 0if { = 1 }if !lookedAtByCompact[].Has() {if ! && !isCompactJSON[plainStrings]() {return , false }returnappend(, ...), true }ifcontrolChars.Has() || !isCompactJSON[escapedStrings]() {return , false }if {returnjsonstring.AppendHTMLEscaped(, ), true }returnappend(, ...), true}// isCompactJSON is whether src, which has no control character, is valid JSON without a byte to remove, whose// strings are walked as S tells.func isCompactJSON[ plainStrings | escapedStrings]( []byte) bool {var := unsafe.Sizeof() == unsafe.Sizeof(plainStrings{})var [maxDepthOfCompactScan]byte// the closing brackets of the values being read := 0 := len() := 0for {// a value.if >= {returnfalse }switch := []; {case == '"':if { = quoteEnd(, +1) } else { = escapedQuoteEnd(, +1) }if < 0 {returnfalse }case == '{':if == maxDepthOfCompactScan {returnfalse } [] = '}' ++ ++if < && [] == '}' { ++ --break }// a key.if >= || [] != '"' {returnfalse }if { = quoteEnd(, +1) } else { = escapedQuoteEnd(, +1) }if < 0 {returnfalse }if >= || [] != ':' {returnfalse } ++continuecase == '[':if == maxDepthOfCompactScan {returnfalse } [] = ']' ++ ++if < && [] == ']' { ++ --break }continuecase == 't':if !bytes.HasPrefix([:], []byte("true")) {returnfalse } += 4case == 'f':if !bytes.HasPrefix([:], []byte("false")) {returnfalse } += 5case == 'n':if !bytes.HasPrefix([:], []byte("null")) {returnfalse } += 4case == '-' || ('0' <= && <= '9'): := numberEnd(, )if < 0 {returnfalse } = default:returnfalse }// after a value.for {if == 0 {return == }if >= {returnfalse }switch [] {case',': ++if [-1] == '}' {// a key.if >= || [] != '"' {returnfalse }if { = quoteEnd(, +1) } else { = escapedQuoteEnd(, +1) }if < 0 {returnfalse }if >= || [] != ':' {returnfalse } ++ }case [-1]: -- ++continuedefault:returnfalse }break } }}// quoteEnd returns the index after the quote which ends the string whose content starts at i, or -1.// The string has no escape, so the quote is the next one. Most of the strings are short, so the quote is// looked for by words here, not by a call. The words are read as little-endian ones, so that the lowest byte// found by bits.TrailingZeros64 is the first one in memory on a big-endian machine too; on a little-endian one// the read is a load as it is.func quoteEnd( []byte, int) int { := len() := unsafe.Pointer(unsafe.SliceData())for ; +8 <= ; += 8 { := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(, ))[:]) ^ (lsb * '"')if := ( - lsb) &^ & msb; != 0 {return + bits.TrailingZeros64()/8 + 1 } }for ; < ; ++ {if [] == '"' {return + 1 } }return -1}// escapedQuoteEnd is quoteEnd for a string which may have escapes, which are validated.func escapedQuoteEnd( []byte, int) int { := len() := unsafe.Pointer(unsafe.SliceData())for {for ; +8 <= ; += 8 { := binary.LittleEndian.Uint64((*[8]byte)(unsafe.Add(, ))[:]) := ^ (lsb * '"') := ^ (lsb * '\\')// the lowest bit of the mask of each byte is exact, so the lowest one of both is.if := ((-lsb)&^ | (-lsb)&^) & msb; != 0 { += bits.TrailingZeros64() / 8break } }for ; < && [] != '"' && [] != '\\'; ++ { }if >= {return -1 }if [] == '"' {return + 1 } = escapeEnd(, +1)if < 0 {return -1 } }}// escapeEnd returns the index after the escape of a string whose backslash is before i, or -1 if it is not an// escape of JSON.func escapeEnd( []byte, int) int {if >= len() {return -1 }switch [] {case'"', '\\', '/', 'b', 'f', 'n', 'r', 't':return + 1case'u':if +5 > len() {return -1 }for , := range [+1 : +5] {if !('0' <= && <= '9' || 'a' <= && <= 'f' || 'A' <= && <= 'F') {return -1 } }return + 5 }return -1}// numberEnd returns the index after the number which starts at i, or -1 if it is not a number of JSON.func numberEnd( []byte, int) int { := len()if [] == '-' { ++if >= {return -1 } }switch {case [] == '0': ++case'1' <= [] && [] <= '9': ++for < && '0' <= [] && [] <= '9' { ++ }default:return -1 }if < && [] == '.' { ++if >= || [] < '0' || [] > '9' {return -1 }for < && '0' <= [] && [] <= '9' { ++ } }if < && ([] == 'e' || [] == 'E') { ++if < && ([] == '+' || [] == '-') { ++ }if >= || [] < '0' || [] > '9' {return -1 }for < && '0' <= [] && [] <= '9' { ++ } }return}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.