Browse Source

types: simplify safeMul (#5061)

Refs https://github.com/tendermint/tendermint/pull/4764#discussion_r446488731

also, multiplication using * should be more efficient.
pull/5066/head
Anton Kaliaev 4 years ago
committed by GitHub
parent
commit
9b7f260bbb
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 16 deletions
  1. +6
    -14
      types/validator_set.go
  2. +2
    -2
      types/validator_set_test.go

+ 6
- 14
types/validator_set.go View File

@ -988,22 +988,14 @@ func safeMul(a, b int64) (int64, bool) {
absOfB = -b
}
var (
c = a
overflow bool
)
for absOfB > 1 {
c, overflow = safeAdd(c, a)
if overflow {
return c, true
}
absOfB--
absOfA := a
if a < 0 {
absOfA = -a
}
if (b < 0 && a > 0) || (b < 0 && a < 0) {
return -c, false
if absOfA > math.MaxInt64/absOfB {
return 0, true
}
return c, false
return a * b, false
}

+ 2
- 2
types/validator_set_test.go View File

@ -1482,8 +1482,8 @@ func TestSafeMul(t *testing.T) {
5: {-2, 3, -6, false},
6: {math.MaxInt64, 1, math.MaxInt64, false},
7: {math.MaxInt64 / 2, 2, math.MaxInt64 - 1, false},
8: {math.MaxInt64 / 2, 3, -1, true},
9: {math.MaxInt64, 2, -1, true},
8: {math.MaxInt64 / 2, 3, 0, true},
9: {math.MaxInt64, 2, 0, true},
}
for i, tc := range testCases {


Loading…
Cancel
Save