forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
refcount.go
60 lines (46 loc) · 1.28 KB
/
refcount.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 refcount
import (
"fmt"
"sync"
)
var refCounters = map[string]uint{}
// refCounterMutex is used to access refCounters safely.
var refCounterMutex sync.Mutex
// Get returns the current value of the refCounter.
func Get(refCounter string) uint {
refCounterMutex.Lock()
defer refCounterMutex.Unlock()
return refCounters[refCounter]
}
// Increment increases a refCounter by the value. If the ref counter doesn't exist, a new one is created.
// The counter's new value is returned.
func Increment(refCounter string, value uint) uint {
refCounterMutex.Lock()
defer refCounterMutex.Unlock()
v := refCounters[refCounter]
oldValue := v
v = v + value
if v < oldValue {
panic(fmt.Sprintf("Ref counter %q overflowed from %d to %d", refCounter, oldValue, v))
}
refCounters[refCounter] = v
return v
}
// Decrement decreases a refCounter by the value. If the ref counter doesn't exist, a new one is created.
// The counter's new value is returned. A counter cannot be decreased below zero.
func Decrement(refCounter string, value uint) uint {
refCounterMutex.Lock()
defer refCounterMutex.Unlock()
v := refCounters[refCounter]
if v < value {
v = 0
} else {
v = v - value
}
if v == 0 {
delete(refCounters, refCounter)
} else {
refCounters[refCounter] = v
}
return v
}