//go:build go1.27 && goexperiment.jsonv2

package encoder

import (
	
	
	jsonv1 
	jsonv2 
	
	
	
	

	
	
	
)

// The keys of a map of an interface type, which encoding/json encodes when it is built on encoding/json/v2
// ( GOEXPERIMENT=jsonv2, the default since Go 1.27; this file uses the API of Go 1.27 ): the name of a key is
// made from its dynamic value as a value in the place of a name is, and a key whose value is not written as a
// string is an error.
//
//   - a string, an integer, a float32 and a float64 are their text; a float64 held by a key of interface{}
//     is not, as interface{} writes it as a number.
//   - a value with AppendText or MarshalText of its value, or of its pointer through a pointer, is its text;
//     MarshalJSON is not called for a name.
//   - a pointer is the name of its value.
//   - a slice of bytes is its base64.
//   - nil, a bool, a nil pointer, a struct, an array, another slice or a map is not a name; a complex number, a
//     channel or a function is an unsupported type.
//
// The keys are sorted by their names, as the keys of the maps whose keys are not strings are: OpMapKey sorts them
// after the last one is encoded ( see MapContext.SortEncodedKeys ).

// interfaceMapKeys is whether a map of an interface type as its key is encoded.
const interfaceMapKeys = true

var (
	emptyInterfaceType  = reflect.TypeOf((*any)(nil)).Elem()
	float64Type         = reflect.TypeOf(float64(0))
	textAppenderType    = reflect.TypeOf((*encoding.TextAppender)(nil)).Elem()
	jsonMarshalerType   = reflect.TypeOf((*jsonv1.Marshaler)(nil)).Elem()
	jsonMarshalerToType = reflect.TypeOf((*jsonv2.MarshalerTo)(nil)).Elem()
)

// appendInterfaceMapKey appends the name of the key of a map of an interface type, or of a type of pointers which
// points to itself ( see pointerMapKeyCode ), as a string. p is the address of the key as the map is read into the
// context: an interface{} for a key of an interface type, whatever the interface type is ( see
// newReflectCollector ), and the pointer for a key of pointers. It is the address of the interface itself for an
// interface which the pointers of a key lead to, which OpMarshalTextPtr follows.
func appendInterfaceMapKey( *RuntimeContext,  *Opcode,  []byte,  unsafe.Pointer) ([]byte, error) {
	var  any
	var  reflect.Type
	switch {
	case .Type == runtime.TypePtr(emptyInterfaceType):
		// an interface{}, which is the same in place and in the context.
		,  = *(*any)(), emptyInterfaceType
	case .Op == OpMarshalTextPtr:
		 = runtime.TypeOfPtr(.Type)
		 = interfaceAt(, )
	default:
		if  = runtime.TypeOfPtr(.Type); .Kind() == reflect.Pointer {
			,  = pointerOf(.Type, *(*unsafe.Pointer)()), nil
		} else {
			 = *(*any)()
		}
	}
	// a string or a value of a method, as most keys of interfaces are, is named without mapKeyName: ownKeyName,
	// written here, as it is not inlined.
	,  := .(string)
	var  error
	if ! && (*emptyInterface)(unsafe.Pointer(&)).ptr != nil {
		, ,  = methodKeyName()
	}
	if ! {
		,  = mapKeyName(, )
	}
	if  != nil {
		return nil, 
	}
	// appendText, written here as AppendMarshalText writes it: it is not inlined.
	, _ = jsonstring.AppendQuoted(StringEscaper(), , )
	return , nil
}

// NilMapKeyError is the error of a key whose pointers, which the opcode code of what they lead to follows, end at
// nil ( see pointerMapKeyCode ), as encoding/json reports it: the nil pointer is reported as the last of them.
func ( *Opcode) error {
	 := runtime.TypeOfPtr(.Type)
	if .Kind() != reflect.Pointer {
		 = reflect.PointerTo()
	}
	return notStringMapKey(reflect.Zero())
}

// pointerOf returns the pointer ptr of the type typ, held by an interface{} as it is.
func pointerOf(,  unsafe.Pointer) any {
	return *(*any)(unsafe.Pointer(&emptyInterface{typ: , ptr: }))
}

