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

types: add Abs() method to sdk.Int #8963

Merged
merged 5 commits into from
Mar 24, 2021
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* (x/auth) [\#8522](https://github.com/cosmos/cosmos-sdk/pull/8522) Allow to query all stored accounts
* (crypto/types) [\#8600](https://github.com/cosmos/cosmos-sdk/pull/8600) `CompactBitArray`: optimize the `NumTrueBitsBefore` method and add an `Equal` method.
* (x/upgrade) [\#8743](https://github.com/cosmos/cosmos-sdk/pull/8743) Add tracking module versions as per ADR-041
* (types) [\#8962](https://github.com/cosmos/cosmos-sdk/issues/8962) Add `Abs()` method to `sdk.Int`.

### Bug Fixes

Expand Down
7 changes: 7 additions & 0 deletions types/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ func mod(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) }

func neg(i *big.Int) *big.Int { return new(big.Int).Neg(i) }

func abs(i *big.Int) *big.Int { return new(big.Int).Abs(i) }

func min(i *big.Int, i2 *big.Int) *big.Int {
if i.Cmp(i2) == 1 {
return new(big.Int).Set(i2)
Expand Down Expand Up @@ -304,6 +306,11 @@ func (i Int) Neg() (res Int) {
return Int{neg(i.i)}
}

// Abs returns the absolute value of Int.
func (i Int) Abs() Int {
return Int{abs(i.i)}
}

// return the minimum of the ints
func MinInt(i1, i2 Int) Int {
return Int{min(i1.BigInt(), i2.BigInt())}
Expand Down
3 changes: 3 additions & 0 deletions types/int_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ func (s *intTestSuite) TestArithInt() {
{sdk.MinInt(i1, i2), minint(n1, n2)},
{sdk.MaxInt(i1, i2), maxint(n1, n2)},
{i1.Neg(), -n1},
{i1.Abs(), n1},
{i1.Neg().Abs(), n1},
}

for tcnum, tc := range cases {
Expand Down Expand Up @@ -206,6 +208,7 @@ func (s *intTestSuite) TestImmutabilityAllInt() {
func(i *sdk.Int) { _ = i.MulRaw(rand.Int63()) },
func(i *sdk.Int) { _ = i.QuoRaw(rand.Int63()) },
func(i *sdk.Int) { _ = i.Neg() },
func(i *sdk.Int) { _ = i.Abs() },
func(i *sdk.Int) { _ = i.IsZero() },
func(i *sdk.Int) { _ = i.Sign() },
func(i *sdk.Int) { _ = i.Equal(randint()) },
Expand Down