bytes.go (866B)
1 package pools 2 3 import ( 4 "sync" 5 6 "codeberg.org/gruf/go-byteutil" 7 ) 8 9 // BufferPool is a pooled allocator for bytes.Buffer objects 10 type BufferPool interface { 11 // Get fetches a bytes.Buffer from pool 12 Get() *byteutil.Buffer 13 14 // Put places supplied bytes.Buffer in pool 15 Put(*byteutil.Buffer) 16 } 17 18 // NewBufferPool returns a newly instantiated bytes.Buffer pool 19 func NewBufferPool(size int) BufferPool { 20 return &bufferPool{ 21 pool: sync.Pool{ 22 New: func() interface{} { 23 return &byteutil.Buffer{B: make([]byte, 0, size)} 24 }, 25 }, 26 size: size, 27 } 28 } 29 30 // bufferPool is our implementation of BufferPool 31 type bufferPool struct { 32 pool sync.Pool 33 size int 34 } 35 36 func (p *bufferPool) Get() *byteutil.Buffer { 37 return p.pool.Get().(*byteutil.Buffer) 38 } 39 40 func (p *bufferPool) Put(buf *byteutil.Buffer) { 41 if buf.Cap() < p.size { 42 return 43 } 44 buf.Reset() 45 p.pool.Put(buf) 46 }