Skip to content

Commit

Permalink
If float value comes, decodes to int as truncating the value.
Browse files Browse the repository at this point in the history
  • Loading branch information
shamaton committed Jun 21, 2021
1 parent 1be520e commit 85f28ad
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
14 changes: 14 additions & 0 deletions internal/decoding/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ func (d *decoder) asInt(offset int, k reflect.Kind) (int64, int, error) {
bs, offset := d.readSize8(offset)
return int64(binary.BigEndian.Uint64(bs)), offset, nil

case code == def.Float32:
v, offset, err := d.asFloat32(offset, k)
if err != nil {
return 0, 0, err
}
return int64(v), offset, nil

case code == def.Float64:
v, offset, err := d.asFloat64(offset, k)
if err != nil {
return 0, 0, err
}
return int64(v), offset, nil

case code == def.Nil:
offset++
return 0, offset, nil
Expand Down
34 changes: 34 additions & 0 deletions msgpack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,40 @@ func TestFloat(t *testing.T) {
t.Error(err)
}
}
{
var r int
v := float32(2.345)
b, err := msgpack.MarshalAsArray(v)
if err != nil {
t.Error(err)
}

err = msgpack.UnmarshalAsArray(b, &r)
if err != nil {
t.Error(err)
}

if r != 2 {
t.Error("different value", r)
}
}
{
var r int
v := 6.789
b, err := msgpack.MarshalAsArray(v)
if err != nil {
t.Error(err)
}

err = msgpack.UnmarshalAsArray(b, &r)
if err != nil {
t.Error(err)
}

if r != 6 {
t.Error("different value", r)
}
}
// error
{
var v float32
Expand Down

0 comments on commit 85f28ad

Please sign in to comment.