You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/iox/bufferpool.go

43 lines
706 B
Go

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