-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
35 lines (29 loc) · 606 Bytes
/
pool.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
package just
import (
"sync"
)
type Pool[T any] struct {
pool sync.Pool
reset func(T)
}
// NewPool returns a new pool with concrete type and resets fn.
func NewPool[T any](constructor func() T, reset func(T)) *Pool[T] {
if reset == nil {
reset = func(T) {}
}
return &Pool[T]{
pool: sync.Pool{
New: func() any { return constructor() },
},
reset: reset,
}
}
// Get return another object from the pool.
func (p *Pool[T]) Get() T {
return p.pool.Get().(T)
}
// Put will reset the object and put this object to the pool.
func (p *Pool[T]) Put(obj T) {
p.reset(obj)
p.pool.Put(obj)
}