Merge pull request #150 from goccy/feature/fix-nested-map

Fix encoding of nested map
This commit is contained in:
Masaaki Goshima 2021-03-15 13:51:11 +09:00 committed by GitHub
commit 7c0a056064
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 34 additions and 2 deletions

View File

@ -50,6 +50,10 @@ func TestCoverMap(t *testing.T) {
name string name string
data interface{} data interface{}
}{ }{
{
name: "NestedMap",
data: map[string]map[string]int{"a": {"b": 1}},
},
// HeadMapZero // HeadMapZero
{ {
name: "HeadMapZero", name: "HeadMapZero",

View File

@ -726,8 +726,7 @@ func encodeCompileMap(ctx *encodeCompileContext) (*opcode, error) {
value := newMapValueCode(ctx, header) value := newMapValueCode(ctx, header)
ctx.incIndex() ctx.incIndex()
valueType := typ.Elem() valueCode, err := encodeCompileMapValue(ctx.withType(typ.Elem()))
valueCode, err := encodeCompile(ctx.withType(valueType), false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -756,6 +755,15 @@ func encodeCompileMap(ctx *encodeCompileContext) (*opcode, error) {
return (*opcode)(unsafe.Pointer(header)), nil return (*opcode)(unsafe.Pointer(header)), nil
} }
func encodeCompileMapValue(ctx *encodeCompileContext) (*opcode, error) {
switch ctx.typ.Kind() {
case reflect.Map:
return encodeCompilePtr(ctx.withType(rtype_ptrTo(ctx.typ)))
default:
return encodeCompile(ctx, false)
}
}
func encodeTypeToHeaderType(code *opcode) opType { func encodeTypeToHeaderType(code *opcode) opType {
switch code.op { switch code.op {
case opInt: case opInt:

View File

@ -278,6 +278,16 @@ func encodeRunEscapedIndent(ctx *encodeRuntimeContext, b []byte, codeSet *opcode
b = append(b, ']', ',', '\n') b = append(b, ']', ',', '\n')
code = code.end.next code = code.end.next
} }
case opMapPtr:
p := load(ctxptr, code.idx)
if p == 0 {
b = encodeNull(b)
b = encodeComma(b)
code = code.end.next
break
}
store(ctxptr, code.idx, ptrToPtr(p))
fallthrough
case opMap: case opMap:
ptr := load(ctxptr, code.idx) ptr := load(ctxptr, code.idx)
if ptr == 0 { if ptr == 0 {

View File

@ -278,6 +278,16 @@ func encodeRunIndent(ctx *encodeRuntimeContext, b []byte, codeSet *opcodeSet, op
b = append(b, ']', ',', '\n') b = append(b, ']', ',', '\n')
code = code.end.next code = code.end.next
} }
case opMapPtr:
p := load(ctxptr, code.idx)
if p == 0 {
b = encodeNull(b)
b = encodeComma(b)
code = code.end.next
break
}
store(ctxptr, code.idx, ptrToPtr(p))
fallthrough
case opMap: case opMap:
ptr := load(ctxptr, code.idx) ptr := load(ctxptr, code.idx)
if ptr == 0 { if ptr == 0 {