package decoder

import (
	
	
	
	

	
	
)

type interfaceDecoder struct {
	typ reflect.Type
	// hasMethods is set for an interface type which has methods, whose value is not replaced by the decoded value
	// ( see decodeWithMethods ): the value of an interface{} is read without reflect ( see Decode ).
	hasMethods bool
	// values are how the values of the types which the interface value holds are decoded, by the type of an
	// interface{}, or by the itab of an interface type with methods ( see valueDecoderOf ).
	values        runtime.TypeCache[ifaceValueDecoder]
	structName    string
	fieldName     string
	sliceDecoder  *sliceDecoder
	mapDecoder    *mapDecoder
	floatDecoder  *floatDecoder
	numberDecoder *numberDecoder
	stringDecoder *stringDecoder
}

func newEmptyInterfaceDecoder(,  string) *interfaceDecoder {
	 := &interfaceDecoder{
		typ:        emptyInterfaceType,
		structName: ,
		fieldName:  ,
		floatDecoder: newFloatDecoder(, , func( unsafe.Pointer,  float64) {
			*(*any)() = 
		}),
		numberDecoder: newNumberDecoder(, , func( unsafe.Pointer,  json.Number) {
			*(*any)() = 
		}),
		stringDecoder: newStringDecoder(, ),
	}
	.sliceDecoder = newSliceDecoder(
		,
		emptyInterfaceType,
		emptyInterfaceType.Size(),
		, ,
	)
	.mapDecoder = newMapDecoder(
		interfaceMapType,
		stringType,
		.stringDecoder,
		interfaceMapType.Elem(),
		,
		,
		,
	)
	return 
}

