package decoder

import (
	
	
	

	
	
)

type mapDecoder struct {
	mapType   reflect.Type
	keyType   reflect.Type
	valueType reflect.Type
	// mapTypePtr, keyPtrType and valuePtrType are the type descriptors of the map, of *K and of *V.
	mapTypePtr   unsafe.Pointer
	keyPtrType   unsafe.Pointer
	valuePtrType unsafe.Pointer
	// isStringAnyMap is whether the map is a map[string]interface{}, which is decoded without reflect.
	isStringAnyMap bool
	keyDecoder     Decoder
	valueDecoder   Decoder
	// keyUnsupported is set for a map whose keys are not decoded ( see mapKeySupported ): an object is a type
	// error.
	keyUnsupported bool
	structName     string
	fieldName      string
	// temps holds the zero values which the key and the value of an entry are decoded into ( see mapTemps ).
	temps sync.Pool
}

// mapTemps are the zero values of the key and of the value of a map, into which the key and the value of every
// entry are decoded, which reflect.Value.SetMapIndex copies into the map, and which are zeroed after it: a
// decoder keeps them in a pool, so that a map is decoded without allocating them.
type mapTemps struct {
	k, v   unsafe.Pointer
	kv, vv reflect.Value
}

func newMapDecoder( reflect.Type,  reflect.Type,  Decoder,  reflect.Type,  Decoder, ,  string) *mapDecoder {
	 := &mapDecoder{
		mapType:        ,
		keyDecoder:     ,
		keyType:        ,
		valueType:      ,
		mapTypePtr:     runtime.TypePtr(),
		keyPtrType:     ptrTypeOf(),
		valuePtrType:   ptrTypeOf(),
		isStringAnyMap:  == interfaceMapType,
		valueDecoder:   ,
		keyUnsupported: !mapKeySupported(, ),
		structName:     ,
		fieldName:      ,
	}
	.temps.New = func() any {
		 := &mapTemps{k: newValue(), v: newValue()}
		.kv, .vv = valueAt(.keyPtrType, .k), valueAt(.valuePtrType, .v)
		return 
	}
	return 
}

// mapValue returns the reflect.Value of the map m.
func ( *mapDecoder) ( unsafe.Pointer) reflect.Value {
	// A map is a pointer in an interface value.
	return reflect.ValueOf(*(*any)(unsafe.Pointer(&emptyInterface{typ: .mapTypePtr, ptr: })))
}

// decodeEntries decodes the entries of the object from cursor into the map, whose keys and values are decoded into
// k and v, as Decode does, but the entries whose keys are of another type ( see errMapKeyType ), which are dropped.
// If afterKey is set, cursor is after the key of such an entry, whose value is decoded first. It is a function of
// its own, so that Decode keeps the size it had: such a key is rare.
//
//go:noinline
func ( *mapDecoder) ( *RuntimeContext, ,  int64, , , ,  unsafe.Pointer,  bool) (int64, error) {
	 := .Buf
	 := .mapValue()
	 := valueAt(.keyPtrType, )
	 := valueAt(.valuePtrType, )
	for {
		 := 
		if ! {
			,  := .keyDecoder.Decode(, , , )
			if  != nil &&  != errMapKeyType {
				return 0, 
			}
			if [-1] != '"' {
				return 0, errKeyNotString(, )
			}
			 =  != nil
			 = 
		}
		 = false
		 = skipWhiteSpace(, )
		if [] != ':' {
			return 0, errors.ErrExpected("colon after object key", )
		}
		var  int64
		var  error
		if  {
			// the value of an entry which is dropped is skipped, as encoding/json does
			,  = skipValue(, +1, )
		} else if ,  = .valueDecoder.Decode(, +1, , );  == nil {
			.SetMapIndex(, )
		}
		if  != nil {
			return 0, 
		}
		.SetZero()
		.SetZero()
		 = skipWhiteSpace(, )
		if [] == '}' {
			**(**unsafe.Pointer)(unsafe.Pointer(&)) = 
			return  + 1, nil
		}
		if [] != ',' {
			return 0, errors.ErrExpected("comma after object value", )
		}
		++
	}
}

// errKeyNotString returns the syntax error of the key of an object at cursor, which is not a string.
//
//go:noinline
func errKeyNotString( []byte,  int64) error {
	 = skipWhiteSpace(, )
	return errors.ErrInvalidBeginningOfValue([], )
}

// 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:noinline
func ( *mapDecoder) ( *RuntimeContext, ,  int64) (int64, error) {
	if isOtherValue(.Buf[], objectValue) {
		return .skipTypeError(, , .mapType)
	}
	return 0, errors.ErrExpected("{ character for map value", )
}

