-
Notifications
You must be signed in to change notification settings - Fork 2
/
concurrent_counter.go
43 lines (36 loc) · 1019 Bytes
/
concurrent_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
package counter
import (
cmap "github.com/orcaman/concurrent-map"
)
// ConcurrentCounter is a thread-safe version of Counter
type ConcurrentCounter struct {
counter cmap.ConcurrentMap
}
func NewConcurrentCounter() *ConcurrentCounter {
return &ConcurrentCounter{cmap.New()}
}
// Update add a new element to the counter.
func (c *ConcurrentCounter) Update(elem string) {
c.counter.Upsert(elem, 1, func(exist bool, valueInMap interface{}, newValue interface{}) interface{} {
if exist {
return valueInMap.(int) + 1
}
return newValue
})
}
// Has checks whether the elem has been counted before.
func (c *ConcurrentCounter) Has(elem string) bool {
return c.counter.Has(elem)
}
// Unique returns the number of unique elements counted.
func (c *ConcurrentCounter) Unique() int {
return c.counter.Count()
}
// Has checks whether the elem has been counted before.
func (c *ConcurrentCounter) Total() int {
var total int
for t := range c.counter.IterBuffered() {
total += t.Val.(int)
}
return total
}