-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
50 lines (43 loc) · 772 Bytes
/
pool.go
File metadata and controls
50 lines (43 loc) · 772 Bytes
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
// pool.go provides a type-safe, generic wrapper around sync.Pool with support for object resetting and finalizers.
package xsync
import (
"runtime"
"sync"
)
type Pool[T any] struct {
sync.Pool
ResetFunc func(*T)
}
func NewPool[T any](
allocFunc func() *T,
resetFunc func(*T),
freeFunc func(*T),
) *Pool[T] {
return &Pool[T]{
Pool: sync.Pool{
New: func() any {
if allocFunc == nil {
var v T
return &v
}
v := allocFunc()
if freeFunc != nil {
runtime.SetFinalizer(v, func(v *T) {
freeFunc(v)
})
}
return v
},
},
ResetFunc: resetFunc,
}
}
func (p *Pool[T]) Get() *T {
return p.Pool.Get().(*T)
}
func (p *Pool[T]) Put(item *T) {
if p.ResetFunc != nil {
p.ResetFunc(item)
}
p.Pool.Put(item)
}