Skip to content

Commit

Permalink
types: add Abs() method to sdk.Int (#8963)
Browse files Browse the repository at this point in the history
Fixes #8962

Co-authored-by: Alessio Treglia <alessio@tendermint.com>
  • Loading branch information
hallazzang and Alessio Treglia authored Mar 24, 2021
1 parent 56c312a commit 8ee9da7
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 0 deletions.
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

0 comments on commit 8ee9da7

Please sign in to comment.