diff --git a/conversion.go b/conversion.go index 559451e2..c7da0c73 100644 --- a/conversion.go +++ b/conversion.go @@ -41,7 +41,11 @@ var ( ) // ToBig returns a big.Int version of z. +// Return `nil` if z is nil func (z *Int) ToBig() *big.Int { + if z == nil { + return nil + } b := new(big.Int) switch maxWords { // Compile-time check. case 4: // 64-bit architectures. @@ -61,7 +65,11 @@ func (z *Int) ToBig() *big.Int { // FromBig is a convenience-constructor from big.Int. // Returns a new Int and whether overflow occurred. +// OBS: If b is `nil`, this method returns `nil, false` func FromBig(b *big.Int) (*Int, bool) { + if b == nil { + return nil, false + } z := &Int{} overflow := z.SetFromBig(b) return z, overflow @@ -69,7 +77,12 @@ func FromBig(b *big.Int) (*Int, bool) { // MustFromBig is a convenience-constructor from big.Int. // Returns a new Int and panics if overflow occurred. +// OBS: If b is `nil`, this method does _not_ panic, but +// instead returns `nil` func MustFromBig(b *big.Int) *Int { + if b == nil { + return nil + } z := &Int{} if z.SetFromBig(b) { panic("overflow") diff --git a/conversion_test.go b/conversion_test.go index 37a26fb0..05451add 100644 --- a/conversion_test.go +++ b/conversion_test.go @@ -19,15 +19,27 @@ var ( ) func TestFromBig(t *testing.T) { - a := new(big.Int) + var a *big.Int b, o := FromBig(a) + if o { + t.Fatalf("nil conversion overflowed! big.Int %x", b) + } + if b != nil { + t.Fatalf("got %x, exp %v", b, nil) + } + b2 := MustFromBig(a) + if b2 != nil { + t.Fatalf("got %x, exp %v", b2, nil) + } + a = new(big.Int) + b, o = FromBig(a) if o { t.Fatalf("conversion overflowed! big.Int %x", a.Bytes()) } if exp, got := a.Bytes(), b.Bytes(); !bytes.Equal(got, exp) { t.Fatalf("got %x exp %x", got, exp) } - b2 := MustFromBig(a) + b2 = MustFromBig(a) if exp, got := a.Bytes(), b2.Bytes(); !bytes.Equal(got, exp) { t.Fatalf("got %x exp %x", got, exp) } @@ -211,7 +223,10 @@ func TestFromBigOverflow(t *testing.T) { } func TestToBig(t *testing.T) { - + var uint256Nil *Int + if bigNil := uint256Nil.ToBig(); bigNil != nil { + t.Errorf("want big.Int , have %x", bigNil) + } if bigZero := new(Int).ToBig(); bigZero.Cmp(new(big.Int)) != 0 { t.Errorf("expected big.Int 0, got %x", bigZero) }