package decoder
import (
"encoding/json"
"reflect"
"strconv"
"unsafe"
"github.com/goccy/go-json/internal/errors"
"github.com/goccy/go-json/internal/runtime"
)
type interfaceDecoder struct {
typ reflect .Type
hasMethods bool
values runtime .TypeCache [ifaceValueDecoder ]
structName string
fieldName string
sliceDecoder *sliceDecoder
mapDecoder *mapDecoder
floatDecoder *floatDecoder
numberDecoder *numberDecoder
stringDecoder *stringDecoder
}
func newEmptyInterfaceDecoder(structName , fieldName string ) *interfaceDecoder {
ifaceDecoder := &interfaceDecoder {
typ : emptyInterfaceType ,
structName : structName ,
fieldName : fieldName ,
floatDecoder : newFloatDecoder (structName , fieldName , func (p unsafe .Pointer , v float64 ) {
*(*any )(p ) = v
}),
numberDecoder : newNumberDecoder (structName , fieldName , func (p unsafe .Pointer , v json .Number ) {
*(*any )(p ) = v
}),
stringDecoder : newStringDecoder (structName , fieldName ),
}
ifaceDecoder .sliceDecoder = newSliceDecoder (
ifaceDecoder ,
emptyInterfaceType ,
emptyInterfaceType .Size (),
structName , fieldName ,
)
ifaceDecoder .mapDecoder = newMapDecoder (
interfaceMapType ,
stringType ,
ifaceDecoder .stringDecoder ,
interfaceMapType .Elem (),
ifaceDecoder ,
structName ,
fieldName ,
)
return ifaceDecoder
}
func newInterfaceDecoder(typ reflect .Type , structName , fieldName string ) *interfaceDecoder {
emptyIfaceDecoder := newEmptyInterfaceDecoder (structName , fieldName )
stringDecoder := newStringDecoder (structName , fieldName )
return &interfaceDecoder {
typ : typ ,
hasMethods : typ .NumMethod () > 0 ,
structName : structName ,
fieldName : fieldName ,
sliceDecoder : newSliceDecoder (
emptyIfaceDecoder ,
emptyInterfaceType ,
emptyInterfaceType .Size (),
structName , fieldName ,
),
mapDecoder : newMapDecoder (
interfaceMapType ,
stringType ,
stringDecoder ,
interfaceMapType .Elem (),
emptyIfaceDecoder ,
structName ,
fieldName ,
),
floatDecoder : newFloatDecoder (structName , fieldName , func (p unsafe .Pointer , v float64 ) {
*(*any )(p ) = v
}),
numberDecoder : newNumberDecoder (structName , fieldName , func (p unsafe .Pointer , v json .Number ) {
*(*any )(p ) = v
}),
stringDecoder : stringDecoder ,
}
}
var (
emptyInterfaceType = reflect .TypeOf ((*any )(nil )).Elem ()
EmptyInterfaceType = emptyInterfaceType
interfaceMapType = reflect .TypeOf ((*map [string ]any )(nil )).Elem ()
stringType = reflect .TypeOf ("" )
)
type emptyInterface struct {
typ unsafe .Pointer
ptr unsafe .Pointer
}
func (d *interfaceDecoder ) Decode (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
if d .hasMethods {
return d .decodeWithMethods (ctx , cursor , depth , p )
}
h := (*emptyInterface )(p )
if h .ptr == nil {
return d .decodeEmptyInterface (ctx , cursor , depth , p )
}
v := d .values .Load (uintptr (h .typ ))
if v == nil {
var err error
if v , err = d .valueDecoderOf (ctx , h .typ , *(*any )(p )); err != nil {
return 0 , err
}
}
return d .decodeValue (ctx , cursor , depth , p , v , h .ptr )
}
type ifaceValueKind uint8
const (
ifaceValueReplaced ifaceValueKind = iota
ifaceValuePointee
ifaceValueKept
)
type ifaceValueDecoder struct {
kind ifaceValueKind
dec Decoder
textType reflect .Type
}
func (d *interfaceDecoder ) valueDecoderOf (ctx *RuntimeContext , key unsafe .Pointer , iface any ) (*ifaceValueDecoder , error ) {
v := &ifaceValueDecoder {kind : ifaceValueReplaced }
if d .hasMethods {
v .kind = ifaceValueKept
}
if typ := reflect .TypeOf (iface ); typ .Kind () == reflect .Ptr && typ .Elem () != d .typ {
dec , err := ctx .DecoderOf ((*emptyInterface )(unsafe .Pointer (&iface )).typ )
if err != nil {
return nil , err
}
v .kind , v .dec = ifaceValuePointee , dec
if text , ok := dec .(*unmarshalTextDecoder ); ok {
v .textType = text .typ
}
}
return d .values .Store (uintptr (key ), v ), nil
}
func (d *interfaceDecoder ) decodeValue (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer , v *ifaceValueDecoder , ptr unsafe .Pointer ) (int64 , error ) {
switch v .kind {
case ifaceValueReplaced :
return d .decodeEmptyInterface (ctx , cursor , depth , p )
case ifaceValuePointee :
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
if buf [cursor ] == 'n' {
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
*(*[2 ]unsafe .Pointer )(p ) = [2 ]unsafe .Pointer {}
return cursor + 4 , nil
}
if v .textType != nil && isOtherValue (buf [cursor ], stringValue ) {
return ctx .textUnmarshalerKindError (cursor , depth , v .textType )
}
return v .dec .Decode (ctx , cursor , depth , ptr )
}
return d .decodeKept (ctx , cursor , depth , p )
}
func (d *interfaceDecoder ) decodeKept (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
if buf [cursor ] == 'n' {
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
*(*[2 ]unsafe .Pointer )(p ) = [2 ]unsafe .Pointer {}
return cursor + 4 , nil
}
*(*[2 ]unsafe .Pointer )(p ) = [2 ]unsafe .Pointer {}
first := ctx .typeError == nil
next , err := ctx .skipTypeError (cursor , depth , d .typ )
if err == nil && first {
ctx .typeError .atStart = true
}
return next , err
}
type nonEmptyInterface struct {
itab unsafe .Pointer
ptr unsafe .Pointer
}
func (d *interfaceDecoder ) decodeWithMethods (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
h := (*nonEmptyInterface )(p )
if h .itab == nil || h .ptr == nil {
return d .decodeKept (ctx , cursor , depth , p )
}
v := d .values .Load (uintptr (h .itab ))
if v == nil {
var err error
if v , err = d .valueDecoderOf (ctx , h .itab , reflect .NewAt (d .typ , p ).Elem ().Interface ()); err != nil {
return 0 , err
}
}
return d .decodeValue (ctx , cursor , depth , p , v , h .ptr )
}
func decodeFloatSlow(ctx *RuntimeContext , cursor int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
end , err := numberEnd (buf , cursor )
if err != nil {
return 0 , err
}
b := buf [cursor :end ]
f , parseErr := strconv .ParseFloat (*(*string )(unsafe .Pointer (&b )), 64 )
if inRange := parseErr == nil ; !inRange {
ctx .numberTypeError (cursor , end , float64Type )
f = 0
}
**(**any )(unsafe .Pointer (&p )) = f
return end , nil
}
func (d *interfaceDecoder ) decodeEmptyInterface (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case '{' :
depth ++
if depth > maxDecodeNestingDepth {
return 0 , errors .ErrExceededMaxDepth (buf [cursor ], cursor )
}
m , cursor , err := decodeNewStringAnyMap (ctx , d , cursor , depth )
if err != nil {
return 0 , err
}
**(**any )(unsafe .Pointer (&p )) = m
return cursor , nil
case '[' :
return d .decodeAnySlice (ctx , cursor , depth , p )
case '-' , '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' :
if (ctx .Option .Flags & UseNumberOption ) != 0 {
return d .numberDecoder .Decode (ctx , cursor , depth , p )
}
if f , next , ok := parseFloatFast (buf , cursor ); ok && validEndNumberChar [buf [next ]] {
**(**any )(unsafe .Pointer (&p )) = f
return next , nil
}
return decodeFloatSlow (ctx , cursor , p )
case '"' :
if end := plainStringEnd (buf , cursor +1 ); end >= 0 {
**(**any )(unsafe .Pointer (&p )) = ctx .makeString (buf [cursor +1 : end ])
return end + 1 , nil
}
s , c , _ , err := d .stringDecoder .decodeString (ctx , cursor )
if err != nil {
return 0 , err
}
**(**any )(unsafe .Pointer (&p )) = s
return c , nil
case 't' :
if err := validateTrue (buf , cursor ); err != nil {
return 0 , err
}
cursor += 4
**(**any )(unsafe .Pointer (&p )) = true
return cursor , nil
case 'f' :
if err := validateFalse (buf , cursor ); err != nil {
return 0 , err
}
cursor += 5
**(**any )(unsafe .Pointer (&p )) = false
return cursor , nil
case 'n' :
if err := validateNull (buf , cursor ); err != nil {
return 0 , err
}
cursor += 4
**(**any )(unsafe .Pointer (&p )) = nil
return cursor , nil
}
return cursor , errors .ErrInvalidBeginningOfValue (buf [cursor ], cursor )
}
func decodeStringAnyMap(ctx *RuntimeContext , d *interfaceDecoder , m map [string ]any , cursor , depth int64 ) (int64 , error ) {
buf := ctx .Buf
cursor ++
cursor = skipWhiteSpace (buf , cursor )
if buf [cursor ] == '}' {
return cursor + 1 , nil
}
for {
key , c , ok , err := d .stringDecoder .decodeString (ctx , cursor )
if err != nil {
return 0 , err
}
if !ok {
return 0 , errors .ErrSyntax ("invalid character 'n' looking for beginning of object key string" , skipWhiteSpace (buf , cursor )+1 )
}
cursor = skipWhiteSpace (buf , c )
if buf [cursor ] != ':' {
return 0 , errors .ErrExpected ("colon after object key" , cursor )
}
cursor ++
c , err = d .decodeEmptyInterface (ctx , cursor , depth , unsafe .Pointer (&ctx .slot ))
if err != nil {
ctx .slot = nil
return 0 , err
}
m [key ] = ctx .slot
ctx .slot = nil
cursor = skipWhiteSpace (buf , c )
switch buf [cursor ] {
case '}' :
return cursor + 1 , nil
case ',' :
cursor ++
default :
return 0 , errors .ErrExpected ("comma after object value" , cursor )
}
}
}
func decodeNewStringAnyMap(ctx *RuntimeContext , d *interfaceDecoder , cursor , depth int64 ) (map [string ]any , int64 , error ) {
buf := ctx .Buf
cursor ++
cursor = skipWhiteSpace (buf , cursor )
if buf [cursor ] == '}' {
return map [string ]any {}, cursor + 1 , nil
}
base := len (ctx .entryStack )
fail := func (err error ) (map [string ]any , int64 , error ) {
ctx .slot = nil
ctx .popEntries (base )
return nil , 0 , err
}
for {
if cursor = skipWhiteSpace (buf , cursor ); buf [cursor ] != '"' {
return fail (syntaxErrorAt (buf , cursor , whereKey ))
}
var key string
var c int64
if end := plainStringEnd (buf , cursor +1 ); end >= 0 {
key , c = ctx .makeString (buf [cursor +1 :end ]), end +1
} else {
var err error
if key , c , _, err = d .stringDecoder .decodeString (ctx , cursor ); err != nil {
return fail (err )
}
}
cursor = skipWhiteSpace (buf , c )
if buf [cursor ] != ':' {
return fail (syntaxErrorAt (buf , cursor , whereAfterKey ))
}
cursor ++
c , err := d .decodeEmptyInterface (ctx , cursor , depth , unsafe .Pointer (&ctx .slot ))
if err != nil {
return fail (err )
}
ctx .entryStack = append (ctx .entryStack , anyEntry {key : key , value : ctx .slot })
ctx .slot = nil
cursor = skipWhiteSpace (buf , c )
switch buf [cursor ] {
case '}' :
entries := ctx .entryStack [base :]
m := make (map [string ]any , len (entries ))
for i := range entries {
m [entries [i ].key ] = entries [i ].value
}
ctx .popEntries (base )
if len (m ) != len (entries ) && ctx .Option .V2 != 0 {
return nil , 0 , errV2DuplicateName
}
return m , cursor + 1 , nil
case ',' :
cursor ++
default :
return fail (errors .ErrExpected ("comma after object value" , cursor ))
}
}
}
var emptyAnySlice any = []any {}
func (d *interfaceDecoder ) decodeAnySlice (ctx *RuntimeContext , cursor , depth int64 , p unsafe .Pointer ) (int64 , error ) {
buf := ctx .Buf
depth ++
if depth > maxDecodeNestingDepth {
return 0 , errors .ErrExceededMaxDepth (buf [cursor ], cursor )
}
cursor ++
cursor = skipWhiteSpace (buf , cursor )
if buf [cursor ] == ']' {
**(**any )(unsafe .Pointer (&p )) = emptyAnySlice
return cursor + 1 , nil
}
base := len (ctx .anyStack )
for {
c , err := d .decodeEmptyInterface (ctx , cursor , depth , unsafe .Pointer (&ctx .slot ))
if err != nil {
ctx .slot = nil
ctx .popAny (base )
return 0 , err
}
ctx .anyStack = append (ctx .anyStack , ctx .slot )
ctx .slot = nil
cursor = skipWhiteSpace (buf , c )
switch buf [cursor ] {
case ']' :
elems := make ([]any , len (ctx .anyStack )-base )
copy (elems , ctx .anyStack [base :])
ctx .popAny (base )
**(**any )(unsafe .Pointer (&p )) = elems
return cursor + 1 , nil
case ',' :
cursor ++
default :
ctx .popAny (base )
return 0 , errors .ErrInvalidCharacter (buf [cursor ], "slice" , cursor )
}
}
}
func NewPathDecoder () Decoder {
ifaceDecoder := &interfaceDecoder {
typ : emptyInterfaceType ,
structName : "" ,
fieldName : "" ,
floatDecoder : newFloatDecoder ("" , "" , func (p unsafe .Pointer , v float64 ) {
*(*any )(p ) = v
}),
numberDecoder : newNumberDecoder ("" , "" , func (p unsafe .Pointer , v json .Number ) {
*(*any )(p ) = v
}),
stringDecoder : newStringDecoder ("" , "" ),
}
ifaceDecoder .sliceDecoder = newSliceDecoder (
ifaceDecoder ,
emptyInterfaceType ,
emptyInterfaceType .Size (),
"" , "" ,
)
ifaceDecoder .mapDecoder = newMapDecoder (
interfaceMapType ,
stringType ,
ifaceDecoder .stringDecoder ,
interfaceMapType .Elem (),
ifaceDecoder ,
"" , "" ,
)
return ifaceDecoder
}
func (d *interfaceDecoder ) DecodePath (ctx *RuntimeContext , cursor , depth int64 ) ([][]byte , int64 , error ) {
buf := ctx .Buf
cursor = skipWhiteSpace (buf , cursor )
switch buf [cursor ] {
case '{' :
return d .mapDecoder .DecodePath (ctx , cursor , depth )
case '[' :
return d .sliceDecoder .DecodePath (ctx , cursor , depth )
}
end , err := skipValue (buf , cursor , depth )
if err != nil {
return nil , 0 , err
}
return nil , end , nil
}
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 .