-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipool.go
59 lines (51 loc) · 1.09 KB
/
ipool.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
package dyntpl
// Pool represents internal pool.
// In addition to native sync.Pool requires Reset() method.
type Pool interface {
Get() any
Put(any)
// Reset cleanups data before putting to the pool.
Reset(any)
}
type ipools struct {
index map[string]int
buf []Pool
}
type ipoolVar struct {
key string
val any
}
var ipoolRegistry ipools
func (p *ipools) init() {
if p.index == nil {
p.index = make(map[string]int)
}
}
func (p *ipools) acquire(key string) (any, error) {
ipoolRegistry.init()
i, ok := p.index[key]
if !ok {
return nil, ErrUnknownPool
}
return p.buf[i].Get(), nil
}
func (p *ipools) release(key string, x any) error {
ipoolRegistry.init()
i, ok := p.index[key]
if !ok {
return ErrUnknownPool
}
p.buf[i].Reset(x)
p.buf[i].Put(x)
return nil
}
// RegisterPool adds new internal pool to the registry by given key.
func RegisterPool(key string, pool Pool) error {
ipoolRegistry.init()
if _, ok := ipoolRegistry.index[key]; ok {
return nil
}
ipoolRegistry.buf = append(ipoolRegistry.buf, pool)
ipoolRegistry.index[key] = len(ipoolRegistry.buf) - 1
return nil
}