func ( *mapDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	 := int64(len())
	if  < 2 {
		return 0, errors.ErrExpected("{} for map", )
	}
	switch [] {
	case 'n':
		if  := validateNull(, );  != nil {
			return 0, 
		}
		 += 4
		**(**unsafe.Pointer)(unsafe.Pointer(&)) = nil
		return , nil
	case '{':
		// only an object nests its values one level deeper: null or another value at the limit is not too deep
		++
		if  > maxDecodeNestingDepth {
			return 0, errors.ErrExceededMaxDepth([], )
		}
	default:
		return .decodeOther(, , )
	}
	if .keyUnsupported {
		return .unsupportedMapKeys(, , -1, )
	}
	if .isStringAnyMap {
		 := *(*map[string]any)()
		if  == nil {
			, ,  := decodeNewStringAnyMap(, .valueDecoder.(*interfaceDecoder), , )
			if  != nil {
				return 0, 
			}
			*(*map[string]any)() = 
			return , nil
		}
		,  := decodeStringAnyMap(, .valueDecoder.(*interfaceDecoder), , , )
		if  != nil {
			return 0, 
		}
		return , nil
	}
	++
	 = skipWhiteSpace(, )
	 := *(*unsafe.Pointer)()
	if  == nil {
		 = reflect.MakeMap(.mapType).UnsafePointer()
	}
	if [] == '}' {
		**(**unsafe.Pointer)(unsafe.Pointer(&)) = 
		++
		return , nil
	}
	// The key and the value of every entry are decoded into the same zero values ( see mapTemps ), which go back
	// to the pool when the object ends: after an error, they may have values, and are left to the collector.
	 := .temps.Get().(*mapTemps)
	, , ,  := .k, .v, .kv, .vv
	 := .mapValue()
	for {
		,  := .keyDecoder.Decode(, , , )
		if  != nil {
			if  == errMapKeyType {
				// a key of another type: the rest of the object is decoded by decodeEntries
				return .decodeEntries(, , , , , , , true)
			}
			return 0, 
		}
		if [-1] != '"' {
			// a key is a string, which ends with a quote, but its decoder may decode a value of any kind
			return 0, errKeyNotString(, )
		}
		 = skipWhiteSpace(, )
		if [] != ':' {
			return 0, errors.ErrExpected("colon after object key", )
		}
		++
		,  := .valueDecoder.Decode(, , , )
		if  != nil {
			return 0, 
		}
		.SetMapIndex(, )
		.SetZero()
		.SetZero()
		 = skipWhiteSpace(, )
		if [] == '}' {
			**(**unsafe.Pointer)(unsafe.Pointer(&)) = 
			.temps.Put()
			++
			return , nil
		}
		if [] != ',' {
			return 0, errors.ErrExpected("comma after object value", )
		}
		++
	}
}

func ( *mapDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	 := int64(len())
	if  < 2 {
		return nil, 0, errors.ErrExpected("{} for map", )
	}
	switch [] {
	case 'n':
		if  := validateNull(, );  != nil {
			return nil, 0, 
		}
		 += 4
		return [][]byte{nullbytes}, , nil
	case '{':
		++
		if  > maxDecodeNestingDepth {
			return nil, 0, errors.ErrExceededMaxDepth([], )
		}
	default:
		return nil, 0, errors.ErrExpected("{ character for map value", )
	}
	++
	 = skipWhiteSpace(, )
	if [] == '}' {
		++
		return nil, , nil
	}
	,  := .keyDecoder.(*stringDecoder)
	if ! {
		return nil, 0, &errors.UnmarshalTypeError{
			Value:  "string",
			Type:   reflect.TypeOf(""),
			Offset: ,
			Struct: .structName,
			Field:  .fieldName,
		}
	}
	 := [][]byte{}
	for {
		if [skipWhiteSpace(, )] != '"' {
			return nil, 0, errKeyNotString(, )
		}
		, ,  := .decodeByte(, )
		if  != nil {
			return nil, 0, 
		}
		 = skipWhiteSpace(, )
		if [] != ':' {
			return nil, 0, errors.ErrExpected("colon after object key", )
		}
		++
		 := .Option.Path.node
		, ,  := .Option.Path.Field(string())
		if  != nil {
			return nil, 0, 
		}
		// .. selects its name in the value too, at any depth: the value is searched with it
		,  := .(*PathRecursiveNode)
		 := 
		if  &&  != nil {
			.Option.Path.node = 
			, ,  := .valueDecoder.DecodePath(, , )
			.Option.Path.node = 
			if ,  := .(*errors.PathError);  &&  {
				// the rest of the path after .. does not fit the value, so it selects nothing in it
				 = nil
				,  = skipValue(, , )
			}
			if  != nil {
				return nil, 0, 
			}
			 = append(, ...)
			 = 
		}
		switch {
		case :
			, ,  := .valueDecoder.DecodePath(, , )
			if  != nil {
				return nil, 0, 
			}
			if  &&  == nil {
				// the value is selected too, which the same pass ends
				 = append(, [:])
			}
			 = append(, ...)
			 = 
		case  &&  == nil:
			,  := skipValue(, , )
			if  != nil {
				return nil, 0, 
			}
			 = append(, [:])
			 = 
		case !:
			,  := skipValue(, , )
			if  != nil {
				return nil, 0, 
			}
			 = 
		}
		 = skipWhiteSpace(, )
		if [] == '}' {
			++
			return , , nil
		}
		if [] != ',' {
			return nil, 0, errors.ErrExpected("comma after object value", )
		}
		++
	}
}