@@ -18,6 +18,7 @@ package math
18
18
19
19
import (
20
20
"fmt"
21
+ "math/bits"
21
22
"strconv"
22
23
)
23
24
@@ -78,22 +79,20 @@ func MustParseUint64(s string) uint64 {
78
79
return v
79
80
}
80
81
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.
84
83
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
86
86
}
87
87
88
- // SafeAdd returns the result and whether overflow occurred .
88
+ // SafeAdd returns x+y and checks for overflow .
89
89
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
91
92
}
92
93
93
- // SafeMul returns multiplication result and whether overflow occurred .
94
+ // SafeMul returns x*y and checks for overflow .
94
95
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
99
98
}
0 commit comments