Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix Decoder failed to decode int8/int16 type values of map field in struct #366

Merged
merged 2 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
44 changes: 44 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
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)
}
}