From e7e1c36222f9c56afde6cba8ccdd2b0370dcd994 Mon Sep 17 00:00:00 2001 From: Hieu Vu <72878483+hieuvubk@users.noreply.github.com> Date: Tue, 7 Nov 2023 15:36:39 +0700 Subject: [PATCH] feat(math): Add mutative api for NewIntFromBigInt (#18030) --- math/CHANGELOG.md | 1 + math/int.go | 15 +++++++++++++++ math/int_test.go | 18 ++++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/math/CHANGELOG.md b/math/CHANGELOG.md index be97b7f21e..cba50310e1 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 8685cf5a3f..9df290d8ee 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 410e395511..cbcf29d632 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)