package encoder

import (
	
	
	
	
	
	
	
	
	

	
	
)

// The keys of a map for the semantics of encoding/json/v2: a key is encoded as a value is, in the place of a name,
// where a number is a string, and a key which is not a string is an error. A key of a string, an integer or a
// float, which the VM writes, is a different name for every key of the map. The other keys are named here, and
// two keys of a map may have the same name: the names of a map are recorded to report it.

// v2MapKeyCode returns the code of the key of a map of the type typ.
func ( *Compiler) ( reflect.Type) (Code, error) {
	 := .funcs.funcsOf()
	// a time.Duration and a json.Number are named by appendKeyNameAfter, wherever they are.
	if len() == 0 && v2MethodOf(, noMethod) == noMethod &&  != timeDurationType &&  != jsonNumberType {
		switch .Kind() {
		case reflect.String:
			return .stringCode(, false)
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			return .mapKeyCode()
		case reflect.Float32:
			return &FloatCode{typ: , bitSize: 32, isString: true}, nil
		case reflect.Float64:
			return &FloatCode{typ: , bitSize: 64, isString: true}, nil
		}
	}
	if .Kind() == reflect.Interface && .NumMethod() > 0 {
		return .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
			return appendMapKeyName(, , , methodInterfaceOf(, ), )
		}), nil
	}
	return .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
		return appendMapKeyName(, , , , )
	}), nil
}

// methodInterfaceOf returns the address of the key at p of a map whose keys are of typ, an interface type with
// methods, as a value of typ: p has the words of the interface{} which the key is read into ( see
// newInterfaceKeyCollector ), not the ones of typ, whose first word is an itab.
func methodInterfaceOf( reflect.Type,  unsafe.Pointer) unsafe.Pointer {
	 := reflect.New()
	if  := *(*any)();  != nil {
		.Elem().Set(reflect.ValueOf())
	}
	return .UnsafePointer()
}

// appendMapKeyName appends the name of the key at p, of typ, by the functions of marshaling, its method or its
// kind, and records it in the context of the map, failing if the map has the name already. The names of a map
// whose entries are sorted are checked as the entries are written in the order of the names ( see SameMapName ).
func appendMapKeyName( *RuntimeContext,  []byte,  reflect.Type,  unsafe.Pointer,  []*MarshalFunc) ([]byte, error) {
	 := len()
	,  := , ErrUseDefault
	.KeyName = true // for a method or a function which writes to an encoder, at the place of a name
	if len() > 0 {
		,  = appendByFuncs(, , , , )
	}
	 :=  != ErrUseDefault
	if  == ErrUseDefault {
		// a key, which is not addressable
		,  = appendKeyName(, , reflect.NewAt(, ).Elem(), false)
	}
	.KeyName = false
	if  == nil && [] != '"' {
		 = &errors.TextError{Err: errors.ErrNonStringName, GoType: }
	}
	if  != nil {
		if .Option.Flag&UnorderedMapOption == 0 {
			// a name of a sorted map, which is encoded after the names before it, which are not entries yet ( see
			// MapContext.SortEncodedKeys ): the error is at the place of the first name, where encoding/json/v2
			// writes each name.
			 = &errors.OutputError{Out: [:.SortedKeysStart()], Err: }
		}
		return , 
	}
	if .Option.Flag&(RawRewriteOption|AllowDuplicateNamesOption) == RawRewriteOption && bytes.IndexByte([:], '\\') >= 0 {
		// a name of a raw value which the options of raw values may keep with its escapes, as PreserveRawStrings does,
		// which another name may be the same as by another escape: the output is checked by its names ( see
		// RescanNames ).
		.RescanNames = true
	}
	if .Option.Flag&(AllowDuplicateNamesOption|UnorderedMapOption) != UnorderedMapOption {
		return , nil
	}
	 := .mapContexts[.mapDepth-1]
	if !.namesKept {
		if .names == nil {
			.names = map[string]struct{}{}
		}
		clear(.names)
		.namesKept = true
	}
	 := string([:])
	if ,  := .names[];  {
		 := jsonstring.AppendUnescaped(nil, []byte([1:len()-1]))
		 := &errors.TextError{Err: errors.ErrDuplicateName, Name: string()}
		if  || keyMethodOf(, , noMethod, false) != noMethod {
			// the name was written by a function or a method, which the error is reported for.
			.GoType = 
		}
		return , 
	}
	.names[] = struct{}{}
	return , nil
}

