File: refcount.go

package info (click to toggle)
incus 6.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,428 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (60 lines) | stat: -rw-r--r-- 1,307 bytes parent folder | download | duplicates (7)
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
}