| 1 |
//go:build !go1.27 || !goexperiment.jsonv2 |
| 2 |
|
| 3 |
package encoder |
| 4 |
|
| 5 |
import ( |
| 6 |
"encoding" |
| 7 |
"reflect" |
| 8 |
"unsafe" |
| 9 |
|
| 10 |
"github.com/goccy/go-json/internal/errors" |
| 11 |
"github.com/goccy/go-json/internal/runtime" |
| 12 |
) |
| 13 |
|
| 14 |
// interfaceMapKeys is whether every map of an interface type as its key is encoded: encoding/json which is not |
| 15 |
// built on encoding/json/v2 refuses the type of such a map, but the one of an interface type which has |
| 16 |
// MarshalText, whose keys are the texts of their values ( see map_key_interface.go ). |
| 17 |
const interfaceMapKeys = false |
| 18 |
|
| 19 |
var emptyInterfaceType = reflect.TypeOf((*any)(nil)).Elem() |
| 20 |
|
| 21 |
// appendInterfaceMapKey appends the name of the key of a map of an interface type which has MarshalText, as a |
| 22 |
// string: the text of its dynamic value, as encoding/json makes it. p is the address of the key as the map is |
| 23 |
// read into the context: an interface{}, whatever the interface type of the key is ( see newReflectCollector ). |
| 24 |
func appendInterfaceMapKey(ctx *RuntimeContext, code *Opcode, b []byte, p unsafe.Pointer) ([]byte, error) { |
| 25 |
v := reflect.NewAt(emptyInterfaceType, p).Elem() |
| 26 |
for v.Kind() == reflect.Interface && !v.IsNil() { |
| 27 |
v = v.Elem() |
| 28 |
} |
| 29 |
m, ok := v.Interface().(encoding.TextMarshaler) |
| 30 |
if !ok { |
| 31 |
// a nil key, which has no text. |
| 32 |
return nil, &errors.UnsupportedValueError{Value: v, Str: "nil key of " + runtime.TypeOfPtr(code.Type).String()} |
| 33 |
} |
| 34 |
text, err := m.MarshalText() |
| 35 |
if err != nil { |
| 36 |
return nil, errors.ErrMarshaler(v.Type(), err, "MarshalText") |
| 37 |
} |
| 38 |
return appendText(ctx, b, *(*string)(unsafe.Pointer(&text))), nil |
| 39 |
} |