-
Notifications
You must be signed in to change notification settings - Fork 1
/
integer_values.go
96 lines (75 loc) · 1.6 KB
/
integer_values.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
96
package raphanus
import "github.com/msoap/raphanus/common"
// GetInt - get integer value by key
func (db *DB) GetInt(key string) (int64, error) {
if db.withLock {
db.RLock()
defer db.RUnlock()
}
rawVal, ok := db.data[key]
if !ok {
return 0, raphanuscommon.ErrKeyNotExists
}
value, ok := rawVal.(int64)
if !ok {
return 0, raphanuscommon.ErrKeyTypeMissmatch
}
return value, nil
}
// SetInt - create/update integer value by key
func (db *DB) SetInt(key string, value int64, ttl int) error {
if db.withLock {
db.Lock()
defer db.Unlock()
}
if !isValidKey(key) {
return raphanuscommon.ErrKeyIsNotValid
}
db.data[key] = value
db.setTTL(key, ttl)
return nil
}
// UpdateInt - update integer value by exists key
func (db *DB) UpdateInt(key string, value int64) (err error) {
if db.withLock {
db.Lock()
defer db.Unlock()
}
_, ok := db.data[key]
if !ok {
return raphanuscommon.ErrKeyNotExists
}
db.data[key] = value
return nil
}
// IncrInt - increment integer value on 1
func (db *DB) IncrInt(key string) (err error) {
if db.withLock {
db.Lock()
defer db.Unlock()
}
err = db.addInt(key, 1)
return err
}
// DecrInt - decrement integer value on 1
func (db *DB) DecrInt(key string) (err error) {
if db.withLock {
db.Lock()
defer db.Unlock()
}
err = db.addInt(key, -1)
return err
}
func (db *DB) addInt(key string, value int64) (err error) {
_, ok := db.data[key]
if !ok {
return raphanuscommon.ErrKeyNotExists
}
_, ok = db.data[key].(int64)
if !ok {
return raphanuscommon.ErrKeyTypeMissmatch
}
item := db.data[key].(int64)
db.data[key] = item + value
return nil
}