diff --git a/math/CHANGELOG.md b/math/CHANGELOG.md index be97b7f21e48..cba50310e182 100644 --- a/math/CHANGELOG.md +++ b/math/CHANGELOG.md @@ -40,6 +40,7 @@ Ref: https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.j * [#18247](https://github.com/cosmos/cosmos-sdk/pull/18247) Add mutative api for Uint.BigInt() * [#17803](https://github.com/cosmos/cosmos-sdk/pull/17803) Add mutative api for Int.BigInt() +* [#18030](https://github.com/cosmos/cosmos-sdk/pull/18030) Add mutative api for NewIntFromBigInt ### Bug Fixes diff --git a/math/int.go b/math/int.go index 8685cf5a3fdc..9df290d8ee53 100644 --- a/math/int.go +++ b/math/int.go @@ -126,6 +126,21 @@ func NewIntFromBigInt(i *big.Int) Int { return Int{new(big.Int).Set(i)} } +// NewIntFromBigIntMut constructs Int from big.Int. If the provided big.Int is nil, +// it returns an empty instance. This function panics if the bit length is > 256. +// Note, this function mutate the argument. +func NewIntFromBigIntMut(i *big.Int) Int { + if i == nil { + return Int{} + } + + if i.BitLen() > MaxBitLen { + panic("NewIntFromBigInt() out of bound") + } + + return Int{i} +} + // NewIntFromString constructs Int from string func NewIntFromString(s string) (res Int, ok bool) { i, ok := newIntegerFromString(s) diff --git a/math/int_test.go b/math/int_test.go index 410e395511c4..cbcf29d632dc 100644 --- a/math/int_test.go +++ b/math/int_test.go @@ -56,6 +56,24 @@ func (s *intTestSuite) TestNewIntFromBigInt() { s.Require().NotEqual(r, i.BigInt()) } +func (s *intTestSuite) TestNewIntFromBigIntMut() { + im := math.NewIntFromBigIntMut(nil) + s.Require().True(im.IsNil()) + + r := big.NewInt(42) + im = math.NewIntFromBigIntMut(r) + s.Require().Equal(r, im.BigInt()) + + // Compare value of NewIntFromBigInt and NewIntFromBigIntMut + i := math.NewIntFromBigInt(r) + s.Require().Equal(i, im) + + // modify r and ensure i doesn't change & im changes + r = r.SetInt64(100) + s.Require().NotEqual(r, i.BigInt()) + s.Require().Equal(r, im.BigInt()) +} + func (s *intTestSuite) TestConvertToBigIntMutative() { r := big.NewInt(42) i := math.NewIntFromBigInt(r)