-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfactory_pointer.go
71 lines (53 loc) · 1.22 KB
/
factory_pointer.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
65
66
67
68
69
70
71
package parco
import "sync"
type (
Factory[T any] interface {
Get() T
}
PoolFactory[T any] interface {
Factory[T]
Put(T)
}
FuncFactory[T any] func() T
nativePooledFactoryOption[T any] interface {
Configure(f *NativePooledFactory[T])
}
nativePooledFactoryOptionFunc[T any] func(factory *NativePooledFactory[T])
)
func (f nativePooledFactoryOptionFunc[T]) Configure(factory *NativePooledFactory[T]) {
f(factory)
}
func (f FuncFactory[T]) Get() T {
return f()
}
func ObjectFactory[T any]() Factory[T] {
return FuncFactory[T](func() (t T) {
return
})
}
type NativePooledFactory[T any] struct {
inner sync.Pool
resetFunc func(*T)
}
func (f NativePooledFactory[T]) Get() T {
return f.inner.Get().(T)
}
func (f NativePooledFactory[T]) Put(t T) {
f.inner.Put(t)
}
func PooledFactory[T any](inner Factory[T], options ...nativePooledFactoryOption[T]) PoolFactory[T] {
f := NativePooledFactory[T]{
inner: sync.Pool{New: func() any {
return inner.Get()
}},
}
for _, opt := range options {
opt.Configure(&f)
}
return f
}
func WithResetFunc[T any](fn func(*T)) nativePooledFactoryOption[T] {
return nativePooledFactoryOptionFunc[T](func(factory *NativePooledFactory[T]) {
factory.resetFunc = fn
})
}