bitbucket.org/number571/tendermint@v0.8.14/libs/math/safemath.go (about) 1 package math 2 3 import ( 4 "errors" 5 "math" 6 ) 7 8 var ErrOverflowInt32 = errors.New("int32 overflow") 9 var ErrOverflowUint8 = errors.New("uint8 overflow") 10 var ErrOverflowInt8 = errors.New("int8 overflow") 11 12 // SafeAddInt32 adds two int32 integers 13 // If there is an overflow this will panic 14 func SafeAddInt32(a, b int32) int32 { 15 if b > 0 && (a > math.MaxInt32-b) { 16 panic(ErrOverflowInt32) 17 } else if b < 0 && (a < math.MinInt32-b) { 18 panic(ErrOverflowInt32) 19 } 20 return a + b 21 } 22 23 // SafeSubInt32 subtracts two int32 integers 24 // If there is an overflow this will panic 25 func SafeSubInt32(a, b int32) int32 { 26 if b > 0 && (a < math.MinInt32+b) { 27 panic(ErrOverflowInt32) 28 } else if b < 0 && (a > math.MaxInt32+b) { 29 panic(ErrOverflowInt32) 30 } 31 return a - b 32 } 33 34 // SafeConvertInt32 takes a int and checks if it overflows 35 // If there is an overflow this will panic 36 func SafeConvertInt32(a int64) int32 { 37 if a > math.MaxInt32 { 38 panic(ErrOverflowInt32) 39 } else if a < math.MinInt32 { 40 panic(ErrOverflowInt32) 41 } 42 return int32(a) 43 } 44 45 // SafeConvertUint8 takes an int64 and checks if it overflows 46 // If there is an overflow it returns an error 47 func SafeConvertUint8(a int64) (uint8, error) { 48 if a > math.MaxUint8 { 49 return 0, ErrOverflowUint8 50 } else if a < 0 { 51 return 0, ErrOverflowUint8 52 } 53 return uint8(a), nil 54 } 55 56 // SafeConvertInt8 takes an int64 and checks if it overflows 57 // If there is an overflow it returns an error 58 func SafeConvertInt8(a int64) (int8, error) { 59 if a > math.MaxInt8 { 60 return 0, ErrOverflowInt8 61 } else if a < math.MinInt8 { 62 return 0, ErrOverflowInt8 63 } 64 return int8(a), nil 65 }