types: simplify safeMul (#5061)

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

also, multiplication using * should be more efficient.
This commit is contained in:
Anton Kaliaev
2020-06-29 20:26:14 +04:00
committed by GitHub
parent 04b8cf7879
commit 9b7f260bbb
2 changed files with 8 additions and 16 deletions

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
}

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 {