Skip to content

Commit

Permalink
Handle mod 0 uniformly for all API methods (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
karalabe authored Jul 24, 2020
1 parent 4ce82e6 commit 6785da6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
12 changes: 10 additions & 2 deletions uint256.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,12 @@ func (z *Int) AddOverflow(x, y *Int) bool {
return carry != 0
}

// AddMod sets z to the sum ( x+y ) mod m, and returns z
// AddMod sets z to the sum ( x+y ) mod m, and returns z.
// If m == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Int) AddMod(x, y, m *Int) *Int {
if m.IsZero() {
return z.Clear()
}
if z == m { // z is an alias for m // TODO: Understand why needed and add tests for all "division" methods.
m = m.Clone()
}
Expand Down Expand Up @@ -567,8 +571,12 @@ func (z *Int) SMod(x, y *Int) *Int {
}

// MulMod calculates the modulo-m multiplication of x and y and
// returns z
// returns z.
// If m == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Int) MulMod(x, y, m *Int) *Int {
if x.IsZero() || y.IsZero() || m.IsZero() {
return z.Clear()
}
p := umul(x, y)
var (
pl Int
Expand Down
23 changes: 20 additions & 3 deletions uint256_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ var (

// A collection of interesting input values for ternary operators (addmod, mulmod).
ternTestCases = [][3]string{
{"0", "0", "0"},
{"1", "0", "0"},
{"1", "1", "0"},
{"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe", "0"},
{"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
{"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd", "3", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
Expand Down Expand Up @@ -920,9 +924,22 @@ func TestTernOp(t *testing.T) {
}
}
}

t.Run("AddMod", func(t *testing.T) { proc(t, (*Int).AddMod, addMod) })
t.Run("MulMod", func(t *testing.T) { proc(t, (*Int).MulMod, mulMod) })
t.Run("AddMod", func(t *testing.T) {
proc(t, (*Int).AddMod, func(z, x, y, m *big.Int) *big.Int {
if m.Sign() == 0 {
return z.SetUint64(0)
}
return addMod(z, x, y, m)
})
})
t.Run("MulMod", func(t *testing.T) {
proc(t, (*Int).MulMod, func(z, x, y, m *big.Int) *big.Int {
if m.Sign() == 0 {
return z.SetUint64(0)
}
return mulMod(z, x, y, m)
})
})
}

func TestCmpOp(t *testing.T) {
Expand Down

0 comments on commit 6785da6

Please sign in to comment.