Skip to content

Commit 6ccce09

Browse files
authored
common/math: use math/bits intrinsics for Safe* (#21316)
This is a resubmit of erigontech/erigon#556. The performance benefit of this change is negligible, but it does remove a TODO.
1 parent bcb3087 commit 6ccce09

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

common/math/integer.go

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package math
1818

1919
import (
2020
"fmt"
21+
"math/bits"
2122
"strconv"
2223
)
2324

@@ -78,22 +79,20 @@ func MustParseUint64(s string) uint64 {
7879
return v
7980
}
8081

81-
// NOTE: The following methods need to be optimised using either bit checking or asm
82-
83-
// SafeSub returns subtraction result and whether overflow occurred.
82+
// SafeSub returns x-y and checks for overflow.
8483
func SafeSub(x, y uint64) (uint64, bool) {
85-
return x - y, x < y
84+
diff, borrowOut := bits.Sub64(x, y, 0)
85+
return diff, borrowOut != 0
8686
}
8787

88-
// SafeAdd returns the result and whether overflow occurred.
88+
// SafeAdd returns x+y and checks for overflow.
8989
func SafeAdd(x, y uint64) (uint64, bool) {
90-
return x + y, y > MaxUint64-x
90+
sum, carryOut := bits.Add64(x, y, 0)
91+
return sum, carryOut != 0
9192
}
9293

93-
// SafeMul returns multiplication result and whether overflow occurred.
94+
// SafeMul returns x*y and checks for overflow.
9495
func SafeMul(x, y uint64) (uint64, bool) {
95-
if x == 0 || y == 0 {
96-
return 0, false
97-
}
98-
return x * y, y > MaxUint64/x
96+
hi, lo := bits.Mul64(x, y)
97+
return lo, hi != 0
9998
}

0 commit comments

Comments
 (0)