// interfaceAt returns the value of the interface of the type typ at the address p, held by an interface{}.
func interfaceAt( reflect.Type,  unsafe.Pointer) any {
	if .NumMethod() == 0 {
		return *(*any)()
	}
	// an interface with methods, whose words are the ones of any of them: the conversion takes the type of its
	// itab, as reflect converts it.
	return *(*interface{ () })()
}

// ownKeyName returns the name which the value of an interface x has by itself, and whether it has one: a string, or
// the text of its method, which a value or a pointer to one has. A nil pointer is named by the interface type ( see
// mapKeyName ).
func ownKeyName( any) (string, bool, error) {
	if ,  := .(string);  || (*emptyInterface)(unsafe.Pointer(&)).ptr == nil {
		return , , nil
	}
	return methodKeyName()
}

// mapKeyName returns the name of the key x, as an interface{} holds it: its pointers and its interfaces are followed,
// one by one, to the value which names it. iface is the interface type which x is the value of, whose own name it
// doesn't have ( see ownKeyName ), or nil when x is a pointer of the key.
func mapKeyName( any,  reflect.Type) (string, error) {
	var  keyCycle
	for {
		if  != nil {
			if  == nil {
				return "", notStringMapKey(reflect.Zero())
			}
			 := (*emptyInterface)(unsafe.Pointer(&)).ptr
			 := reflect.TypeOf()
			switch  := .Kind(); {
			case  == reflect.Interface:
				// a key of an interface type with methods, which the interface{} holds as the value of its type.
				 = interfaceAt(, )
				if , ,  := ownKeyName();  {
					return , 
				}
				continue
			case  == reflect.Pointer &&  == nil:
				// The method of the marshaler which the interface type is, if any, is called with the nil pointer. A
				// MarshalJSON is not called for a name.
				switch {
				case .Implements(jsonMarshalerToType), .Implements(jsonMarshalerType):
					return "", notStringMapKey(reflect.ValueOf())
				case .Implements(textAppenderType):
					return appendTextName(.(encoding.TextAppender))
				case .Implements(marshalTextType):
					return marshalTextName(.(encoding.TextMarshaler))
				}
				return "", notStringMapKey(reflect.ValueOf())
			case  == reflect.Float64 &&  == emptyInterfaceType &&  == float64Type:
				// interface{} writes a float64 as a number, which is not a name.
				 := reflect.ValueOf()
				if  := .Float(); math.IsNaN() || math.IsInf(, 0) {
					return "", nonFiniteMapKey(, )
				}
				return "", notStringMapKey()
			case  != reflect.Pointer &&  != nil:
				// a value which is not addressable, whose own name it doesn't have.
				return kindKeyName(reflect.ValueOf())
			case  != reflect.Pointer:
				// a nil value of a type which is not a pointer, as a nil map, which its methods name.
				return valueKeyName(, false)
			}
			 = nil
		}
		// a pointer, which is followed to the pointer, the interface or the value it points to.
		,  := reflect.TypeOf(), (*emptyInterface)(unsafe.Pointer(&)).ptr
		if  == nil {
			return "", notStringMapKey(reflect.ValueOf())
		}
		if .reachedPointer(, ) {
			return "", &errors.UnsupportedValueError{Value: reflect.ValueOf(), Str: "encountered a cycle via " + .String()}
		}
		switch  := .Elem(); .Kind() {
		case reflect.Pointer:
			 = pointerOf(runtime.TypePtr(), *(*unsafe.Pointer)())
		case reflect.Interface:
			,  = interfaceAt(, ), 
			if , ,  := ownKeyName();  {
				return , 
			}
		default:
			return valueKeyName(, true)
		}
	}
}

// valueKeyName returns the name of the value which x holds, or which x points to when byPointer: by the methods of
// x, or by the kind of the value.
func valueKeyName( any,  bool) (string, error) {
	if , ,  := methodKeyName();  {
		return , 
	}
	 := reflect.ValueOf()
	if  {
		if .Type().Name() != "" {
			// a pointer of a type of its own, as type P *T, which has no methods: the methods of the value are the
			// ones of the pointer to it.
			return (.Elem().Addr().Interface(), true)
		}
		 = .Elem()
	}
	return kindKeyName()
}

