-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstats.go
54 lines (40 loc) · 834 Bytes
/
stats.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
package util
import "sync"
// shared by multiple components
type Stats struct {
data map[string]int
mu sync.Mutex
}
func (s *Stats) Increment(key string) {
s.IncrementBy(key, 1)
}
func (s *Stats) IncrementBy(key string, value int) {
s.mu.Lock()
defer s.mu.Unlock()
if s.data == nil {
s.data = make(map[string]int)
}
// this is safe because the default value is 0 and we'll only have count stats
s.data[key] += value
}
func (s *Stats) ToMap() map[string]int {
s.mu.Lock()
defer s.mu.Unlock()
if s.data == nil {
s.data = make(map[string]int)
}
return s.data
}
func (s *Stats) CopyAndReset() *Stats {
s.mu.Lock()
defer s.mu.Unlock()
copiedData := make(map[string]int)
for key, value := range s.data {
copiedData[key] = value
}
copy := &Stats{
data: copiedData,
}
s.data = nil
return copy
}