Skip to content

Commit

Permalink
MulOverflow (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
yperbasis authored Jun 5, 2020
1 parent c8f0ce8 commit ccc827b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
14 changes: 14 additions & 0 deletions uint256.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,20 @@ func (z *Int) Mul(x, y *Int) *Int {
return z.Set(&res)
}

// MulOverflow sets z to the product x*y, and returns whether overflow occurred
func (z *Int) MulOverflow(x, y *Int) bool {
p := umul(x, y)
var (
pl Int
ph Int
)
copy(pl[:], p[:4])
copy(ph[:], p[4:])

z.Set(&pl)
return !ph.IsZero()
}

func (z *Int) squared() {
var (
res Int
Expand Down
21 changes: 21 additions & 0 deletions uint256_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,27 @@ func TestRandomMul(t *testing.T) {
},
)
}
func TestRandomMulOverflow(t *testing.T) {
for i := 0; i < 10000; i++ {
b, f1, err := randNums()
if err != nil {
t.Fatal(err)
}
b2, f2, err := randNums()
if err != nil {
t.Fatal(err)
}
f1a, f2a := f1.Clone(), f2.Clone()
overflow := f1.MulOverflow(f1, f2)
b.Mul(b, b2)
if err := checkOverflow(b, f1, overflow); err != nil {
t.Fatal(err)
}
if eq := checkEq(b, f1); !eq {
t.Fatalf("Expected equality:\nf1= %x\nf2= %x\n[ - ]==\nf= %x\nb= %x\n", f1a, f2a, f1, b)
}
}
}
func TestRandomSquare(t *testing.T) {
testRandomOp(t,
func(f1, f2, f3 *Int) {
Expand Down

0 comments on commit ccc827b

Please sign in to comment.