-
Notifications
You must be signed in to change notification settings - Fork 11
/
safemath.go
60 lines (53 loc) · 1.41 KB
/
safemath.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package math
import (
"errors"
"math"
)
var ErrOverflowInt32 = errors.New("int32 overflow")
var ErrOverflowUint8 = errors.New("uint8 overflow")
var ErrOverflowInt8 = errors.New("int8 overflow")
// SafeAddInt32 adds two int32 integers.
func SafeAddInt32(a, b int32) (int32, error) {
if b > 0 && (a > math.MaxInt32-b) {
return 0, ErrOverflowInt32
} else if b < 0 && (a < math.MinInt32-b) {
return 0, ErrOverflowInt32
}
return a + b, nil
}
// SafeSubInt32 subtracts two int32 integers.
func SafeSubInt32(a, b int32) (int32, error) {
if b > 0 && (a < math.MinInt32+b) {
return 0, ErrOverflowInt32
} else if b < 0 && (a > math.MaxInt32+b) {
return 0, ErrOverflowInt32
}
return a - b, nil
}
// SafeConvertInt32 takes a int and checks if it overflows.
func SafeConvertInt32(a int64) (int32, error) {
if a > math.MaxInt32 {
return 0, ErrOverflowInt32
} else if a < math.MinInt32 {
return 0, ErrOverflowInt32
}
return int32(a), nil
}
// SafeConvertUint8 takes an int64 and checks if it overflows.
func SafeConvertUint8(a int64) (uint8, error) {
if a > math.MaxUint8 {
return 0, ErrOverflowUint8
} else if a < 0 {
return 0, ErrOverflowUint8
}
return uint8(a), nil
}
// SafeConvertInt8 takes an int64 and checks if it overflows.
func SafeConvertInt8(a int64) (int8, error) {
if a > math.MaxInt8 {
return 0, ErrOverflowInt8
} else if a < math.MinInt8 {
return 0, ErrOverflowInt8
}
return int8(a), nil
}