forked from beego/beego-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc_utils.go
95 lines (89 loc) · 1.9 KB
/
calc_utils.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
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
package cache
import (
"math"
berror "github.com/beego/beego-error/v2"
)
var (
ErrIncrementOverflow = berror.Error(IncrementOverflow, "this incr invocation will overflow.")
ErrDecrementOverflow = berror.Error(DecrementOverflow, "this decr invocation will overflow.")
ErrNotIntegerType = berror.Error(NotIntegerType, "item val is not (u)int (u)int32 (u)int64")
)
const (
MinUint32 uint32 = 0
MinUint64 uint64 = 0
)
func incr(originVal interface{}) (interface{}, error) {
switch val := originVal.(type) {
case int:
tmp := val + 1
if val > 0 && tmp < 0 {
return nil, ErrIncrementOverflow
}
return tmp, nil
case int32:
if val == math.MaxInt32 {
return nil, ErrIncrementOverflow
}
return val + 1, nil
case int64:
if val == math.MaxInt64 {
return nil, ErrIncrementOverflow
}
return val + 1, nil
case uint:
tmp := val + 1
if tmp < val {
return nil, ErrIncrementOverflow
}
return tmp, nil
case uint32:
if val == math.MaxUint32 {
return nil, ErrIncrementOverflow
}
return val + 1, nil
case uint64:
if val == math.MaxUint64 {
return nil, ErrIncrementOverflow
}
return val + 1, nil
default:
return nil, ErrNotIntegerType
}
}
func decr(originVal interface{}) (interface{}, error) {
switch val := originVal.(type) {
case int:
tmp := val - 1
if val < 0 && tmp > 0 {
return nil, ErrDecrementOverflow
}
return tmp, nil
case int32:
if val == math.MinInt32 {
return nil, ErrDecrementOverflow
}
return val - 1, nil
case int64:
if val == math.MinInt64 {
return nil, ErrDecrementOverflow
}
return val - 1, nil
case uint:
if val == 0 {
return nil, ErrDecrementOverflow
}
return val - 1, nil
case uint32:
if val == MinUint32 {
return nil, ErrDecrementOverflow
}
return val - 1, nil
case uint64:
if val == MinUint64 {
return nil, ErrDecrementOverflow
}
return val - 1, nil
default:
return nil, ErrNotIntegerType
}
}