From 3145a275866ada3f64df5c50c125df4dbb6952c0 Mon Sep 17 00:00:00 2001 From: Neal Patel Date: Mon, 29 May 2023 11:11:34 -0500 Subject: [PATCH] Fix panic in New() with large value and negative exp (#8) --- decimal.go | 5 +---- decimal_test.go | 13 ++++++++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/decimal.go b/decimal.go index ecb236a..e62b503 100644 --- a/decimal.go +++ b/decimal.go @@ -124,9 +124,7 @@ func New(value int64, exp int32) Decimal { if value >= minInt*s && value <= maxInt*s { return Decimal{fixed: value * pow10Table[precision+exp]} } - } - // when exp > 7, it would be greater than maxInt - if exp <= 6 { + } else if exp <= 6 { // when exp > 6, it would be greater than maxInt s := pow10Table[exp] if value >= minInt/s && value <= maxInt/s { return Decimal{fixed: value * pow10Table[precision+exp]} @@ -1081,7 +1079,6 @@ func (d *NullDecimal) UnmarshalText(text []byte) error { d.Valid = true return nil - } func (d NullDecimal) Value() (driver.Value, error) { diff --git a/decimal_test.go b/decimal_test.go index f78b571..5061c5b 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -138,6 +138,18 @@ func TestDecimal(t *testing.T) { shouldEqual(t, x, alpacadecimal.RequireFromString("10000000")) require.False(t, x.IsOptimized()) } + + { + x := alpacadecimal.New(10_000_000, 0) + shouldEqual(t, x, alpacadecimal.RequireFromString("10000000")) + require.False(t, x.IsOptimized()) + } + + { + x := alpacadecimal.New(1_000_000_000, -2) + shouldEqual(t, x, alpacadecimal.RequireFromString("10000000")) + require.False(t, x.IsOptimized()) + } }) t.Run("NewFromBigInt", func(t *testing.T) { @@ -184,7 +196,6 @@ func TestDecimal(t *testing.T) { require.NoError(t, err) require.Equal(t, x.String(), y.String()) - }) t.Run("NewFromInt", func(t *testing.T) {