Skip to content

Instantly share code, notes, and snippets.

@melekes
Created January 20, 2017 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melekes/ed23251ce80129a3a4fe3086254718f3 to your computer and use it in GitHub Desktop.
Save melekes/ed23251ce80129a3a4fe3086254718f3 to your computer and use it in GitHub Desktop.
// 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