max – How to Implement Overflow Handling in Go
Take a look at the SEI CERT C Coding Standard: INT32-C. Ensure that operations on signed integers do not result in overflow. Translate the C signed int Compliant Solution to Go int64.
package main
import (
"fmt"
"math"
)
/*
SEI CERT C Coding Standard
INT32-C. Ensure that operations on signed integers do not result in overflow
https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow
Compliant Solution
*/
func sum(a, b int64) (int64, error) {
if ((b > 0) && (a > (math.MaxInt64 - b))) ||
((b < 0) && (a < (math.MinInt64 - b))) {
err := fmt.Errorf("overflow: %d + %d", a, b)
return 0, err
} else {
return a + b, nil
}
}
func main() {
fmt.Println(sum(42, -24))
fmt.Println(sum(math.MaxInt64, +0))
fmt.Println(sum(math.MinInt64, -0))
fmt.Println(sum(math.MaxInt64, 1))
fmt.Println(sum(math.MinInt64, -1))
}
18
9223372036854775807
-9223372036854775808
0 overflow: 9223372036854775807 + 1
0 overflow: -9223372036854775808 + -1
Read more here: Source link
