File: id_pool.go

package info (click to toggle)
golang-github-jtolds-gls 4.2.1-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 92 kB
  • sloc: makefile: 2
file content (34 lines) | stat: -rw-r--r-- 633 bytes parent folder | download | duplicates (8)
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
package gls

// though this could probably be better at keeping ids smaller, the goal of
// this class is to keep a registry of the smallest unique integer ids
// per-process possible

import (
	"sync"
)

type idPool struct {
	mtx      sync.Mutex
	released []uint
	max_id   uint
}

func (p *idPool) Acquire() (id uint) {
	p.mtx.Lock()
	defer p.mtx.Unlock()
	if len(p.released) > 0 {
		id = p.released[len(p.released)-1]
		p.released = p.released[:len(p.released)-1]
		return id
	}
	id = p.max_id
	p.max_id++
	return id
}

func (p *idPool) Release(id uint) {
	p.mtx.Lock()
	defer p.mtx.Unlock()
	p.released = append(p.released, id)
}