Skip to content

Commit

Permalink
fix: issue where Decoder panics when decoding an Object containing a …
Browse files Browse the repository at this point in the history
…Map with int8/int16 as key or value type
  • Loading branch information
ahaostudy committed Oct 31, 2023
1 parent f0fbe40 commit 4ce3eae
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
11 changes: 10 additions & 1 deletion map.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,16 @@ func (d *Decoder) decMapByValue(value reflect.Value) error {
return perrors.WithStack(err)
}

m.Elem().SetMapIndex(EnsurePackValue(entryKey), EnsureRawValue(entryValue))
// add a layer of conversion to make the map compatible with more types during decoding
key := EnsurePackValue(entryKey)
if mKey := m.Elem().Type().Key(); key.Type().ConvertibleTo(mKey) {
key = key.Convert(mKey)
}
val := EnsureRawValue(entryValue)
if mVal := m.Elem().Type().Elem(); val.Type().ConvertibleTo(mVal) {
val = val.Convert(mVal)
}
m.Elem().SetMapIndex(key, val)
}

SetValue(value, m)
Expand Down
39 changes: 39 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,42 @@ func TestJavaMap(t *testing.T) {
RegisterPOJO(customMap)
testJavaDecode(t, "customArgTypedFixed_CustomMap", customMap)
}

type Obj struct {
Map8 map[int8]int8
Map16 map[int16]int16
Map32 map[int32]int32
}

func (Obj) JavaClassName() string {
return ""
}

func TestMapInObject(t *testing.T) {
var (
obj Obj
e *Encoder
d *Decoder
err error
res interface{}
)

obj = Obj{
Map8: map[int8]int8{1: 2, 3: 4},
Map16: map[int16]int16{1: 2, 3: 4},
Map32: map[int32]int32{1: 2, 3: 4},
}

e = NewEncoder()
e.Encode(obj)
if len(e.Buffer()) == 0 {
t.Fail()
}

d = NewDecoder(e.Buffer())
res, err = d.Decode()
if err != nil {
t.Errorf("Decode() = %+v", err)
}
t.Logf("decode(%v) = %v, %v\n", obj, res, err)
}

0 comments on commit 4ce3eae

Please sign in to comment.