go-zero/core/iox/bufferpool.go

43 lines
706 B
Go
Raw Permalink Normal View History

2020-07-26 17:09:05 +08:00
package iox
import (
"bytes"
"sync"
)
2021-02-19 18:40:26 +08:00
// A BufferPool is a pool to buffer bytes.Buffer objects.
2020-07-26 17:09:05 +08:00
type BufferPool struct {
capability int
pool *sync.Pool
}
2021-02-19 18:40:26 +08:00
// NewBufferPool returns a BufferPool.
2020-07-26 17:09:05 +08:00
func NewBufferPool(capability int) *BufferPool {
return &BufferPool{
capability: capability,
pool: &sync.Pool{
New: func() any {
2020-07-26 17:09:05 +08:00
return new(bytes.Buffer)
},
},
}
}
2021-02-19 18:40:26 +08:00
// Get returns a bytes.Buffer object from bp.
2020-07-26 17:09:05 +08:00
func (bp *BufferPool) Get() *bytes.Buffer {
buf := bp.pool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
2021-02-19 18:40:26 +08:00
// Put returns buf into bp.
2020-07-26 17:09:05 +08:00
func (bp *BufferPool) Put(buf *bytes.Buffer) {
if buf == nil {
return
}
2020-07-26 17:09:05 +08:00
if buf.Cap() < bp.capability {
bp.pool.Put(buf)
}
}