// appendKeyName appends the name of the value v, which reflect can take the address of, as a JSON string: it is
// addressable if it is the value which a pointer key points to ( see keyMethodOf ).
func appendKeyName( *RuntimeContext,  []byte,  reflect.Value,  bool) ([]byte, error) {
	return appendKeyNameAfter(, , , noMethod, )
}

// keyMethodOf returns the method of marshaling which names a key of the type t, addressable or not, after the method
// after, as v2MethodOf does. With CallMethodsWithLegacySemantics, a key is named as encoding/json names it: a string
// by itself, and a key of another kind by AppendText or MarshalText only, the methods after methodMarshalJSON, of a
// value receiver unless the key is addressable.
func keyMethodOf( *RuntimeContext,  reflect.Type,  int,  bool) int {
	if .Option.Flag&CallMethodsWithLegacySemanticsOption == 0 {
		return v2MethodOf(, )
	}
	if .Kind() == reflect.String {
		return noMethod
	}
	return methodOfAt(, max(, methodMarshalJSON), )
}

// appendKeyNameAfter appends the name of the value v, addressable or not ( see appendKeyName ), by its method after
// the method after or by its kind.
func appendKeyNameAfter( *RuntimeContext,  []byte,  reflect.Value,  int,  bool) ([]byte, error) {
	 := .Type()
	if  == timeTimeType {
		// written as a value of time.Time is, as encoding/json/v2 writes a time, not by its methods
		return appendTime(, , .Addr().UnsafePointer())
	}
	switch  := keyMethodOf(, , , );  {
	case methodMarshalJSONTo:
		// the encoder, at the place of a name, takes a string only.
		,  := V2Hooks.MarshalTo(, , , .Addr().Interface())
		if  == ErrUseDefault {
			return (, , , methodMarshalJSONTo, )
		}
		return , 
	case methodMarshalJSON:
		,  := .Addr().Interface().(json.Marshaler).MarshalJSON()
		if  != nil {
			return , &errors.MethodError{GoType: , Err: unsupportedError(, errors.MethodMarshalJSON), Kind: errors.MethodMarshalJSON}
		}
		,  := AppendRaw(, , )
		if  != nil {
			return , &errors.MethodError{GoType: , Err: , Kind: errors.MethodMarshalJSON}
		}
		if [len()] != '"' {
			return , &errors.TextError{Err: errors.ErrNonStringName, GoType: }
		}
		return , nil
	case methodAppendText, methodMarshalText:
		return appendTextOf(, , , , .Addr().Interface())
	}
	switch {
	case  == timeDurationType && .Option.Flag&FormatDurationAsNanoOption == 0:
		// the nanoseconds of the int64 with FormatDurationAsNano, which its kind writes
		return , &errors.SemanticError{GoType: , Err: errNoDuration}
	case  == jsonNumberType:
		,  := AppendNumberString(, append(, '"'), json.Number(.String()))
		if  != nil {
			return , 
		}
		return append(, '"'), nil
	}
	switch .Kind() {
	case reflect.String:
		return appendName(, , .String())
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		 = append(, '"')
		return append(appendIntValue(, .Int()), '"'), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		 = append(, '"')
		return append(appendUintValue(, .Uint()), '"'), nil
	case reflect.Float32, reflect.Float64:
		 := .Float()
		if math.IsNaN() || math.IsInf(, 0) {
			if .Option.Flag&ReportErrorsWithLegacySemanticsOption != 0 {
				// the error of encoding/json, with the float
				return , &errors.UnsupportedValueError{Value: , Str: strconv.FormatFloat(, 'g', -1, 64)}
			}
			return , &errors.SemanticError{GoType: , Err: errUnsupportedValue()}
		}
		 := 64
		if .Kind() == reflect.Float32 {
			 = 32
		}
		 = append(, '"')
		return append(appendFloatOfBits(, , ), '"'), nil
	case reflect.Pointer, reflect.Interface:
		if .Option.Flag&CallMethodsWithLegacySemanticsOption != 0 {
			switch {
			case .Kind() == reflect.Pointer && .IsNil() && (.Implements(marshalTextType) || .Implements(appendTextType)):
				// a nil pointer of MarshalText or AppendText, which encoding/json names "" with
				// CallMethodsWithLegacySemantics
				return append(, `""`...), nil
			case .Kind() == reflect.Interface && !.IsNil() && .Elem().Kind() == reflect.Pointer && .Elem().IsNil():
				// a nil pointer held by an interface value of MarshalText or AppendText, which encoding/json names by
				// the method of the interface type, called for the nil pointer, as it writes such a value
				if , ,  := appendNilTextKey(, , );  {
					return , 
				}
			}
		}
		// the pointers and the interfaces are followed here, one by one, up to a value which is named otherwise: by
		// its functions, its method or its kind.
		var  keyCycle
		for {
			if .IsNil() {
				return , &errors.TextError{Err: errors.ErrNonStringName, GoType: .Type()}
			}
			 := .Elem()
			if .Kind() == reflect.Interface {
				// the dynamic value, in a variable of its own, which is addressable.
				 := reflect.New(.Type()).Elem()
				.Set()
				 = 
			}
			// named by the functions of its own type first, as a key of that type is.
			if  := .Option.Funcs.funcsOf(.Type()); len() > 0 {
				if ,  := appendByFuncs(, , .Addr().UnsafePointer(), .Type(), );  != ErrUseDefault {
					return , 
				}
			}
			if  := .Kind();  != reflect.Pointer &&  != reflect.Interface || v2MethodOf(.Type(), noMethod) != noMethod {
				// the value which a pointer points to is addressable, not the copy of the one an interface holds
				return appendKeyName(, , , .Kind() == reflect.Pointer)
			}
			if .reached() {
				return , &errors.SemanticError{GoType: , Err: errors.ErrCycle}
			}
			 = 
		}
	case reflect.Array:
		if .Elem().Kind() == reflect.Uint8 &&
			!v2BytesAsArray(, .Option.Flag&FormatByteArrayAsArrayOption != 0, .Option.Flag&FormatBytesWithLegacySemanticsOption != 0) {
			 := unsafe.Slice((*byte)(.Addr().UnsafePointer()), .Len())
			 = append(, '"')
			return append(base64.StdEncoding.AppendEncode(, ), '"'), nil
		}
	case reflect.Complex64, reflect.Complex128, reflect.Chan, reflect.Func, reflect.UnsafePointer:
		return , &errors.SemanticError{GoType: }
	}
	return , &errors.TextError{Err: errors.ErrNonStringName, GoType: }
}

