@@ -18,6 +18,7 @@ package math
1818
1919import (
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.
8483func 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 .
8989func 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 .
9495func 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