Skip to content

Commit

Permalink
feat(math): Add mutative api for NewIntFromBigInt (#18030)
Browse files Browse the repository at this point in the history
  • Loading branch information
hieuvubk committed Nov 7, 2023
1 parent a6eea3c commit e7e1c36
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions math/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 15 additions & 0 deletions math/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions math/int_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit e7e1c36

Please sign in to comment.