-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.go
60 lines (43 loc) · 796 Bytes
/
counter.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 counter
// @author Mikhail Kirillov <mikkirillov@yandex.ru>
// @version 1.005
// @date 2018-04-26
import (
"sync"
"github.com/belfinor/ldb"
"github.com/belfinor/pack"
)
var mutex sync.Mutex
func Inc(key []byte, val int64) int64 {
mutex.Lock()
defer mutex.Unlock()
raw := ldb.Get(key)
cur := pack.Bytes2Int(raw)
cur += val
if cur <= int64(0) {
ldb.Del(key)
cur = 0
} else {
ldb.Set(key, pack.Int2Bytes(cur))
}
return cur
}
func Get(key []byte) int64 {
raw := ldb.Get(key)
cur := pack.Bytes2Int(raw)
return cur
}
func Reset(key []byte) {
mutex.Lock()
defer mutex.Unlock()
ldb.Del(key)
}
func Set(key []byte, val int64) {
mutex.Lock()
defer mutex.Unlock()
if val <= int64(0) {
ldb.Del(key)
} else {
ldb.Set(key, pack.Int2Bytes(val))
}
}