func newInterfaceDecoder( reflect.Type, ,  string) *interfaceDecoder {
	 := newEmptyInterfaceDecoder(, )
	 := newStringDecoder(, )
	return &interfaceDecoder{
		typ:        ,
		hasMethods: .NumMethod() > 0,
		structName: ,
		fieldName:  ,
		sliceDecoder: newSliceDecoder(
			,
			emptyInterfaceType,
			emptyInterfaceType.Size(),
			, ,
		),
		mapDecoder: newMapDecoder(
			interfaceMapType,
			stringType,
			,
			interfaceMapType.Elem(),
			,
			,
			,
		),
		floatDecoder: newFloatDecoder(, , func( unsafe.Pointer,  float64) {
			*(*any)() = 
		}),
		numberDecoder: newNumberDecoder(, , func( unsafe.Pointer,  json.Number) {
			*(*any)() = 
		}),
		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 ( *interfaceDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	if .hasMethods {
		return .decodeWithMethods(, , , )
	}
	// p is an interface{}: a nil one, the most common, is decoded as it is, and the value of another one may be
	// decoded into what it points to
	 := (*emptyInterface)()
	if .ptr == nil {
		return .decodeEmptyInterface(, , , )
	}
	 := .values.Load(uintptr(.typ))
	if  == nil {
		var  error
		if ,  = .valueDecoderOf(, .typ, *(*any)());  != nil {
			return 0, 
		}
	}
	return .decodeValue(, , , , , .ptr)
}

// ifaceValueKind is how the value which an interface value holds is decoded, as encoding/json does.
type ifaceValueKind uint8

const (
	// ifaceValueReplaced is a value of an interface{} which is replaced by the value decoded as the one of an
	// interface{}.
	ifaceValueReplaced ifaceValueKind = iota
	// ifaceValuePointee is a pointer to a value which is not an interface value: the value is decoded into what it
	// points to, as a value of the pointer type, whose unmarshalers are used.
	ifaceValuePointee
	// ifaceValueKept is a value of an interface type with methods which is not a pointer: nothing is decoded into it,
	// and the interface value is set to nil ( see decodeKept ).
	ifaceValueKept
)

// ifaceValueDecoder is how a value of a type which an interface value holds is decoded, which depends on the type
// only: it is found once for a type.
type ifaceValueDecoder struct {
	kind ifaceValueKind
	// dec is the decoder of a pointer of ifaceValuePointee.
	dec Decoder
	// textType is the pointer type of ifaceValuePointee which implements encoding.TextUnmarshaler: a value which
	// is not a string is a type error of the value it points to ( see textUnmarshalerKindError ).
	textType reflect.Type
}

// valueDecoderOf finds how the value iface, of the type typ, which the interface value holds is decoded, and
// keeps it for the type by key: the type of an interface{}, or the itab of an interface type with methods.
func ( *interfaceDecoder) ( *RuntimeContext,  unsafe.Pointer,  any) (*ifaceValueDecoder, error) {
	 := &ifaceValueDecoder{kind: ifaceValueReplaced}
	if .hasMethods {
		.kind = ifaceValueKept
	}
	if  := reflect.TypeOf(); .Kind() == reflect.Ptr && .Elem() != .typ {
		,  := .DecoderOf((*emptyInterface)(unsafe.Pointer(&)).typ)
		if  != nil {
			return nil, 
		}
		.kind, .dec = ifaceValuePointee, 
		if ,  := .(*unmarshalTextDecoder);  {
			.textType = .typ
		}
	}
	return .values.Store(uintptr(), ), nil
}

// decodeValue decodes the value at cursor into the interface value at p, which holds a value decoded as v says,
// whose data word is ptr.
func ( *interfaceDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer,  *ifaceValueDecoder,  unsafe.Pointer) (int64, error) {
	switch .kind {
	case ifaceValueReplaced:
		return .decodeEmptyInterface(, , , )
	case ifaceValuePointee:
		 := .Buf
		 = skipWhiteSpace(, )
		if [] == 'n' {
			// null sets the interface value to nil, not what it points to
			if  := validateNull(, );  != nil {
				return 0, 
			}
			*(*[2]unsafe.Pointer)() = [2]unsafe.Pointer{}
			return  + 4, nil
		}
		if .textType != nil && isOtherValue([], stringValue) {
			return .textUnmarshalerKindError(, , .textType)
		}
		return .dec.Decode(, , , )
	}
	return .decodeKept(, , , )
}

// decodeKept decodes the value at cursor into the interface value at p of an interface type with methods, whose
// value is not decoded into: null sets it to nil, and any other value is a type error at the start of the value,
// which sets it to nil too, as encoding/json does.
func ( *interfaceDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	if [] == 'n' {
		if  := validateNull(, );  != nil {
			return 0, 
		}
		*(*[2]unsafe.Pointer)() = [2]unsafe.Pointer{}
		return  + 4, nil
	}
	*(*[2]unsafe.Pointer)() = [2]unsafe.Pointer{}
	 := .typeError == nil
	,  := .skipTypeError(, , .typ)
	if  == nil &&  {
		.typeError.atStart = true
	}
	return , 
}

// nonEmptyInterface is the layout of a value of an interface type with methods: the itab of the type it holds,
// which is nil for a nil value, and the data word.
type nonEmptyInterface struct {
	itab unsafe.Pointer
	ptr  unsafe.Pointer
}

// decodeWithMethods decodes the value of an interface type which has methods: a value which is a pointer is
// decoded into what it points to, as encoding/json does. How a value is decoded is kept by its itab, which is of
// one type for the interface type of the decoder.
func ( *interfaceDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := (*nonEmptyInterface)()
	if .itab == nil || .ptr == nil {
		// a nil value, or a nil pointer
		return .decodeKept(, , , )
	}
	 := .values.Load(uintptr(.itab))
	if  == nil {
		var  error
		if ,  = .valueDecoderOf(, .itab, reflect.NewAt(.typ, ).Elem().Interface());  != nil {
			return 0, 
		}
	}
	return .decodeValue(, , , , , .ptr)
}

// decodeFloatSlow decodes the number at cursor into the interface{} at p, which the fast parse doesn't: a number
// which is not valid by the grammar is a syntax error, and a number out of the range of a float64 is a type error,
// after which the decoding goes on, which stores 0, as encoding/json does from Go 1.27.2. It is not inlined, so
// that the decoding of the values of interface{} keeps the size it had.
//
//go:noinline
func decodeFloatSlow( *RuntimeContext,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	,  := numberEnd(, )
	if  != nil {
		return 0, 
	}
	 := [:]
	,  := strconv.ParseFloat(*(*string)(unsafe.Pointer(&)), 64)
	// a number of the grammar which ParseFloat fails is out of the range of float64
	if  :=  == nil; ! {
		.numberTypeError(, , float64Type)
		 = 0
	}
	**(**any)(unsafe.Pointer(&)) = 
	return , nil
}

func ( *interfaceDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	switch [] {
	case '{':
		++
		if  > maxDecodeNestingDepth {
			return 0, errors.ErrExceededMaxDepth([], )
		}
		, ,  := decodeNewStringAnyMap(, , , )
		if  != nil {
			return 0, 
		}
		**(**any)(unsafe.Pointer(&)) = 
		return , nil
	case '[':
		return .decodeAnySlice(, , , )
	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		if (.Option.Flags & UseNumberOption) != 0 {
			return .numberDecoder.Decode(, , , )
		}
		if , ,  := parseFloatFast(, );  && validEndNumberChar[[]] {
			**(**any)(unsafe.Pointer(&)) = 
			return , nil
		}
		return decodeFloatSlow(, , )
	case '"':
		if  := plainStringEnd(, +1);  >= 0 {
			**(**any)(unsafe.Pointer(&)) = .makeString([+1 : ])
			return  + 1, nil
		}
		, , ,  := .stringDecoder.decodeString(, )
		if  != nil {
			return 0, 
		}
		**(**any)(unsafe.Pointer(&)) = 
		return , nil
	case 't':
		if  := validateTrue(, );  != nil {
			return 0, 
		}
		 += 4
		**(**any)(unsafe.Pointer(&)) = true
		return , nil
	case 'f':
		if  := validateFalse(, );  != nil {
			return 0, 
		}
		 += 5
		**(**any)(unsafe.Pointer(&)) = false
		return , nil
	case 'n':
		if  := validateNull(, );  != nil {
			return 0, 
		}
		 += 4
		**(**any)(unsafe.Pointer(&)) = nil
		return , nil
	}
	return , errors.ErrInvalidBeginningOfValue([], )
}

// decodeStringAnyMap decodes the object at cursor into m, a map[string]interface{}, by the assignment of Go:
// the values are decoded as interface{} by d. depth counts the object already.
func decodeStringAnyMap( *RuntimeContext,  *interfaceDecoder,  map[string]any, ,  int64) (int64, error) {
	 := .Buf
	++ // '{'
	 = skipWhiteSpace(, )
	if [] == '}' {
		return  + 1, nil
	}
	for {
		, , ,  := .stringDecoder.decodeString(, )
		if  != nil {
			return 0, 
		}
		if ! {
			// null is not a key
			return 0, errors.ErrSyntax("invalid character 'n' looking for beginning of object key string", skipWhiteSpace(, )+1)
		}
		 = skipWhiteSpace(, )
		if [] != ':' {
			return 0, errors.ErrExpected("colon after object key", )
		}
		++
		,  = .decodeEmptyInterface(, , , unsafe.Pointer(&.slot))
		if  != nil {
			.slot = nil
			return 0, 
		}
		[] = .slot
		.slot = nil
		 = skipWhiteSpace(, )
		switch [] {
		case '}':
			return  + 1, nil
		case ',':
			++
		default:
			return 0, errors.ErrExpected("comma after object value", )
		}
	}
}

// decodeNewStringAnyMap decodes the object at cursor into a new map[string]interface{}. The entries are pushed
// to the stack of entries of the context, each key with its value, and put into a map of their number at the end
// of the object: a map filled entry by entry grows and moves its entries several times on the way, which took
// more time than the entries themselves. A key which is repeated is put later, so that the last one wins as in a
// map filled in order.
func decodeNewStringAnyMap( *RuntimeContext,  *interfaceDecoder, ,  int64) (map[string]any, int64, error) {
	 := .Buf
	++ // '{'
	 = skipWhiteSpace(, )
	if [] == '}' {
		return map[string]any{},  + 1, nil
	}
	 := len(.entryStack)
	 := func( error) (map[string]any, int64, error) {
		.slot = nil
		.popEntries()
		return nil, 0, 
	}
	for {
		if  = skipWhiteSpace(, ); [] != '"' {
			return (syntaxErrorAt(, , whereKey))
		}
		var  string
		var  int64
		if  := plainStringEnd(, +1);  >= 0 {
			,  = .makeString([+1:]), +1
		} else {
			var  error
			if , , _,  = .stringDecoder.decodeString(, );  != nil {
				return ()
			}
		}
		 = skipWhiteSpace(, )
		if [] != ':' {
			return (syntaxErrorAt(, , whereAfterKey))
		}
		++
		,  := .decodeEmptyInterface(, , , unsafe.Pointer(&.slot))
		if  != nil {
			return ()
		}
		// the key and the value are pushed together, after the value, whose own entries are popped already.
		.entryStack = append(.entryStack, anyEntry{key: , value: .slot})
		.slot = nil
		 = skipWhiteSpace(, )
		switch [] {
		case '}':
			 := .entryStack[:]
			 := make(map[string]any, len())
			for  := range  {
				[[].key] = [].value
			}
			.popEntries()
			if len() != len() && .Option.V2 != 0 {
				// a name which the object has twice, which the semantics of v2 reject or merge
				return nil, 0, errV2DuplicateName
			}
			return ,  + 1, nil
		case ',':
			++
		default:
			return (errors.ErrExpected("comma after object value", ))
		}
	}
}

// emptyAnySlice is the value of an empty array as interface{}: an empty []interface{}, which all of them share,
// so that it is not allocated for each. It has no room for an element, so that nothing is written through it.
var emptyAnySlice any = []any{}

// decodeAnySlice decodes the array at cursor as a []interface{}: the elements are pushed to the stack
// of the context, and copied into a slice of their number at the end of the array.
func ( *interfaceDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	++
	if  > maxDecodeNestingDepth {
		return 0, errors.ErrExceededMaxDepth([], )
	}
	++ // '['
	 = skipWhiteSpace(, )
	if [] == ']' {
		**(**any)(unsafe.Pointer(&)) = emptyAnySlice
		return  + 1, nil
	}
	 := len(.anyStack)
	for {
		,  := .decodeEmptyInterface(, , , unsafe.Pointer(&.slot))
		if  != nil {
			.slot = nil
			.popAny()
			return 0, 
		}
		.anyStack = append(.anyStack, .slot)
		.slot = nil
		 = skipWhiteSpace(, )
		switch [] {
		case ']':
			 := make([]any, len(.anyStack)-)
			copy(, .anyStack[:])
			.popAny()
			**(**any)(unsafe.Pointer(&)) = 
			return  + 1, nil
		case ',':
			++
		default:
			.popAny()
			return 0, errors.ErrInvalidCharacter([], "slice", )
		}
	}
}

func () Decoder {
	 := &interfaceDecoder{
		typ:        emptyInterfaceType,
		structName: "",
		fieldName:  "",
		floatDecoder: newFloatDecoder("", "", func( unsafe.Pointer,  float64) {
			*(*any)() = 
		}),
		numberDecoder: newNumberDecoder("", "", func( unsafe.Pointer,  json.Number) {
			*(*any)() = 
		}),
		stringDecoder: newStringDecoder("", ""),
	}
	.sliceDecoder = newSliceDecoder(
		,
		emptyInterfaceType,
		emptyInterfaceType.Size(),
		"", "",
	)
	.mapDecoder = newMapDecoder(
		interfaceMapType,
		stringType,
		.stringDecoder,
		interfaceMapType.Elem(),
		,
		"", "",
	)
	return 
}

// DecodePath returns the values of the rest of the path, which is not empty: the object or the array decodes them,
// and any other value, which has no member or element, has none.
func ( *interfaceDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	switch [] {
	case '{':
		return .mapDecoder.DecodePath(, , )
	case '[':
		return .sliceDecoder.DecodePath(, , )
	}
	,  := skipValue(, , )
	if  != nil {
		return nil, 0, 
	}
	return nil, , nil
}