Skip to content

Commit 77fa9aa

Browse files
authored
Merge pull request #108 from nvanbenschoten/nvanbenschoten/interop
apd: add apd.BigInt / math/big.Int interop methods
2 parents f2c65f2 + 500bc48 commit 77fa9aa

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

bigint.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,3 +937,22 @@ func (z *BigInt) Xor(x, y *BigInt) *BigInt {
937937
z.updateInner(zi)
938938
return z
939939
}
940+
941+
///////////////////////////////////////////////////////////////////////////////
942+
// apd.BigInt / math/big.Int interop //
943+
///////////////////////////////////////////////////////////////////////////////
944+
945+
// MathBigInt returns the math/big.Int representation of z.
946+
func (z *BigInt) MathBigInt() *big.Int {
947+
var tmp1 big.Int
948+
return z.inner(&tmp1)
949+
}
950+
951+
// SetMathBigInt sets z to x and returns z.
952+
func (z *BigInt) SetMathBigInt(x *big.Int) *BigInt {
953+
var tmp1 big.Int
954+
zi := z.inner(&tmp1)
955+
zi.Set(x)
956+
z.updateInner(zi)
957+
return z
958+
}

bigint_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -751,6 +751,32 @@ func TestBigIntMatchesMathBigInt(t *testing.T) {
751751
})
752752
}
753753

754+
// TestBigIntMathBigIntRoundTrip uses testing/quick to verify that the
755+
// apd.BigInt / math/big.Int interoperation methods each round-trip.
756+
func TestBigIntMathBigIntRoundTrip(t *testing.T) {
757+
t.Run("apd->math->apd", func(t *testing.T) {
758+
base := func(z number) string {
759+
return z.toApd(t).String()
760+
}
761+
roundtrip := func(z number) string {
762+
bi := z.toApd(t).MathBigInt()
763+
return new(BigInt).SetMathBigInt(bi).String()
764+
}
765+
require(t, quick.CheckEqual(base, roundtrip, nil))
766+
})
767+
768+
t.Run("math->apd->math", func(t *testing.T) {
769+
base := func(z number) string {
770+
return z.toMath(t).String()
771+
}
772+
roundtrip := func(z number) string {
773+
bi := new(BigInt).SetMathBigInt(z.toMath(t))
774+
return bi.MathBigInt().String()
775+
}
776+
require(t, quick.CheckEqual(base, roundtrip, nil))
777+
})
778+
}
779+
754780
// number is a quick.Generator for large integer numbers.
755781
type number string
756782

0 commit comments

Comments
 (0)