// appendNilTextKey appends the name of the interface value v, which holds a nil pointer, by the method of the
// interface type of v, called for the nil pointer, and reports true, if it is MarshalText or AppendText ( see
// v2MethodOfInterface ) of the pointer: a method of the value it points to can't be called for it.
func appendNilTextKey( *RuntimeContext,  []byte,  reflect.Value) ([]byte, bool, error) {
	,  := .Elem().Type(), .Interface()
	 := v2MethodOfInterface(.Type())
	if  != methodAppendText &&  != methodMarshalText || .Elem().Implements(marshalerTypeOf()) {
		return , false, nil
	}
	,  := appendTextOf(, , , , )
	return , true, 
}

// appendTextOf appends the text of recv by its method m, AppendText or MarshalText, as a JSON string, with the
// errors of a value of typ.
func appendTextOf( *RuntimeContext,  []byte,  reflect.Type,  int,  any) ([]byte, error) {
	if  == methodAppendText {
		return appendMethodText(, , , errors.MethodAppendText, nil, func( unsafe.Pointer,  []byte) ([]byte, error) {
			return .(textAppender).AppendText()
		})
	}
	return appendMethodText(, , , errors.MethodMarshalText, nil, func( unsafe.Pointer,  []byte) ([]byte, error) {
		,  := .(encoding.TextMarshaler).MarshalText()
		return append(, ...), 
	})
}

// appendName appends the name as a JSON string, which must be valid UTF-8 unless it is allowed.
func appendName( *RuntimeContext,  []byte,  string) ([]byte, error) {
	if ,  := jsonstring.AppendQuoted(textEscaper(), , );  {
		return , nil
	} else if ,  := InvalidUTF8(, , );  != nil {
		return , 
	} else {
		return , nil
	}
}

func appendIntValue( []byte,  int64) []byte { return strconv.AppendInt(, , 10) }

func appendUintValue( []byte,  uint64) []byte { return strconv.AppendUint(, , 10) }

func errUnsupportedValue( float64) error { return fmt.Errorf("unsupported value: %v", ) }