package decoderimport ()type structFieldSet struct { dec Decoder offset uintptr isTaggedKey bool fieldIdx int key string keyLen int64// err is the cause of the type error of a field promoted from an embedded pointer to an unexported struct, at // offset, which can't be allocated: it is reported only when the pointer is nil ( see unsettable ). err error}// unsettable reports whether the field can't be set in the struct at p: it is promoted from an embedded pointer to// an unexported struct, which is nil. A pointer which is set is followed, as encoding/json does.func ( *structFieldSet) ( unsafe.Pointer) bool {return .err != nil && *(*unsafe.Pointer)(unsafe.Add(, .offset)) == nil}type structDecoder struct {// fields are the fields of the struct in their order, by their exact keys. fields []*structFieldSet keys *structKeys// fieldUniqueNameNum is the number of the fields which differ by their folded keys: under FirstWinOption, // the rest of an object is skipped when every one of them was decoded. fieldUniqueNameNum int stringDecoder *stringDecoder structName string fieldName string// typ is the struct type, which the type errors of the fields which can't be set report. typ reflect.Type}func newStructDecoder(, string) *structDecoder {return &structDecoder{keys: newStructKeys(nil),stringDecoder: newStringDecoder(, ),structName: ,fieldName: , }}// setFields sets the fields of the struct, which are in the order of the struct, and makes their tables.func ( *structDecoder) ( []*structFieldSet) { .fields = .keys = newStructKeys() := map[string]int{}for , := range { := string(appendFoldedKey(nil, []byte(.key))) , := []if ! { = len() [] = } .fieldIdx = } .fieldUniqueNameNum = len()}func ( *structDecoder) ( *RuntimeContext, , int64, unsafe.Pointer) (int64, error) { := .Buf := int64(len()) = skipWhiteSpace(, ) := (*sliceHeader)(unsafe.Pointer(&)).dataswitchchar(, ) {case'n':if := validateNull(, ); != nil {return0, } += 4return , nilcase'{':// only an object nests its values one level deeper: null or another value at the limit is not too deep ++if > maxDecodeNestingDepth {return0, errors.ErrExceededMaxDepth([], ) }default:return .decodeOther(, , ) } ++ = skipWhiteSpace(, )if [] == '}' { ++return , nil }if (.Option.Flags & FirstWinOption) != 0 {return .decodeObjectFirstWin(, , , ) } := (.Option.Flags & DisallowUnknownFieldsOption) != 0for { , , := .decodeKey(, , )if != nil {return0, }ifchar(, ) == ':' { = + 1 } else { = skipWhiteSpace(, )ifchar(, ) != ':' {return0, errors.ErrExpected("colon after object key", ) } ++ }if >= {return0, errors.ErrExpected("object value after colon", ) }if != nil {if .unsettable() {// a field which can't be set: the error is recorded as a type error, and the decoding goes on , := .unsettableField(, , , .err)if != nil {return0, } = } else { , := .dec.Decode(, , , unsafe.Add(, .offset))if != nil {return0, } = } } else { , := skipValue(, , )if != nil {return0, } = } = skipWhiteSpace(, )ifchar(, ) == '}' { ++return , nil }ifchar(, ) != ',' {return0, errors.ErrExpected("comma after object element", ) } ++ }}// decodeObjectFirstWin is the loop of Decode under FirstWinOption, from the first key of a non-empty object at// cursor: a field is decoded at its first key, the value of a later key of the field is skipped, and the rest of// the object is skipped once every field is decoded. It is a function of its own, so that the loop of Decode keeps// nothing of it in its registers.func ( *structDecoder) ( *RuntimeContext, , int64, unsafe.Pointer) (int64, error) { := .Buf := int64(len()) := (*sliceHeader)(unsafe.Pointer(&)).data// seen and seenMore are the fields decoded in the object, by their indexes: the bits of seen are the first 64 // fields, and the ones of seenMore the others ( see decodedBefore ); seenFieldNum is their number.var (uint64 []uint64int ) := (.Option.Flags & DisallowUnknownFieldsOption) != 0for { , , := .decodeKey(, , )if != nil {return0, }ifchar(, ) == ':' { = + 1 } else { = skipWhiteSpace(, )ifchar(, ) != ':' {return0, errors.ErrExpected("colon after object key", ) } ++ }if >= {return0, errors.ErrExpected("object value after colon", ) }if != nil {// the first 64 fields are the bits of seen, in a register; the others are looked at by a callvarbool := .unsettable()if {// a field which can't be set: the error is recorded as a type error, and the decoding goes on , := .unsettableField(, , , .err)if != nil {return0, } = } elseif := .fieldIdx; < 64 { := uint64(1) << uint() = & != 0 |= } else { = .decodedBefore(, &) }switch {case :case : , := skipValue(, , )if != nil {return0, } = default: , := .dec.Decode(, , , unsafe.Add(, .offset))if != nil {return0, } = ++if .fieldUniqueNameNum <= {// every field is decoded: the rest of the object is skipped, which is nothing in most objects, // whose last key is the last fieldif = skipWhiteSpace(, ); char(, ) == '}' {return + 1, nil }returnskipRestOfObject(, , ) } } } else { , := skipValue(, , )if != nil {return0, } = } = skipWhiteSpace(, )ifchar(, ) == '}' { ++return , nil }ifchar(, ) != ',' {return0, errors.ErrExpected("comma after object element", ) } ++ }}// decodedBefore reports whether the field of the index, which is 64 or more, was decoded before in the object, under// FirstWinOption, and marks it decoded: its bit is in more, which is made for a struct of more than 64 fields when// such a field is decoded. The first 64 fields are marked in decodeObjectFirstWin itself, without an allocation.////go:noinlinefunc ( *structDecoder) ( int, *[]uint64) bool {if * == nil { * = make([]uint64, (.fieldUniqueNameNum-64+63)/64) } -= 64 , := &(*)[/64], uint64(1)<<uint(%64) := *& != 0 * |= return}// unsettableField records err, the error of a field which can't be set, for the value at cursor, and skips the// value. It is not inlined, so that Decode keeps the size it had.////go:noinlinefunc ( *structDecoder) ( *RuntimeContext, , int64, error) (int64, error) { := .Buf = skipWhiteSpace(, ) , := skipValue(, , )if != nil {return0, } .unsettableValueError(, , kindOf([]), .typ, )return , nil}func ( *structDecoder) ( *RuntimeContext, , int64) ([][]byte, int64, error) {returnnil, 0, fmt.Errorf("json: struct decoder does not support decode path")}// decodeKey reads the key of an object at cursor, and returns its field or nil, and the position after it.// A key which matches no field is an error if disallowUnknownFields is set. It is a function of its own, so that// the loop of Decode keeps its values in the registers, and the key is not returned, which would take registers// of the loop too.func ( *structDecoder) ( []byte, int64, bool) (*structFieldSet, int64, error) {if [] != '"' { = skipWhiteSpace(, )if [] != '"' {returnnil, 0, errors.ErrInvalidBeginningOfValue([], ) } }// A key of ASCII without an escape is found by the words of the buffer, which may be read up to its capacity: // the nul byte at its end stops a key before it. Any other key, and a key near the end of a buffer which has // no room after it, is scanned as a string.if := + 1; +16 <= int64(cap()) { := .keys := load64(, ) := specialKeyBytes()if != 0 {// A key of less than 8 bytes, which is most keys. The first entry of the table for it is looked at // here: most keys are found in it. Its index is made from the bytes of the key before their fold, and // so is computed while they are folded, and the mask of the bytes from the bits of the special byte. := bits.TrailingZeros64() / 8if [+int64()] != '"' {return .decodeKeyNotASCII(, , ) } := ( ^ ( - 1)) >> 8 &= := foldASCIIWord() := &.entries[.index(|bit5&, 0)]var *structFieldSetif .short == { = .unique } elseif .fields != nil && .hasLength() { = .findASCII([:+int64()], , 0) }if == nil && {returnnil, 0, unknownFieldError([ : +int64()]) }return , + int64() + 1, nil }// A key of 8 bytes or more, whose end is looked for word by word. It is looked up by its first and last // words, as a short key is. := + 8 = specialKeyBytes(load64(, ))for == 0 { += 8if +8 > int64(cap()) {return .decodeKeyByScan(, , ) } = specialKeyBytes(load64(, )) } += int64(bits.TrailingZeros64() / 8)if [] != '"' {return .decodeKeyNotASCII(, , ) } := [:] := len()var *structFieldSet// A key of a length which no field has, which is a key of no field in most objects of such a length, // is not looked up.if .hasLength() { := load64(, -8) , := foldASCIIWord(), foldASCIIWord() := &.entries[.index(|bit5, |bit5)]if .n == && .w0 == && .w1 == && .unique != nil && ( <= 16 || equalFoldedASCII(, .folded)) { = .unique } elseif .fields != nil { = .findASCII(, , ) } }if == nil && {returnnil, 0, unknownFieldError() }return , + 1, nil }return .decodeKeyByScan(, , )}// decodeKeyNotASCII is decodeKey for a key which has a byte which is not ASCII, or an escape. A key without an// escape is read word by word too, and looked up by its bytes as they are among the keys which are not ASCII// first: a key is usually the same as the key of its field, which it is found by whatever the fold of its runes,// because a key which is the same wins over the others. Any other key is folded rune by rune if its runes may// fold to the ones of a key, and else is of no field. A key with an escape is scanned as a string.func ( *structDecoder) ( []byte, int64, bool) (*structFieldSet, int64, error) { := + 1 := for {if +8 > int64(cap()) {return .decodeKeyByScan(, , ) }if := keyEndBytes(load64(, )); != 0 { += int64(bits.TrailingZeros64() / 8)break } += 8 }if [] != '"' {return .decodeKeyByScan(, , ) } := [:] := len() := .keys// the words of the key, as keyWords makes them, read from the buffer := load64(, )varuint64if < 8 { &= 1<<(uint()*8&63) - 1 } else { = load64(, -8) }var *structFieldSetif .hasExactLength() {// the first entry of the key is looked at here: most keys are found in it. , := hashWords(, , ) := &.exact[indexOf(, , .exactShift)]if .n == && .w0 == && .w1 == && .unique != nil && ( <= 16 || equalMiddleWords(, .folded)) {return .unique, + 1, nil }if .unique != nil { = .findExact(, , ) } }if == nil {// Most keys which are not the key of a field are told so by their first rune which is not ASCII, which // folds to no rune of a key ( see mayFold ); the others are looked at rune by rune.if .leadMayFold() && .firstRuneMayFold(, ) && .mayFold() { , = .lookup(, stringInfo{firstEscape: -1, nonASCII: true}) } elseif { = decodeLiteral(, stringInfo{firstEscape: -1, nonASCII: true}) } }if == nil && {returnnil, 0, unknownFieldError() }return , + 1, nil}// decodeKeyByScan is decodeKey for any key, which it scans as a string.func ( *structDecoder) ( []byte, int64, bool) (*structFieldSet, int64, error) { , , , := .stringDecoder.scanString(, )if < 0 { , , , = .stringDecoder.scanStringRest(, , --1, ) }if != nil {returnnil, 0, } , := .keys.lookup(, )if == nil && {returnnil, 0, unknownFieldError() }return , , nil}// decodeOther skips the value at cursor, which is not an object: a value of another kind is a type error, and// anything else a syntax error. It is a function of its own, so that Decode keeps the size it had.////go:noinlinefunc ( *structDecoder) ( *RuntimeContext, , int64) (int64, error) {if := .Buf[]; isOtherValue(, objectValue) {return .skipTypeError(, , .typ) }return0, errors.ErrInvalidBeginningOfValue(.Buf[], )}func unknownFieldError( []byte) error {returnfmt.Errorf("json: unknown field %q", )}// specialKeyBytes returns the word which has the top bit of the first byte of w which ends a simple key, and// maybe the top bits of bytes after it: a quote, a backslash, a control character or a byte which is not ASCII.func specialKeyBytes( uint64) uint64 {// Only the first such byte is looked for, so the masks may be wrong in the bytes after it, which saves // instructions: a subtraction borrows from the next byte only at a byte which is found. // A byte of a quote or a backslash is 0 in q or s, whose subtraction sets its top bit; the one of a control // character sets the top bit of the subtraction of 0x20, and the one of a byte which is not ASCII is set. := ^ ('"' * lsb) := ^ ('\\' * lsb)return ((( - lsb) &^ ) | (( - lsb) &^ ) | ( - 0x20*lsb) | ) & msb}// keyEndBytes is specialKeyBytes for a key which may have bytes which are not ASCII: it has the top bit of the// first byte of w which is a quote, a backslash or a control character, and maybe of bytes after it.func keyEndBytes( uint64) uint64 {// a byte of 0x80 or more is none of them: its top bit is cleared from the subtractions, which don't borrow // from the next byte at such a byte. := ^ ('"' * lsb) := ^ ('\\' * lsb)return ((( - lsb) &^ ) | (( - lsb) &^ ) | (( - 0x20*lsb) &^ )) & msb}
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.