github.com/xgzlucario/GigaCache@v0.0.0-20240508025442-54204e9c8a6b/buffer_pool.go (about)

     1  package cache
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  )
     7  
     8  // BufferPool is a bytes buffer pool.
     9  type BufferPool struct {
    10  	pool      *sync.Pool
    11  	miss, hit atomic.Uint64
    12  }
    13  
    14  // Get returns buffer with length of want.
    15  func (p *BufferPool) Get(want int) []byte {
    16  	buf := p.pool.Get().(*[]byte)
    17  
    18  	if cap(*buf) < want {
    19  		*buf = make([]byte, want)
    20  		p.miss.Add(1)
    21  
    22  	} else {
    23  		*buf = (*buf)[:want]
    24  		p.hit.Add(1)
    25  	}
    26  
    27  	return *buf
    28  }
    29  
    30  // Put adds given buffer to the pool.
    31  func (p *BufferPool) Put(b []byte) {
    32  	p.pool.Put(&b)
    33  }
    34  
    35  // NewBufferPool creates a new buffer pool instance.
    36  func NewBufferPool() *BufferPool {
    37  	return &BufferPool{
    38  		pool: &sync.Pool{
    39  			New: func() interface{} { return new([]byte) },
    40  		},
    41  	}
    42  }