Skip to content

Commit

Permalink
Fix panic in New() with large value and negative exp (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
Neal authored May 29, 2023
1 parent 3bc6300 commit 3145a27
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
5 changes: 1 addition & 4 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]}
Expand Down Expand Up @@ -1081,7 +1079,6 @@ func (d *NullDecimal) UnmarshalText(text []byte) error {

d.Valid = true
return nil

}

func (d NullDecimal) Value() (driver.Value, error) {
Expand Down
13 changes: 12 additions & 1 deletion decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 3145a27

Please sign in to comment.