// methodKeyName returns the name of the value which x holds, or which x points to, by AppendText or MarshalText of
// x, and whether x has one of them. A value of a string kind, or which x points to, is its string, without its
// methods, as encoding/json names it from Go 1.27.2.
func methodKeyName( any) (string, bool, error) {
	switch  := reflect.ValueOf(); {
	case .Kind() == reflect.String:
		return .String(), true, nil
	case .Kind() == reflect.Pointer && !.IsNil() && .Elem().Kind() == reflect.String:
		return .Elem().String(), true, nil
	}
	var  []byte
	var  error
	switch m := .(type) {
	case encoding.TextAppender:
		if ,  = .AppendText(nil);  != nil {
			return "", true, methodError(, textAppenderType, , "AppendText")
		}
	case encoding.TextMarshaler:
		if ,  = .MarshalText();  != nil {
			return "", true, methodError(, marshalTextType, , "MarshalText")
		}
	default:
		return "", false, nil
	}
	// the text is the method's own, which is written before anything else runs: it is not copied.
	return unsafe.String(unsafe.SliceData(), len()), true, nil
}

// kindKeyName returns the name of the value v, whose methods don't name it, by its kind.
func kindKeyName( reflect.Value) (string, error) {
	switch  := .Kind();  {
	case reflect.Slice:
		// a slice of bytes is written as its base64, as a value is, which is a name; the one of bytes which have a
		// method of marshaling is an array, and a nil one is null.
		 := .Type()
		if  := reflect.PointerTo(.Elem()); .Elem().Kind() == reflect.Uint8 && !.IsNil() &&
			!.Implements(jsonMarshalerType) && !.Implements(jsonMarshalerToType) &&
			!.Implements(marshalTextType) && !.Implements(textAppenderType) {
			return base64.StdEncoding.EncodeToString(.Bytes()), nil
		}
	case reflect.String:
		return .String(), nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return strconv.FormatInt(.Int(), 10), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return strconv.FormatUint(.Uint(), 10), nil
	case reflect.Float32, reflect.Float64:
		 := .Float()
		if math.IsNaN() || math.IsInf(, 0) {
			return "", nonFiniteMapKey(, )
		}
		 := 64
		if  == reflect.Float32 {
			 = 32
		}
		return string(appendFloatOfBits(nil, , )), nil
	case reflect.Complex64, reflect.Complex128, reflect.Chan, reflect.Func, reflect.UnsafePointer:
		return "", &errors.UnsupportedTypeError{Type: .Type()}
	}
	return "", notStringMapKey()
}

// appendTextName returns the text which m appends, as a name. The text is the method's own, which is written before
// anything else runs: it is not copied.
func appendTextName( encoding.TextAppender) (string, error) {
	,  := .AppendText(nil)
	if  != nil {
		return "", methodError(, textAppenderType, , "AppendText")
	}
	return unsafe.String(unsafe.SliceData(), len()), nil
}

// marshalTextName returns the text which m returns, as a name, which is not copied ( see appendTextName ).
func marshalTextName( encoding.TextMarshaler) (string, error) {
	,  := .MarshalText()
	if  != nil {
		return "", methodError(, marshalTextType, , "MarshalText")
	}
	return unsafe.String(unsafe.SliceData(), len()), nil
}

// methodError is the error err of the method of iface m, named method, which is reported of the type whose method it
// is: the one of the value which m points to, if the value has it, or the one of m.
func methodError( any,  reflect.Type,  error,  string) error {
	 := reflect.TypeOf()
	if .Kind() == reflect.Pointer && .Elem().Implements() {
		 = .Elem()
	}
	return errors.ErrMarshaler(, , )
}

// notStringMapKey is the error of a key whose value is not written as a string, as encoding/json reports it.
func notStringMapKey( reflect.Value) error {
	return &errors.UnsupportedValueError{Value: , Str: "object member name must be a string"}
}

// nonFiniteMapKey is the error of a key of a float which is not finite, as encoding/json reports it.
func nonFiniteMapKey( reflect.Value,  float64) error {
	return &errors.UnsupportedValueError{Value: , Str: strconv.FormatFloat(, 'g', -1, 64)}
}