Skip to content

Commit

Permalink
BigIntMut() for legacyDec and test
Browse files Browse the repository at this point in the history
  • Loading branch information
DongLieu committed Nov 9, 2023
1 parent 19e57dd commit 0c9ed37
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions math/dec.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,15 @@ func (d LegacyDec) BigInt() *big.Int {
return cp.Set(d.i)
}

// BigIntMut converts LegacyDec to big.Int, mutative the input
func (d LegacyDec) BigIntMut() *big.Int {
if d.IsNil() {
return nil
}

return d.i
}

func (d LegacyDec) ImmutOp(op func(LegacyDec, LegacyDec) LegacyDec, d2 LegacyDec) LegacyDec {
return op(d.Clone(), d2)
}
Expand Down
20 changes: 20 additions & 0 deletions math/dec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -754,3 +754,23 @@ func TestNegativePrecisionPanic(t *testing.T) {
math.LegacyNewDecWithPrec(10, -1)
})
}

func (s *decimalTestSuite) TestConvertToBigIntMutativeForLegacyDec() {
r := big.NewInt(30)
i := math.LegacyNewDecFromBigInt(r)

// Compare value of BigInt & BigIntMut
s.Require().Equal(i.BigInt(), i.BigIntMut())

// Modify BigIntMut() pointer and ensure i.BigIntMut() & i.BigInt() change
p1 := i.BigIntMut()
p1.SetInt64(40)
s.Require().Equal(big.NewInt(40), i.BigIntMut())
s.Require().Equal(big.NewInt(40), i.BigInt())

// Modify big.Int() pointer and ensure i.BigIntMut() & i.BigInt() don't change
p2 := i.BigInt()
p2.SetInt64(50)
s.Require().NotEqual(big.NewInt(50), i.BigIntMut())
s.Require().NotEqual(big.NewInt(50), i.BigInt())
}

0 comments on commit 0c9ed37

Please sign in to comment.