-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoverflow.go
56 lines (49 loc) · 905 Bytes
/
overflow.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
package overflow
type Int interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}
func Add[T Int](a, b T) (T, bool) {
c := a + b
if (c > a) == (b > 0) {
return c, true
}
return c, false
}
func Sub[T Int](a, b T) (T, bool) {
c := a - b
if (c < a) == (b > 0) {
return c, true
}
return c, false
}
func Mul[T Int](a, b T) (T, bool) {
if a == 0 || b == 0 {
return 0, true
}
c := a * b
if (c < 0) == ((a < 0) != (b < 0)) {
if c/b == a {
return c, true
}
}
return c, false
}
func Div[T Int](a, b T) (T, bool) {
q, _, ok := Quotient(a, b)
return q, ok
}
func Quotient[T Int](a, b T) (T, T, bool) {
if b == 0 {
return 0, 0, false
}
c := a / b
ok := (c < 0) == ((a < 0) != (b < 0))
return c, a % b, ok
}
func Convert[T Int, U Int](a T) (U, bool) {
b := U(a)
if T(b) == a && (a < 0) == (b < 0) {
return b, true
}
return b, false
}