Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(math): add mutative api for Int.BigInt() #17803

Merged
merged 8 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved

* [#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