From 6ec38ec05689d858ed55608268806fe353e2f348 Mon Sep 17 00:00:00 2001 From: Kimjin-gd Date: Sat, 23 Dec 2023 22:47:11 +0800 Subject: [PATCH] fix: negative float32 overflow when unmarshalling (#3811) Co-authored-by: kim1.jin --- core/mapping/unmarshaler.go | 3 +-- core/mapping/unmarshaler_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index 15215693..7df118e9 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "math" "reflect" "strconv" "strings" @@ -622,7 +621,7 @@ func (u *Unmarshaler) processFieldPrimitiveWithJSONNumber(fieldType reflect.Type return err } - if fValue > math.MaxFloat32 { + if value.OverflowFloat(fValue) { return fmt.Errorf("parsing %q as float32: value out of range", v.String()) } diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go index fd02fd6d..e0bd07d3 100644 --- a/core/mapping/unmarshaler_test.go +++ b/core/mapping/unmarshaler_test.go @@ -976,6 +976,19 @@ func TestUnmarshalFloat32WithOverflow(t *testing.T) { assert.Error(t, UnmarshalKey(m, &in)) }) + t.Run("float32 from string less than float32", func(t *testing.T) { + type inner struct { + Value float32 `key:"float, string"` + } + + m := map[string]any{ + "float": "-1.79769313486231570814527423731704356798070e+300", // overflow + } + + var in inner + assert.Error(t, UnmarshalKey(m, &in)) + }) + t.Run("float32 from json.Number greater than float64", func(t *testing.T) { type inner struct { Value float32 `key:"float"` @@ -1001,6 +1014,19 @@ func TestUnmarshalFloat32WithOverflow(t *testing.T) { var in inner assert.Error(t, UnmarshalKey(m, &in)) }) + + t.Run("float32 from json number less than float32", func(t *testing.T) { + type inner struct { + Value float32 `key:"float"` + } + + m := map[string]any{ + "float": json.Number("-1.79769313486231570814527423731704356798070e+300"), // overflow + } + + var in inner + assert.Error(t, UnmarshalKey(m, &in)) + }) } func TestUnmarshalFloat64WithOverflow(t *testing.T) {