Skip to content

Commit

Permalink
common/math: use math/bits intrinsics for Safe* (ethereum#21316)
Browse files Browse the repository at this point in the history
This is a resubmit of erigontech/erigon#556. The performance
benefit of this change is negligible, but it does remove a TODO.
  • Loading branch information
fjl authored Jul 9, 2020
1 parent bcb3087 commit 6ccce09
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions common/math/integer.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package math

import (
"fmt"
"math/bits"
"strconv"
)

Expand Down Expand Up @@ -78,22 +79,20 @@ func MustParseUint64(s string) uint64 {
return v
}

// NOTE: The following methods need to be optimised using either bit checking or asm

// SafeSub returns subtraction result and whether overflow occurred.
// SafeSub returns x-y and checks for overflow.
func SafeSub(x, y uint64) (uint64, bool) {
return x - y, x < y
diff, borrowOut := bits.Sub64(x, y, 0)
return diff, borrowOut != 0
}

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

// SafeMul returns multiplication result and whether overflow occurred.
// SafeMul returns x*y and checks for overflow.
func SafeMul(x, y uint64) (uint64, bool) {
if x == 0 || y == 0 {
return 0, false
}
return x * y, y > MaxUint64/x
hi, lo := bits.Mul64(x, y)
return lo, hi != 0
}

0 comments on commit 6ccce09

Please sign in to comment.