-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy pathoverflow_template.sh
executable file
·97 lines (85 loc) · 2.21 KB
/
overflow_template.sh
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/bin/sh
exec > overflow_impl.go
echo "package overflow
// Code generated by overflow_template.sh from 'go generate'. DO NOT EDIT."
for SIZE in 8 16 32 64
do
echo "
// Add${SIZE} performs + operation on two int${SIZE} operands, returning a result and status.
func Add${SIZE}(a, b int${SIZE}) (int${SIZE}, bool) {
c := a + b
if (c > a) == (b > 0) {
return c, true
}
return c, false
}
// Add${SIZE}p is the unchecked panicing version of Add${SIZE}.
func Add${SIZE}p(a, b int${SIZE}) int${SIZE} {
r, ok := Add${SIZE}(a, b)
if !ok {
panic(\"addition overflow\")
}
return r
}
// Sub${SIZE} performs - operation on two int${SIZE} operands, returning a result and status.
func Sub${SIZE}(a, b int${SIZE}) (int${SIZE}, bool) {
c := a - b
if (c < a) == (b > 0) {
return c, true
}
return c, false
}
// Sub${SIZE}p is the unchecked panicing version of Sub${SIZE}.
func Sub${SIZE}p(a, b int${SIZE}) int${SIZE} {
r, ok := Sub${SIZE}(a, b)
if !ok {
panic(\"subtraction overflow\")
}
return r
}
// Mul${SIZE} performs * operation on two int${SIZE} operands returning a result and status.
func Mul${SIZE}(a, b int${SIZE}) (int${SIZE}, 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
}
// Mul${SIZE}p is the unchecked panicing version of Mul${SIZE}.
func Mul${SIZE}p(a, b int${SIZE}) int${SIZE} {
r, ok := Mul${SIZE}(a, b)
if !ok {
panic(\"multiplication overflow\")
}
return r
}
// Div${SIZE} performs / operation on two int${SIZE} operands, returning a result and status.
func Div${SIZE}(a, b int${SIZE}) (int${SIZE}, bool) {
q, _, ok := Quotient${SIZE}(a, b)
return q, ok
}
// Div${SIZE}p is the unchecked panicing version of Div${SIZE}.
func Div${SIZE}p(a, b int${SIZE}) int${SIZE} {
r, ok := Div${SIZE}(a, b)
if !ok {
panic(\"division failure\")
}
return r
}
// Quotient${SIZE} performs / operation on two int${SIZE} operands, returning a quotient,
// a remainder and status.
func Quotient${SIZE}(a, b int${SIZE}) (int${SIZE}, int${SIZE}, bool) {
if b == 0 {
return 0, 0, false
}
c := a / b
status := (c < 0) == ((a < 0) != (b < 0)) || (c == 0) // no sign check for 0 quotient
return c, a%b, status
}
"
done