github.com/lingyao2333/mo-zero@v1.4.1/core/iox/bufferpool.go (about)

     1  package iox
     2  
     3  import (
     4  	"bytes"
     5  	"sync"
     6  )
     7  
     8  // A BufferPool is a pool to buffer bytes.Buffer objects.
     9  type BufferPool struct {
    10  	capability int
    11  	pool       *sync.Pool
    12  }
    13  
    14  // NewBufferPool returns a BufferPool.
    15  func NewBufferPool(capability int) *BufferPool {
    16  	return &BufferPool{
    17  		capability: capability,
    18  		pool: &sync.Pool{
    19  			New: func() interface{} {
    20  				return new(bytes.Buffer)
    21  			},
    22  		},
    23  	}
    24  }
    25  
    26  // Get returns a bytes.Buffer object from bp.
    27  func (bp *BufferPool) Get() *bytes.Buffer {
    28  	buf := bp.pool.Get().(*bytes.Buffer)
    29  	buf.Reset()
    30  	return buf
    31  }
    32  
    33  // Put returns buf into bp.
    34  func (bp *BufferPool) Put(buf *bytes.Buffer) {
    35  	if buf.Cap() < bp.capability {
    36  		bp.pool.Put(buf)
    37  	}
    38  }