Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// addOrMax performs safe addition: if result overflows, it returns MaxUint64
func addOrMax(accum, value uint64) uint64 {
if (accum + value) < accum {
return math.MaxUint64
} else {
return accum + value
}
}
// subOrZero performs safe subtraction: if result underflows, it returns 0
func subOrZero(accum, value uint64) uint64 {
if accum >= value {
return accum - value
} else {
return 0
}
}
// mulOrMaxIfOverflows performs safe multiplication: if result overflows, it returns MaxUint64
func mulOrMaxIfOverflows(a, b uint64) uint64 {
if mulOverflows(a, b) {
return math.MaxUint64
} else {
return a * b
}
}
// mulOverflows checks for overflow
func mulOverflows(a, b uint64) bool {
if a <= 1 || b <= 1 {
return false
}
c := a * b
return c/b != a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.