2024-04-14 00:16:55 +03:00
|
|
|
package pool
|
|
|
|
|
2024-09-04 22:41:05 +03:00
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"sync"
|
|
|
|
)
|
2024-04-14 00:16:55 +03:00
|
|
|
|
|
|
|
type Pool[T any] struct {
|
|
|
|
p *sync.Pool
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPool[T any](fn func() T) Pool[T] {
|
|
|
|
return Pool[T]{
|
|
|
|
p: &sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
return fn()
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p Pool[T]) Get() T {
|
|
|
|
return p.p.Get().(T)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p Pool[T]) Put(t T) {
|
|
|
|
p.p.Put(t)
|
|
|
|
}
|
2024-09-04 22:41:05 +03:00
|
|
|
|
|
|
|
func NewBytePool(size int) Pool[T] {
|
|
|
|
return NewPool(func() []byte { return make([]byte, size) })
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewBytesPool() Pool[T] {
|
|
|
|
return NewPool(func() *bytes.Buffer { return bytes.NewBuffer(nil) })
|
|
|
|
}
|