Skip to content

Commit

Permalink
feat(math): add mutative api for Int.BigInt() (#17803)
Browse files Browse the repository at this point in the history
  • Loading branch information
hieuvubk authored Sep 25, 2023
1 parent 2b22254 commit 150013e
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions math/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ Ref: https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.j

## [Unreleased]

### Features

* [#17803](https://github.com/cosmos/cosmos-sdk/pull/17803) Add mutative api for Int.BigInt()

### Bug Fixes

* [#17725](https://github.com/cosmos/cosmos-sdk/pull/17725) Fix state break in ApproxRoot. This has been present since math/v1.0.1. It changed the rounding behavior at precision end in an intermediary division from banker's to truncation. The truncation occurs from binary right shift in the case of square roots. The change is now reverted back to banker's rounding universally for any root.
Expand Down
8 changes: 8 additions & 0 deletions math/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ func (i Int) BigInt() *big.Int {
return new(big.Int).Set(i.i)
}

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

// IsNil returns true if Int is uninitialized
func (i Int) IsNil() bool {
return i.i == nil
Expand Down
20 changes: 20 additions & 0 deletions math/int_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,26 @@ func (s *intTestSuite) TestNewIntFromBigInt() {
s.Require().NotEqual(r, i.BigInt())
}

func (s *intTestSuite) TestConvertToBigIntMutative() {
r := big.NewInt(42)
i := math.NewIntFromBigInt(r)

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

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

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

func (s *intTestSuite) TestIntPanic() {
// Max Int = 2^256-1 = 1.1579209e+77
// Min Int = -(2^256-1) = -1.1579209e+77
Expand Down

0 comments on commit 150013e

Please sign in to comment.