Created
January 20, 2017 08:33
-
-
Save melekes/ed23251ce80129a3a4fe3086254718f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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