-
Notifications
You must be signed in to change notification settings - Fork 33
/
idpool.go
56 lines (49 loc) · 1.13 KB
/
idpool.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
package idpool
// Pool keeps track of uint64 identifiers.
//
// Caller is reponsible for locking.
type Pool struct {
// x<next are reserved, unless free says otherwise; next==0 means
// none are reserved.
next uint64
free []uint64
}
// Get returns an available id from the pool.
//
// Get panics if the pool is exhausted; 2**64 should be enough for
// everyone.
func (p *Pool) Get() uint64 {
var id uint64
if n := len(p.free); n > 0 {
id = p.free[n-1]
p.free = p.free[:n-1]
return id
}
r := p.next
p.next++
// TODO panic somewhere around here if wraparound!!
return r
}
// Put returns an id to the pool.
func (p *Pool) Put(id uint64) {
p.free = append(p.free, id)
}
// SetMinimum sets the minimum value that will be returned. This is
// useful for reserving some ids for special use.
func (p *Pool) SetMinimum(min uint64) {
if p.next < min {
p.next = min
}
// make sure the reserved ids aren't returned from the free list
// either
for i, id := range p.free {
if id < min {
n := len(p.free) - 1
if i < n {
// move last item here so we can just truncate
p.free[i] = p.free[n]
}
p.free = p.free[:n]
}
}
}