-
Notifications
You must be signed in to change notification settings - Fork 5
/
pool.go
64 lines (51 loc) · 1.04 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package don
import (
"reflect"
"sync"
)
type pool[T any] interface {
Get() *T
Put(x *T)
}
type requestPool[T any] struct {
pool sync.Pool
reset func(*T)
}
func newRequestPool[T any](zero T) pool[T] {
typ := reflect.TypeOf(zero)
if typ == nil {
return &fakePool[T]{&zero}
}
p := &requestPool[T]{}
if typ.Kind() != reflect.Pointer {
p.pool.New = func() any {
return new(T)
}
p.reset = func(v *T) {
*v = zero
}
} else {
rtype := dataOf(typ)
elem := typ.Elem()
elemrtype := dataOf(elem)
zero := dataOf(reflect.New(elem).Elem().Interface())
p.pool.New = func() any {
v := packEface(rtype, unsafe_New(elemrtype)).(T) //nolint:forcetypeassert
return &v
}
p.reset = func(v *T) {
typedmemmove(elemrtype, dataOf(*v), zero)
}
}
return p
}
func (p *requestPool[T]) Get() *T {
return p.pool.Get().(*T) //nolint:forcetypeassert
}
func (p *requestPool[T]) Put(v *T) {
p.reset(v)
p.pool.Put(v)
}
type fakePool[T any] struct{ v *T }
func (p *fakePool[T]) Get() *T { return p.v }
func (p *fakePool[T]) Put(*T) {}