diff --git a/math/CHANGELOG.md b/math/CHANGELOG.md index 7c99cdd23e..585006ea2a 100644 --- a/math/CHANGELOG.md +++ b/math/CHANGELOG.md @@ -36,6 +36,10 @@ Ref: https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.j ## [Unreleased] +### Features + +* [#18421](https://github.com/cosmos/cosmos-sdk/pull/18421) Add mutative api for `LegacyDec.BigInt()`. + ## [math/v1.2.0](https://github.com/cosmos/cosmos-sdk/releases/tag/math/v1.2.0) - 2023-11-07 ### Features diff --git a/math/dec.go b/math/dec.go index 794a93b4e3..1cff954936 100644 --- a/math/dec.go +++ b/math/dec.go @@ -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) } diff --git a/math/dec_test.go b/math/dec_test.go index 85ff732c52..45cec78ae1 100644 --- a/math/dec_test.go +++ b/math/dec_test.go @@ -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()) +}