Skip to content

Commit

Permalink
Merge pull request #366 from ahaostudy/master
Browse files Browse the repository at this point in the history
fix Decoder failed to decode int8/int16 type values of map field in struct
  • Loading branch information
jasondeng1997 committed Nov 1, 2023
2 parents f0fbe40 + fbdccbe commit fb070d0
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
11 changes: 10 additions & 1 deletion map.go
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
44 changes: 44 additions & 0 deletions map_test.go
Expand Up @@ -18,6 +18,7 @@
package hessian

import (
"reflect"
"testing"
)

Expand Down Expand Up @@ -182,3 +183,46 @@ 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 (
req *Obj
e *Encoder
d *Decoder
err error
res interface{}
)

req = &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(req)
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", req, res, err)

if !reflect.DeepEqual(req, res) {
t.Fatalf("req: %#v != res: %#v", req, res)
}
}

0 comments on commit fb070d0

Please sign in to comment.