forked from kubeflow/common
/
counter.go
71 lines (60 loc) · 1.06 KB
/
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
61
62
63
64
65
66
67
68
69
70
71
package util
import (
"fmt"
"sync"
)
type Counter struct {
lock sync.Mutex
data map[string]int
}
func NewCounter() *Counter {
return &Counter{
lock: sync.Mutex{},
data: map[string]int{},
}
}
func (c *Counter) Inc(key string) {
c.lock.Lock()
defer c.lock.Unlock()
v, ok := c.data[key]
if ok {
c.data[key] = v + 1
return
}
c.data[key] = 0
}
func (c *Counter) DeleteKey(key string) {
c.lock.Lock()
defer c.lock.Lock()
delete(c.data, key)
}
func (c *Counter) Counts(key string) (int, error) {
c.lock.Lock()
defer c.lock.Unlock()
v, ok := c.data[key]
if !ok {
return 0, fmt.Errorf("cannot get key %s", key)
}
var err error = nil
if v < 0 {
err = fmt.Errorf("count %s:%d is negative", key, v)
}
return v, err
}
func (c *Counter) Dec(key string) error {
c.lock.Lock()
defer c.lock.Unlock()
v, ok := c.data[key]
if ok {
if v > 1 {
c.data[key] = v - 1
return nil
}
if v == 1 {
c.DeleteKey(key)
return nil
}
return fmt.Errorf("cannot minus one: key %s has value %d", key, v)
}
return fmt.Errorf("cannot find key %s", key)
}