package decoder
import (
"bytes"
"encoding/binary"
stderrors "errors"
"fmt"
"math/bits"
"reflect"
"slices"
"strings"
"unicode/utf8"
"unsafe"
"github.com/goccy/go-json/internal/errors"
"github.com/goccy/go-json/internal/jsonfields"
"github.com/goccy/go-json/internal/runtime"
"github.com/goccy/go-json/internal/textcoder"
)
var (
errNilField = stderrors .New ("cannot set embedded pointer to unexported struct type" )
errInvalidStringTag = stderrors .New ("invalid use of `string` tag option" )
errRawNotObject = stderrors .New ("embedded raw value must be a JSON object" )
)
type v2StructDecoder struct {
typ reflect .Type
zero zeroer
initErr *jsonfields .Error
fields []*structFieldSet
keyDecoder *structDecoder
foldedTo [foldedTables ][]*structFieldSet
foldKeys *structKeys
foldAlways bool
fallback *v2Fallback
}
const (
foldedInsensitive = 1 << iota
foldedDelimiter
foldedTables = foldedDelimiter << 1
)
func (d *v2StructDecoder ) foldedOf (flags V2Flags ) []*structFieldSet {
return d .foldedTo [(flags /V2MatchCaseInsensitiveNames &1 )*foldedInsensitive |
(flags /V2MatchCaseSensitiveDelimiter &1 )*foldedDelimiter ]
}
func (c *compiler ) compileStructV2 (typ reflect .Type ) (Decoder , error ) {
d := &v2StructDecoder {typ : typ , zero : newZeroer (typ )}
if _ , exists := c .decoders [uintptr (runtime .TypePtr (typ ))]; !exists {
c .decoders [uintptr (runtime .TypePtr (typ ))] = d
}
fields := jsonfields .Of (typ )
reportErrors := c .v1Options &V2ReportErrorsWithLegacySemantics != 0
switch {
case fields .Err != nil && !reportErrors :
d .initErr = fields .Err
return d , nil
case fields .FormatErr != nil :
d .initErr = fields .FormatErr
return d , nil
}
folded := map [string ][]*structFieldSet {}
for i := range fields .List {
f := &fields .List [i ]
var dec Decoder
var err error
if f .String && (!reportErrors || c .stringOptionAppliesAsV1 (f .Type )) {
dec , err = c .stringTagCompiler ().compileV2 (f .Type , typ .Name (), f .Name )
} else {
dec , err = compile (f .Type , typ .Name (), f .Name , c )
}
if err != nil {
return nil , err
}
offset , dec := fieldPathV2 (typ , typ , f .Index , dec )
set := &structFieldSet {dec : c .goOnDecoder (dec ), offset : offset , key : f .Name , keyLen : int64 (len (f .Name )), fieldIdx : i }
d .fields = append (d .fields , set )
if f .Casing &jsonfields .CaseStrict == 0 {
key := string (jsonfields .FoldName ([]byte (f .Name )))
folded [key ] = append (folded [key ], set )
d .foldAlways = d .foldAlways || f .Casing &jsonfields .CaseIgnore != 0
}
}
for i := range d .foldedTo {
d .foldedTo [i ] = make ([]*structFieldSet , len (d .fields ))
}
only := onlyField
if reportErrors {
only = func (match , field *structFieldSet ) *structFieldSet {
if match == nil || fields .List [field .fieldIdx ].ID < fields .List [match .fieldIdx ].ID {
return field
}
return match
}
}
dashes := false
for i , f := range d .fields {
for _ , other := range folded [string (jsonfields .FoldName ([]byte (f .key )))] {
ignore := fields .List [other .fieldIdx ].Casing &jsonfields .CaseIgnore != 0
dashesOnly := !strings .EqualFold (other .key , f .key )
for t := range d .foldedTo {
if t &foldedInsensitive == 0 && !ignore || t &foldedDelimiter != 0 && dashesOnly {
continue
}
d .foldedTo [t ][i ] = only (d .foldedTo [t ][i ], other )
}
}
dashes = dashes || strings .ContainsAny (f .key , "_-" )
}
keys := newStructKeys (d .fields )
d .foldKeys = keys
if dashes {
without := make ([]*structFieldSet , len (d .fields ))
for i , f := range d .fields {
var arr [64 ]byte
key , _ := foldKey (arr [:0 ], []byte (f .key ))
w := *f
w .key , w .keyLen = string (key ), int64 (len (key ))
without [i ] = &w
}
d .foldKeys = newStructKeys (without )
}
keys .makeExact (d .fields , true )
d .keyDecoder = &structDecoder {fields : d .fields , keys : keys , stringDecoder : skipStringDecoder }
if fields .Fallback != nil {
fb , err := c .compileFallback (typ , fields .Fallback )
if err != nil {
return nil , err
}
d .fallback = fb
}
return d , nil
}
func (c *compiler ) stringTagCompiler () *compiler {
return &compiler {
decoders : map [uintptr ]Decoder {}, v2 : true , stringifyNumbers : true , stringTag : true , v1Options : c .v1Options ,
funcs : c .funcs ,
}
}
func (c *compiler ) stringOptionAppliesAsV1 (typ reflect .Type ) bool {
elem := typ
var passed []reflect .Type
for elem .Kind () == reflect .Pointer && len (c .funcs .funcsOf (elem )) == 0 {
if slices .Contains (passed , elem ) {
return false
}
passed = append (passed , elem )
elem = elem .Elem ()
}
stringify := c .v1Options &V2StringifyWithLegacySemantics != 0
switch {
case elem == timeType , stringify && typ .Kind () == reflect .Pointer && typ .Elem ().Kind () == reflect .Pointer :
return false
case len (c .funcs .funcsOf (elem )) > 0 || v2MethodOf (elem , methodUnmarshalJSONFrom ) != noMethod :
return true
case isNumberKind (elem .Kind ()) || elem == jsonNumberType :
return true
}
return stringify && (elem .Kind () == reflect .Bool || elem .Kind () == reflect .String )
}
func fieldPathV2(root , typ reflect .Type , index []int , dec Decoder ) (uintptr , Decoder ) {
sf := typ .Field (index [0 ])
if len (index ) == 1 {
return sf .Offset , dec
}
if sf .Type .Kind () == reflect .Pointer {
offset , inner := fieldPathV2 (root , sf .Type .Elem (), index [1 :], dec )
return sf .Offset , &v2EmbeddedPtrDecoder {
elem : sf .Type .Elem (), offset : offset , dec : inner , settable : sf .IsExported (), root : root ,
}
}
offset , inner := fieldPathV2 (root , sf .Type , index [1 :], dec )
return sf .Offset + offset , inner
}
type v2EmbeddedPtrDecoder struct {
elem reflect .Type
offset uintptr
dec Decoder
settable bool
root reflect .Type
}
func (d *v2EmbeddedPtrDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
if *(*unsafe .Pointer )(p ) == nil {
if !d .settable {
cursor = skipWhiteSpace (ctx .Buf , cursor )
return 0 , &errors .UnmarshalError {GoType : d .root , Start : cursor , NoKind : true , Err : errNilField }
}
*(*unsafe .Pointer )(p ) = newValue (d .elem )
}
return d .dec .Decode (ctx , cursor , depth , unsafe .Add (*(*unsafe .Pointer )(p ), d .offset ))
}
func (d *v2EmbeddedPtrDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
func (d *v2StructDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
if ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
d .zero .zero (p )
}
return cursor + 4 , nil
case '{' :
default :
return ctx .skipTypeError (cursor , depth , d .typ )
}
if d .initErr != nil {
return 0 , &errors .UnmarshalError {GoType : d .initErr .GoType , Start : cursor , Err : d .initErr .Err }
}
depth ++
if depth > maxDecodeNestingDepth {
return 0 , errors .ErrExceededMaxDepth (buf [cursor ], cursor )
}
cursor = skipWhiteSpace (buf , cursor +1 )
if buf [cursor ] == '}' {
return cursor + 1 , nil
}
if !d .foldAlways && d .fallback == nil && ctx .Option .V2 &(V2MatchCaseInsensitiveNames |V2RejectUnknownMembers ) == 0 {
switch ctx .Option .V2 & asV1Text {
case strictText :
if len (d .fields ) <= seenFields {
return d .decodeMembersOnce (ctx , cursor , depth , p )
}
case asV1Text :
return d .decodeMembersAsV1 (ctx , cursor , depth , p )
}
}
rejectDuplicateNames := ctx .Option .V2 &V2AllowDuplicateNames == 0
fold := d .foldAlways || ctx .Option .V2 &V2MatchCaseInsensitiveNames != 0
var seen uint64
var more []uint64
var unknown nameSet
for {
start := cursor
if buf [start ] != '"' {
if start = skipWhiteSpace (buf , start ); buf [start ] != '"' {
return 0 , syntaxErrorAt (buf , start , whereKey )
}
}
var field *structFieldSet
var end int64
var plain bool
if fold {
field , end , plain = d .foldedFieldV2 (ctx , buf , start )
} else {
field , end , plain = plainFieldV2 (d .keyDecoder .keys , buf , start )
}
var name []byte
if !plain {
var err error
if field , end , name , err = d .decodedMember (ctx , buf , start ); err != nil {
return 0 , err
}
}
if field != nil {
if rejectDuplicateNames {
if idx := field .fieldIdx ; idx < seenFields {
bit := uint64 (1 ) << uint (idx )
if seen &bit != 0 {
return 0 , &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
seen |= bit
} else if fieldSeen (idx , &more , len (d .fields )) {
return 0 , &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
}
} else if d .fallback == nil {
next , done , err := d .skipUnknownMembers (ctx , &unknown , fold , buf , start , end , name , depth )
if err != nil {
return 0 , err
}
if done {
unknown .end (ctx .v2 )
return next , nil
}
cursor = next
continue
} else if err := d .unknownMember (ctx , &unknown , rejectDuplicateNames , buf , start , end , name ); err != nil {
return 0 , err
}
if buf [end ] == ':' {
cursor = end + 1
} else {
cursor = skipWhiteSpace (buf , end )
if buf [cursor ] != ':' {
return 0 , syntaxErrorAt (buf , cursor , whereAfterKey )
}
cursor ++
}
var err error
if field != nil {
cursor , err = field .dec .Decode (ctx , cursor , depth , unsafe .Add (p , field .offset ))
} else {
cursor , err = d .fallback .decodeMember (ctx , cursor , depth , p , start , end )
}
if err != nil {
return 0 , err
}
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case '}' :
unknown .end (ctx .v2 )
return cursor + 1 , nil
case ',' :
cursor ++
default :
return 0 , syntaxErrorAt (buf , cursor , whereAfterPair )
}
}
}
func (d *v2StructDecoder ) decodeMembersOnce (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
var seen uint64
var unknown nameSet
for {
start := cursor
if buf [start ] != '"' {
if start = skipWhiteSpace (buf , start ); buf [start ] != '"' {
return 0 , syntaxErrorAt (buf , start , whereKey )
}
}
field , end , plain := plainFieldV2 (d .keyDecoder .keys , buf , start )
var name []byte
if !plain {
var err error
if field , end , name , err = d .decodedMember (ctx , buf , start ); err != nil {
return 0 , err
}
}
if field != nil {
bit := uint64 (1 ) << uint (field .fieldIdx )
if seen &bit != 0 {
return 0 , &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
seen |= bit
} else {
call := ctx .V2Call ()
var added bool
if name == nil {
added = unknown .addListed (call , buf , start +1 , end -1 ) || unknown .add (call , buf , start +1 , end -1 )
} else {
added = unknown .addCopy (call , buf , name )
}
if !added {
return 0 , &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
}
if buf [end ] == ':' {
cursor = end + 1
} else {
cursor = skipWhiteSpace (buf , end )
if buf [cursor ] != ':' {
return 0 , syntaxErrorAt (buf , cursor , whereAfterKey )
}
cursor ++
}
var err error
if field != nil {
cursor , err = field .dec .Decode (ctx , cursor , depth , unsafe .Add (p , field .offset ))
} else {
switch cursor = skipWhiteSpace (buf , cursor ); buf [cursor ] {
case '{' , '[' :
cursor , err = skipNestedV2 (ctx , cursor , depth )
case '"' :
cursor , err = skipStringV2 (buf , cursor )
default :
cursor , err = skipValue (buf , cursor , depth )
}
}
if err != nil {
return 0 , err
}
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case '}' :
unknown .end (ctx .v2 )
return cursor + 1 , nil
case ',' :
cursor ++
default :
return 0 , syntaxErrorAt (buf , cursor , whereAfterPair )
}
}
}
func (d *v2StructDecoder ) decodeMembersAsV1 (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
for {
start := cursor
if buf [start ] != '"' {
if start = skipWhiteSpace (buf , start ); buf [start ] != '"' {
return 0 , syntaxErrorAt (buf , start , whereKey )
}
}
field , end , plain := plainFieldV2 (d .keyDecoder .keys , buf , start )
if !plain {
var err error
if field , end , _, err = d .decodedMember (ctx , buf , start ); err != nil {
return 0 , err
}
}
if buf [end ] == ':' {
cursor = end + 1
} else {
cursor = skipWhiteSpace (buf , end )
if buf [cursor ] != ':' {
return 0 , syntaxErrorAt (buf , cursor , whereAfterKey )
}
cursor ++
}
var err error
if field != nil {
cursor , err = field .dec .Decode (ctx , cursor , depth , unsafe .Add (p , field .offset ))
} else {
cursor , err = skipValue (buf , cursor , depth )
}
if err != nil {
return 0 , err
}
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case '}' :
return cursor + 1 , nil
case ',' :
cursor ++
default :
return 0 , syntaxErrorAt (buf , cursor , whereAfterPair )
}
}
}
func (d *v2StructDecoder ) decodedMember (ctx *RuntimeContext , buf []byte , start int64 ) (*structFieldSet , int64 , []byte , error ) {
candidate , end , err := d .keyDecoder .decodeKey (buf , start , false )
if err != nil {
return nil , 0 , nil , err
}
field , name , err := d .memberOf (ctx , buf [start :end ], candidate )
if err != nil {
if e , ok := err .(*errors .UnmarshalError ); ok {
e .Start = start
}
return nil , 0 , nil , err
}
return field , end , name , nil
}
func (d *v2StructDecoder ) skipUnknownMembers (ctx *RuntimeContext , unknown *nameSet , fold bool , buf []byte , start , end int64 , name []byte , depth int64 ) (int64 , bool , error ) {
if ctx .Option .V2 &V2RejectUnknownMembers != 0 {
if ctx .Option .V2 &V2ReportErrorsWithLegacySemantics == 0 {
return 0 , false , &errors .UnmarshalError {GoType : d .typ , Start : start , Err : errors .ErrUnknownName }
}
ctx .recordUnknownMember (start , end , name )
}
rejectDuplicateNames := ctx .Option .V2 &V2AllowDuplicateNames == 0
nested := rejectDuplicateNames || ctx .Option .V2 &V2AllowInvalidUTF8 == 0
validUTF8 := ctx .Option .V2 &V2AllowInvalidUTF8 == 0
for {
if rejectDuplicateNames {
var added bool
if name == nil {
added = unknown .add (ctx .V2Call (), buf , start +1 , end -1 )
} else {
added = unknown .addCopy (ctx .V2Call (), buf , name )
}
if !added {
return 0 , false , &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
}
cursor := end
if buf [cursor ] == ':' {
cursor ++
} else {
if cursor = skipWhiteSpace (buf , cursor ); buf [cursor ] != ':' {
return 0 , false , syntaxErrorAt (buf , cursor , whereAfterKey )
}
cursor ++
}
var err error
switch cursor = skipWhiteSpace (buf , cursor ); buf [cursor ] {
case '{' , '[' :
if nested {
cursor , err = skipNestedV2 (ctx , cursor , depth )
} else {
cursor , err = skipValue (buf , cursor , depth )
}
case '"' :
if validUTF8 {
cursor , err = skipStringV2 (buf , cursor )
} else {
cursor , err = skipValue (buf , cursor , depth )
}
default :
cursor , err = skipValue (buf , cursor , depth )
}
if err != nil {
return 0 , false , err
}
switch cursor = skipWhiteSpace (buf , cursor ); buf [cursor ] {
case '}' :
return cursor + 1 , true , nil
case ',' :
cursor ++
default :
return 0 , false , syntaxErrorAt (buf , cursor , whereAfterPair )
}
if start = cursor ; buf [start ] != '"' {
if start = skipWhiteSpace (buf , start ); buf [start ] != '"' {
return 0 , false , syntaxErrorAt (buf , start , whereKey )
}
}
var field *structFieldSet
var plain bool
if fold {
field , end , plain = d .foldedFieldV2 (ctx , buf , start )
} else {
field , end , plain = plainFieldV2 (d .keyDecoder .keys , buf , start )
}
if field != nil || !plain {
return start , false , nil
}
name = nil
}
}
func (d *v2StructDecoder ) unknownMember (ctx *RuntimeContext , unknown *nameSet , rejectDuplicateNames bool , buf []byte , start , end int64 , name []byte ) error {
if !rejectDuplicateNames {
return nil
}
var added bool
if name == nil {
added = unknown .add (ctx .V2Call (), buf , start +1 , end -1 )
} else {
added = unknown .addCopy (ctx .V2Call (), buf , name )
}
if !added {
return &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
return nil
}
func (d *v2StructDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
const seenFields = 64
func fieldSeen(idx int , more *[]uint64 , n int ) bool {
if *more == nil {
*more = make ([]uint64 , (n -seenFields +63 )/64 )
}
idx -= seenFields
w , bit := &(*more )[idx /64 ], uint64 (1 )<<uint (idx %64 )
met := *w &bit != 0
*w |= bit
return met
}
func plainFieldV2(keys *structKeys , buf []byte , cursor int64 ) (*structFieldSet , int64 , bool ) {
start := cursor + 1
if start +16 > int64 (cap (buf )) {
return nil , 0 , false
}
w0 := load64 (buf , start )
if special := specialKeyBytes (w0 ); special != 0 {
n := int64 (bits .TrailingZeros64 (special ) / 8 )
if buf [start +n ] != '"' {
return nil , 0 , false
}
next := start + n + 1
w0 &= (special ^ (special - 1 )) >> 8
if !keys .hasExactLength (int (n )) {
return nil , next , true
}
e := &keys .exact [indexOf ((w0 |bit5 )&(1 <<(uint (n )*8 &63 )-1 ), 0 , keys .exactShift )]
if e .n == int (n ) && e .w0 == w0 && e .unique != nil {
return e .unique , next , true
}
if e .unique == nil {
return nil , next , true
}
return keys .findExact (buf [start :start +n ], w0 , 0 ), next , true
}
end := start + 8
special := specialKeyBytes (load64 (buf , end ))
for special == 0 {
end += 8
if end +8 > int64 (cap (buf )) {
return nil , 0 , false
}
special = specialKeyBytes (load64 (buf , end ))
}
end += int64 (bits .TrailingZeros64 (special ) / 8 )
if buf [end ] != '"' {
return nil , 0 , false
}
if !keys .hasExactLength (int (end - start )) {
return nil , end + 1 , true
}
return keys .findExact (buf [start :end ], w0 , load64 (buf , end -8 )), end + 1 , true
}
func foldedPlainFieldV2(keys *structKeys , buf []byte , cursor int64 ) (*structFieldSet , int64 , int , bool ) {
start := cursor + 1
if start +16 > int64 (cap (buf )) {
return nil , 0 , 0 , false
}
w0 := load64 (buf , start )
if special := specialKeyBytes (w0 ); special != 0 {
n := int64 (bits .TrailingZeros64 (special ) / 8 )
if buf [start +n ] != '"' {
return nil , 0 , 0 , false
}
next := start + n + 1
w0 &= (special ^ (special - 1 )) >> 8
if keys .hasLength (int (n )) {
if field := keys .findASCII (buf [start :start +n ], w0 , 0 ); field != nil {
return field , next , 0 , true
}
}
return nil , next , dashCount (w0 ), true
}
dashes := dashCount (w0 )
end := start + 8
w := load64 (buf , end )
special := specialKeyBytes (w )
for special == 0 {
dashes += dashCount (w )
end += 8
if end +8 > int64 (cap (buf )) {
return nil , 0 , 0 , false
}
w = load64 (buf , end )
special = specialKeyBytes (w )
}
end += int64 (bits .TrailingZeros64 (special ) / 8 )
if buf [end ] != '"' {
return nil , 0 , 0 , false
}
if keys .hasLength (int (end - start )) {
if field := keys .findASCII (buf [start :end ], w0 , load64 (buf , end -8 )); field != nil {
return field , end + 1 , 0 , true
}
}
return nil , end + 1 , dashes + dashCount (w &(special -1 )), true
}
func dashCount(w uint64 ) int {
return bits .OnesCount64 (byteMask (w , '_' ) | byteMask (w , '-' ))
}
func (d *v2StructDecoder ) foldedFieldV2 (ctx *RuntimeContext , buf []byte , start int64 ) (*structFieldSet , int64 , bool ) {
field , end , dashes , plain := foldedPlainFieldV2 (d .keyDecoder .keys , buf , start )
if !plain {
return nil , 0 , false
}
folded := d .foldedOf (ctx .Option .V2 )
if field != nil {
return field , end , folded [field .fieldIdx ] == field
}
return nil , end , ctx .Option .V2 &V2MatchCaseSensitiveDelimiter != 0 || dashes == 0 && d .foldKeys == d .keyDecoder .keys ||
!d .foldKeys .hasLength (int (end -start -2 )-dashes )
}
func (d *v2StructDecoder ) memberOf (ctx *RuntimeContext , quoted []byte , candidate *structFieldSet ) (*structFieldSet , []byte , error ) {
name := quoted [1 : len (quoted )-1 ]
if candidate != nil && string (name ) == candidate .key {
return candidate , name , nil
}
plain := !hasNotASCIIOrEscape (name )
insensitive := ctx .Option .V2 &V2MatchCaseInsensitiveNames != 0
folded := d .foldedOf (ctx .Option .V2 )
if !plain {
if ctx .Option .V2 &V2AllowInvalidUTF8 == 0 && !validV2Text (quoted ) {
return nil , nil , errV2Text
}
if name = unquotedName (quoted ); candidate != nil && string (name ) == candidate .key {
return candidate , name , nil
}
}
var match *structFieldSet
switch {
case candidate != nil :
match = folded [candidate .fieldIdx ]
case (insensitive || d .foldAlways ) && ctx .Option .V2 &V2MatchCaseSensitiveDelimiter == 0 :
if n := foldedLength (name ); (n < len (name ) || d .foldKeys != d .keyDecoder .keys ) && (!plain || d .foldKeys .hasLength (n )) {
var arr [64 ]byte
key , nonASCII := foldKey (arr [:0 ], name )
if field , _ := d .foldKeys .lookup (key , stringInfo {firstEscape : -1 , nonASCII : nonASCII }); field != nil {
match = folded [field .fieldIdx ]
}
}
}
if match == ambiguousField {
return nil , nil , &errors .UnmarshalError {GoType : d .typ , Err : errors .ErrAmbiguousName }
}
return match , name , nil
}
var ambiguousField = &structFieldSet {}
func onlyField(match , field *structFieldSet ) *structFieldSet {
if match == nil {
return field
}
return ambiguousField
}
func foldKey(out , name []byte ) ([]byte , bool ) {
i , nonASCII := 0 , false
for ; i < len (name ) && name [i ] != '_' && name [i ] != '-' ; i ++ {
nonASCII = nonASCII || name [i ] >= utf8 .RuneSelf
}
if i == len (name ) {
return name , nonASCII
}
out = append (out , name [:i ]...)
for _ , c := range name [i +1 :] {
if c != '_' && c != '-' {
out = append (out , c )
nonASCII = nonASCII || c >= utf8 .RuneSelf
}
}
return out , nonASCII
}
func foldedLength(name []byte ) int {
n , i := len (name ), 0
for ; i +8 <= len (name ); i += 8 {
w := binary .LittleEndian .Uint64 (name [i :])
n -= bits .OnesCount64 (byteMask (w , '_' ) | byteMask (w , '-' ))
}
for _ , c := range name [i :] {
if c == '_' || c == '-' {
n --
}
}
return n
}
func hasNotASCIIOrEscape(b []byte ) bool {
i := 0
for ; i +8 <= len (b ); i += 8 {
w := binary .LittleEndian .Uint64 (b [i :])
s := w ^ ('\\' * lsb )
if (w |(s -lsb )&^s )&msb != 0 {
return true
}
}
for _ , c := range b [i :] {
if c >= 0x80 || c == '\\' {
return true
}
}
return false
}
func unquotedName(quoted []byte ) []byte {
raw , next , info , _ := skipStringDecoder .scanString (quoted , 0 )
if next < 0 {
raw , _, info , _ = skipStringDecoder .scanStringRest (quoted , raw , -next -1 , info )
}
return decodeLiteral (raw , info )
}
func skipperOf(ctx *RuntimeContext ) unsafe .Pointer {
call := ctx .V2Call ()
i := 0
switch {
case ctx .Option .V2 &V2AllowDuplicateNames != 0 :
i = 2
case ctx .Option .V2 &V2AllowInvalidUTF8 != 0 :
i = 1
}
if call .skippers [i ] == nil {
call .skippers [i ] = textcoder .TakeSkipper (i == 2 , i == 1 )
}
return call .skippers [i ]
}
func releaseSkippers(call *V2Call ) {
for i , s := range call .skippers {
if s != nil {
textcoder .ReleaseSkipper (s )
call .skippers [i ] = nil
}
}
}
type v2Fallback struct {
steps []fallbackStep
mapType reflect .Type
value Decoder
}
type fallbackStep struct {
offset uintptr
elem reflect .Type
}
func (c *compiler ) compileFallback (root reflect .Type , f *jsonfields .Field ) (*v2Fallback , error ) {
fb := &v2Fallback {}
typ := root
for _ , i := range f .Index {
sf := typ .Field (i )
step := fallbackStep {offset : sf .Offset }
typ = sf .Type
if typ .Kind () == reflect .Pointer {
step .elem , typ = typ .Elem (), typ .Elem ()
}
fb .steps = append (fb .steps , step )
}
if typ != jsonfields .RawValueType {
fb .mapType = typ
value , err := compile (typ .Elem (), "" , "" , c )
if err != nil {
return nil , err
}
fb .value = c .goOnDecoder (value )
}
return fb , nil
}
func (fb *v2Fallback ) target (p unsafe .Pointer ) unsafe .Pointer {
for _ , step := range fb .steps {
p = unsafe .Add (p , step .offset )
if step .elem != nil {
if *(*unsafe .Pointer )(p ) == nil {
*(*unsafe .Pointer )(p ) = newValue (step .elem )
}
p = *(*unsafe .Pointer )(p )
}
}
return p
}
func (fb *v2Fallback ) openRaw (p unsafe .Pointer ) (*[]byte , error ) {
b := (*[]byte )(fb .target (p ))
if len (*b ) == 0 {
*b = append (*b , '{' )
return b , nil
}
*b = bytes .TrimRight (*b , " \t\r\n" )
if len (*b ) == 0 || (*b )[len (*b )-1 ] != '}' {
return nil , errRawNotObject
}
*b = bytes .TrimRight ((*b )[:len (*b )-1 ], " \t\r\n" )
if n := len (*b ); n == 0 || (*b )[n -1 ] != ',' && (*b )[n -1 ] != '{' {
*b = append (*b , ',' )
}
return b , nil
}
func (fb *v2Fallback ) decodeMember (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer , start , end int64 ) (int64 , error ) {
quoted := ctx .Buf [start :end ]
target := fb .target (p )
if fb .mapType == nil {
b , err := fb .openRaw (p )
if err != nil {
return ctx .goOnAfter (&errors .UnmarshalError {GoType : jsonfields .RawValueType , Start : start , Err : err }, cursor , depth )
}
valueStart := skipWhiteSpace (ctx .Buf , cursor )
valueEnd , err := ctx .skipValueV2 (valueStart , depth )
if err != nil {
return 0 , &errors .UnmarshalError {GoType : jsonfields .RawValueType , Start : valueStart , Err : err }
}
*b = append (*b , quoted ...)
*b = append (*b , ':' )
*b = append (*b , ctx .Buf [valueStart :valueEnd ]...)
*b = append (*b , '}' )
return valueEnd , nil
}
m := valueAt (ptrTypeOf (fb .mapType ), target )
if m .IsNil () {
m .Set (reflect .MakeMap (fb .mapType ))
}
key := reflect .ValueOf (string (unquotedName (quoted ))).Convert (fb .mapType .Key ())
v := reflect .New (fb .mapType .Elem ())
if old := m .MapIndex (key ); old .IsValid () {
v .Elem ().Set (old )
}
next , err := fb .value .Decode (ctx , cursor , depth , v .UnsafePointer ())
m .SetMapIndex (key , v .Elem ())
return next , err
}
func (c *compiler ) compileMapV2 (typ reflect .Type , structName , fieldName string ) (Decoder , error ) {
if typ == interfaceMapType {
if iface := c .newV2InterfaceDecoder (emptyInterfaceType ); !iface .fromAny {
return &v2AnyMapDecoder {iface : iface }, nil
}
}
d := &v2MapDecoder {typ : typ , ptrType : ptrTypeOf (typ )}
if _ , exists := c .decoders [uintptr (runtime .TypePtr (typ ))]; !exists {
c .decoders [uintptr (runtime .TypePtr (typ ))] = d
defer delete (c .decoders , uintptr (runtime .TypePtr (typ )))
}
keyCompiler := &compiler {
decoders : map [uintptr ]Decoder {}, v2 : true , stringifyNumbers : true , v1Options : c .v1Options , mapKeys : true ,
funcs : c .funcs ,
}
keyDec , err := keyCompiler .compileV2 (typ .Key (), structName , fieldName )
if err != nil {
return nil , err
}
valueDec , err := compile (typ .Elem (), structName , fieldName , c )
if err != nil {
return nil , err
}
d .keyDecoder , d .valueDecoder = keyDec , c .goOnDecoder (valueDec )
return d , nil
}
type v2MapDecoder struct {
typ reflect .Type
ptrType unsafe .Pointer
keyDecoder Decoder
valueDecoder Decoder
}
var emptyStructType = reflect .TypeOf (struct {}{})
func uniqueKeyNames(dec Decoder , kind reflect .Kind , allowInvalidUTF8 bool ) bool {
switch dec .(type ) {
case *v2FuncDecoder , *v2UnmarshalFromDecoder , *v2UnmarshalJSONDecoder , *v2UnmarshalTextDecoder :
return false
}
switch kind {
case reflect .Bool ,
reflect .Int , reflect .Int8 , reflect .Int16 , reflect .Int32 , reflect .Int64 ,
reflect .Uint , reflect .Uint8 , reflect .Uint16 , reflect .Uint32 , reflect .Uint64 , reflect .Uintptr :
return true
case reflect .String :
return !allowInvalidUTF8
}
return false
}
func (d *v2MapDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
*(*unsafe .Pointer )(p ) = nil
return cursor + 4 , nil
case '{' :
default :
return ctx .skipTypeError (cursor , depth , d .typ )
}
depth ++
if depth > maxDecodeNestingDepth {
return 0 , errors .ErrExceededMaxDepth (buf [cursor ], cursor )
}
m := valueAt (d .ptrType , p )
if m .IsNil () {
m .Set (reflect .MakeMap (d .typ ))
}
cursor = skipWhiteSpace (buf , cursor +1 )
if buf [cursor ] == '}' {
return cursor + 1 , nil
}
rejectDuplicateNames := ctx .Option .V2 &V2AllowDuplicateNames == 0
var seen reflect .Value
if rejectDuplicateNames && m .Len () > 0 {
seen = reflect .MakeMap (reflect .MapOf (d .typ .Key (), emptyStructType ))
}
var names nameSet
keyNames := rejectDuplicateNames && !uniqueKeyNames (d .keyDecoder , d .typ .Key ().Kind (), ctx .Option .V2 &V2AllowInvalidUTF8 != 0 )
k , v := reflect .New (d .typ .Key ()), reflect .New (d .typ .Elem ())
for {
start := cursor
if buf [start ] != '"' {
return 0 , syntaxErrorAt (buf , start , whereKey )
}
k .Elem ().SetZero ()
next , err := d .keyDecoder .Decode (ctx , start , depth , k .UnsafePointer ())
if err != nil {
if next , err = ctx .goOnAfterKey (err , start , depth ); err != nil {
return 0 , err
}
if cursor = skipWhiteSpace (buf , next ); buf [cursor ] == '}' {
names .end (ctx .v2 )
return cursor + 1 , nil
}
cursor = skipWhiteSpace (buf , cursor +1 )
continue
}
if keyNames && !names .addCopy (ctx .V2Call (), nil , unquotedName (buf [start :next ])) {
return 0 , &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
key := k .Elem ()
if old := m .MapIndex (key ); old .IsValid () {
if rejectDuplicateNames && (!seen .IsValid () || seen .MapIndex (key ).IsValid ()) {
return 0 , &errors .UnmarshalError {Start : start , Err : errors .ErrDuplicateName }
}
if ctx .Option .V2 &V2MergeWithLegacySemantics == 0 {
v .Elem ().Set (old )
} else {
v .Elem ().SetZero ()
}
} else {
v .Elem ().SetZero ()
}
cursor = skipWhiteSpace (buf , next )
if buf [cursor ] != ':' {
return 0 , syntaxErrorAt (buf , cursor , whereAfterKey )
}
next , err = d .valueDecoder .Decode (ctx , cursor +1 , depth , v .UnsafePointer ())
m .SetMapIndex (key , v .Elem ())
if seen .IsValid () {
seen .SetMapIndex (key , reflect .Zero (emptyStructType ))
}
if err != nil {
return 0 , err
}
cursor = skipWhiteSpace (buf , next )
switch buf [cursor ] {
case '}' :
names .end (ctx .v2 )
return cursor + 1 , nil
case ',' :
cursor = skipWhiteSpace (buf , cursor +1 )
default :
return 0 , syntaxErrorAt (buf , cursor , whereAfterPair )
}
}
}
func (d *v2MapDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
type v2AnyMapDecoder struct {
iface *v2InterfaceDecoder
}
func (d *v2AnyMapDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
*(*unsafe .Pointer )(p ) = nil
return cursor + 4 , nil
case '{' :
default :
return ctx .skipTypeError (cursor , depth , interfaceMapType )
}
m := *(*map [string ]any )(p )
var v any
var next int64
var err error
if m == nil {
next , err = d .iface .Decode (ctx , cursor , depth , unsafe .Pointer (&v ))
} else {
v = m
next , err = d .iface .decodeMerging (ctx , cursor , depth , unsafe .Pointer (&v ))
}
if m , ok := v .(map [string ]any ); ok {
*(*map [string ]any )(p ) = m
}
return next , err
}
func (d *v2AnyMapDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
return nil , 0 , fmt .Errorf ("json: v2 decoder does not support decode path" )
}
The pages are generated with Golds v0.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 .