From 2968247d9c6772f3b46cc6b4accc24b61cb003a0 Mon Sep 17 00:00:00 2001 From: Matthew Slipper Date: Tue, 7 Jan 2020 07:17:01 -0800 Subject: [PATCH] Merge PR #5479: Add convenience Incr() and Decr() methods to Uint --- types/uint.go | 11 +++++++++++ types/uint_test.go | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/types/uint.go b/types/uint.go index 1cc289b900..976b6414a9 100644 --- a/types/uint.go +++ b/types/uint.go @@ -107,6 +107,17 @@ func (u Uint) Mod(u2 Uint) Uint { return Uint{mod(u.i, u2.i)} } +// Incr increments the Uint by one. +func (u Uint) Incr() Uint { + return u.Add(OneUint()) +} + +// Decr decrements the Uint by one. +// Decr will panic if the Uint is zero. +func (u Uint) Decr() Uint { + return u.Sub(OneUint()) +} + // Quo divides Uint with uint64 func (u Uint) QuoUint64(u2 uint64) Uint { return u.Quo(NewUint(u2)) } diff --git a/types/uint_test.go b/types/uint_test.go index e90fbf7f50..548dea5064 100644 --- a/types/uint_test.go +++ b/types/uint_test.go @@ -50,7 +50,9 @@ func TestUintPanics(t *testing.T) { require.Panics(t, func() { ZeroUint().QuoUint64(0) }) require.Panics(t, func() { OneUint().Quo(ZeroUint().Sub(OneUint())) }) require.Panics(t, func() { uintmax.Add(OneUint()) }) + require.Panics(t, func() { uintmax.Incr() }) require.Panics(t, func() { uintmin.Sub(OneUint()) }) + require.Panics(t, func() { uintmin.Decr() }) require.Equal(t, uint64(0), MinUint(ZeroUint(), OneUint()).Uint64()) require.Equal(t, uint64(1), MaxUint(ZeroUint(), OneUint()).Uint64()) @@ -115,6 +117,7 @@ func TestArithUint(t *testing.T) { {u1.QuoUint64(n2), n1 / n2}, {MinUint(u1, u2), minuint(n1, n2)}, {MaxUint(u1, u2), maxuint(n1, n2)}, + {u1.Incr(), n1 + 1}, } for tcnum, tc := range cases { @@ -132,6 +135,7 @@ func TestArithUint(t *testing.T) { }{ {u1.Sub(u2), n1 - n2}, {u1.SubUint64(n2), n1 - n2}, + {u1.Decr(), n1 - 1}, } for tcnum, tc := range subs { @@ -183,6 +187,14 @@ func TestImmutabilityAllUint(t *testing.T) { func(i *Uint) { _ = i.LT(randuint()) }, func(i *Uint) { _ = i.LTE(randuint()) }, func(i *Uint) { _ = i.String() }, + func(i *Uint) { _ = i.Incr() }, + func(i *Uint) { + if i.IsZero() { + return + } + + _ = i.Decr() + }, } for i := 0; i < 1000; i++ {