ints: stricter numbers (#4939)

This commit is contained in:
Marko
2020-06-04 16:34:56 +02:00
committed by GitHub
parent 7c576f02ab
commit a88537bb88
56 changed files with 738 additions and 674 deletions

41
libs/math/safemath.go Normal file
View File

@@ -0,0 +1,41 @@
package math
import (
"errors"
"math"
)
var ErrOverflowInt32 = errors.New("int32 overflow")
// SafeAddInt32 adds two int32 integers
// If there is an overflow this will panic
func SafeAddInt32(a, b int32) int32 {
if b > 0 && (a > math.MaxInt32-b) {
panic(ErrOverflowInt32)
} else if b < 0 && (a < math.MinInt32-b) {
panic(ErrOverflowInt32)
}
return a + b
}
// SafeSubInt32 subtracts two int32 integers
// If there is an overflow this will panic
func SafeSubInt32(a, b int32) int32 {
if b > 0 && (a < math.MinInt32+b) {
panic(ErrOverflowInt32)
} else if b < 0 && (a > math.MaxInt32+b) {
panic(ErrOverflowInt32)
}
return a - b
}
// SafeConvertInt32 takes a int and checks if it overflows
// If there is an overflow this will panic
func SafeConvertInt32(a int64) int32 {
if a > math.MaxInt32 {
panic(ErrOverflowInt32)
} else if a < math.MinInt32 {
panic(ErrOverflowInt32)
}
return int32(a)
}