Merge pull request #283 from goccy/feature/fix-282

Fix mapassign_faststr for indirect struct type
This commit is contained in:
Masaaki Goshima 2021-08-31 13:03:52 +09:00 committed by GitHub
commit 4f058093a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 75 additions and 18 deletions

View File

@ -3732,3 +3732,47 @@ func TestDecodeBinaryTypeWithEscapedChar(t *testing.T) {
}
})
}
func TestIssue282(t *testing.T) {
var J = []byte(`{
"a": {},
"b": {},
"c": {},
"d": {},
"e": {},
"f": {},
"g": {},
"h": {
"m": "1"
},
"i": {}
}`)
type T4 struct {
F0 string
F1 string
F2 string
F3 string
F4 string
F5 string
F6 int
}
type T3 struct {
F0 string
F1 T4
}
type T2 struct {
F0 string `json:"m"`
F1 T3
}
type T0 map[string]T2
// T2 size is 136 bytes. This is indirect type.
var v T0
if err := json.Unmarshal(J, &v); err != nil {
t.Fatal(err)
}
if v["h"].F0 != "1" {
t.Fatalf("failed to assign map value")
}
}

View File

@ -12,7 +12,7 @@ type mapDecoder struct {
mapType *runtime.Type
keyType *runtime.Type
valueType *runtime.Type
stringKeyType bool
canUseAssignFaststrType bool
keyDecoder Decoder
valueDecoder Decoder
structName string
@ -24,7 +24,7 @@ func newMapDecoder(mapType *runtime.Type, keyType *runtime.Type, keyDec Decoder,
mapType: mapType,
keyDecoder: keyDec,
keyType: keyType,
stringKeyType: keyType.Kind() == reflect.String,
canUseAssignFaststrType: canUseAssignFaststrType(keyType, valueType),
valueType: valueType,
valueDecoder: valueDec,
structName: structName,
@ -32,6 +32,19 @@ func newMapDecoder(mapType *runtime.Type, keyType *runtime.Type, keyDec Decoder,
}
}
const (
mapMaxElemSize = 128
)
// See detail: https://github.com/goccy/go-json/pull/283
func canUseAssignFaststrType(key *runtime.Type, value *runtime.Type) bool {
indirectElem := value.Size() > mapMaxElemSize
if indirectElem {
return false
}
return key.Kind() == reflect.String
}
//go:linkname makemap reflect.makemap
func makemap(*runtime.Type, int) unsafe.Pointer
@ -45,8 +58,8 @@ func mapassign_faststr(t *runtime.Type, m unsafe.Pointer, s string) unsafe.Point
func mapassign(t *runtime.Type, m unsafe.Pointer, k, v unsafe.Pointer)
func (d *mapDecoder) mapassign(t *runtime.Type, m, k, v unsafe.Pointer) {
if d.stringKeyType {
mapV := mapassign_faststr(d.mapType, m, *(*string)(k))
if d.canUseAssignFaststrType {
mapV := mapassign_faststr(t, m, *(*string)(k))
typedmemmove(d.valueType, mapV, v)
} else {
mapassign(t, m, k, v)