/
counter.go
65 lines (58 loc) · 1.1 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
package tapdance
import "sync"
// CounterUint64 is a goroutine-safe uint64 counter.
// Wraps, if underflows/overflows.
type CounterUint64 struct {
sync.RWMutex
value uint64
}
// Inc increases the counter and returns resulting value
func (c *CounterUint64) Inc() uint64 {
c.Lock()
defer c.Unlock()
if c.value == ^uint64(0) {
// if max
c.value = 0
} else {
c.value++
}
return c.value
}
// GetAndInc returns current value and then increases the counter
func (c *CounterUint64) GetAndInc() uint64 {
c.Lock()
retVal := c.value
if c.value == ^uint64(0) {
// if max
c.value = 0
} else {
c.value++
}
c.Unlock()
return retVal
}
// Dec decrements the counter and returns resulting value
func (c *CounterUint64) Dec() uint64 {
c.Lock()
defer c.Unlock()
if c.value == 0 {
c.value = ^uint64(0)
} else {
c.value--
}
return c.value
}
// Get returns current counter value
func (c *CounterUint64) Get() (value uint64) {
c.RLock()
value = c.value
c.RUnlock()
return
}
// Set assigns current counter value
func (c *CounterUint64) Set(value uint64) {
c.Lock()
c.value = value
c.Unlock()
return
}