Skip to content

Commit 9e0e881

Browse files
authored
Merge pull request #39 from Basekick-Labs/v5
V5
2 parents b7f5de6 + 523194a commit 9e0e881

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

decode_number.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,12 +171,22 @@ func (d *Decoder) DecodeFloat32() (float32, error) {
171171
}
172172

173173
func (d *Decoder) float32(c byte) (float32, error) {
174-
if c == msgpcode.Float {
174+
switch c {
175+
case msgpcode.Float:
175176
n, err := d.uint32()
176177
if err != nil {
177178
return 0, err
178179
}
179180
return math.Float32frombits(n), nil
181+
case msgpcode.Double:
182+
n, err := d.float64(c)
183+
if err != nil {
184+
return 0, err
185+
}
186+
if n > math.MaxFloat32 || n < -math.MaxFloat32 {
187+
return 0, fmt.Errorf("msgpack: float64 %v overflows float32", n)
188+
}
189+
return float32(n), nil
180190
}
181191

182192
n, err := d.int(c)

types_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,21 @@ func TestInt64(t *testing.T) {
10131013
}
10141014
}
10151015

1016+
func TestDecodeFloat32FromFloat64(t *testing.T) {
1017+
// Issue #12: float32 decode should accept Double code with narrowing.
1018+
b, err := msgpack.Marshal(float64(3.14))
1019+
require.NoError(t, err)
1020+
1021+
var f float32
1022+
require.NoError(t, msgpack.Unmarshal(b, &f))
1023+
require.InDelta(t, float32(3.14), f, 0.001)
1024+
1025+
// Overflow should error.
1026+
b, err = msgpack.Marshal(math.MaxFloat64)
1027+
require.NoError(t, err)
1028+
require.Error(t, msgpack.Unmarshal(b, &f))
1029+
}
1030+
10161031
func TestFloat32(t *testing.T) {
10171032
tests := []struct {
10181033
in float32

0 commit comments

Comments
 (0)