go-zero/core/iox/bufferpool.go
Kevin Wan ae87114282
chore: change interface{} to any (#2818)
* chore: change interface{} to any

* chore: update goctl version to 1.5.0

* chore: update goctl deps
2023-01-24 16:32:02 +08:00

39 lines
676 B
Go

package iox
import (
"bytes"
"sync"
)
// A BufferPool is a pool to buffer bytes.Buffer objects.
type BufferPool struct {
capability int
pool *sync.Pool
}
// NewBufferPool returns a BufferPool.
func NewBufferPool(capability int) *BufferPool {
return &BufferPool{
capability: capability,
pool: &sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
},
}
}
// Get returns a bytes.Buffer object from bp.
func (bp *BufferPool) Get() *bytes.Buffer {
buf := bp.pool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
// Put returns buf into bp.
func (bp *BufferPool) Put(buf *bytes.Buffer) {
if buf.Cap() < bp.capability {
bp.pool.Put(buf)
}
}