From 67c535fdbaed599629848e034b73a009efcfe91a Mon Sep 17 00:00:00 2001 From: Shulhan Date: Fri, 23 Apr 2021 13:14:36 +0700 Subject: math/big: add method IsZero on Int The IsZero method will return true if the current i value is zero. --- lib/math/big/int.go | 9 +++++++++ lib/math/big/int_test.go | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/math/big/int.go b/lib/math/big/int.go index c4cb0289..4cbf2632 100644 --- a/lib/math/big/int.go +++ b/lib/math/big/int.go @@ -12,6 +12,8 @@ import ( "strings" ) +var intZero = NewInt(0) + // // Int extends the standard big.Int package. // @@ -33,6 +35,13 @@ func NewInt(v interface{}) (i *Int) { return i } +// +// IsZero will return true if `i == 0`. +// +func (i *Int) IsZero() bool { + return i.Cmp(&intZero.Int) == 0 +} + // // MarshalJSON implement the json.Marshaler interface and return the output of // String method. diff --git a/lib/math/big/int_test.go b/lib/math/big/int_test.go index 913aacca..003fcdf1 100644 --- a/lib/math/big/int_test.go +++ b/lib/math/big/int_test.go @@ -61,3 +61,21 @@ func TestNewInt(t *testing.T) { test.Assert(t, "NewInt", c.exp, got.String()) } } + +func TestInt_IsZero(t *testing.T) { + cases := []struct { + in *Int + exp bool + }{{ + in: NewInt(0), + exp: true, + }, { + in: NewInt(1), + }, { + in: NewInt(-1), + }} + + for _, c := range cases { + test.Assert(t, "Int.IsZero", c.in.IsZero(), c.exp) + } +} -- cgit v1.3