2021-11-13 14:29:08 +03:00
|
|
|
package pools
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2022-05-08 20:49:45 +03:00
|
|
|
"codeberg.org/gruf/go-byteutil"
|
2021-11-13 14:29:08 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// BufferPool is a pooled allocator for bytes.Buffer objects
|
|
|
|
type BufferPool interface {
|
|
|
|
// Get fetches a bytes.Buffer from pool
|
2022-05-08 20:49:45 +03:00
|
|
|
Get() *byteutil.Buffer
|
2021-11-13 14:29:08 +03:00
|
|
|
|
|
|
|
// Put places supplied bytes.Buffer in pool
|
2022-05-08 20:49:45 +03:00
|
|
|
Put(*byteutil.Buffer)
|
2021-11-13 14:29:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewBufferPool returns a newly instantiated bytes.Buffer pool
|
|
|
|
func NewBufferPool(size int) BufferPool {
|
|
|
|
return &bufferPool{
|
|
|
|
pool: sync.Pool{
|
|
|
|
New: func() interface{} {
|
2022-05-08 20:49:45 +03:00
|
|
|
return &byteutil.Buffer{B: make([]byte, 0, size)}
|
2021-11-13 14:29:08 +03:00
|
|
|
},
|
|
|
|
},
|
|
|
|
size: size,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// bufferPool is our implementation of BufferPool
|
|
|
|
type bufferPool struct {
|
|
|
|
pool sync.Pool
|
|
|
|
size int
|
|
|
|
}
|
|
|
|
|
2022-05-08 20:49:45 +03:00
|
|
|
func (p *bufferPool) Get() *byteutil.Buffer {
|
|
|
|
return p.pool.Get().(*byteutil.Buffer)
|
2021-11-13 14:29:08 +03:00
|
|
|
}
|
|
|
|
|
2022-05-08 20:49:45 +03:00
|
|
|
func (p *bufferPool) Put(buf *byteutil.Buffer) {
|
2021-11-13 14:29:08 +03:00
|
|
|
if buf.Cap() < p.size {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
buf.Reset()
|
|
|
|
p.pool.Put(buf)
|
|
|
|
}
|