pool.go 619 B

1234567891011121314151617181920212223242526272829303132
  1. package pool
  2. import "sync"
  3. type BufferPool struct {
  4. pool sync.Pool
  5. poolSize int
  6. }
  7. func NewBufferPool(poolSize int) *BufferPool {
  8. bp := &BufferPool{}
  9. bp.pool = sync.Pool{
  10. New: func() interface{} {
  11. return make([]byte, poolSize, poolSize)
  12. },
  13. }
  14. bp.poolSize = poolSize
  15. return bp
  16. }
  17. func (bp *BufferPool) Get() []byte {
  18. buf := bp.pool.Get().([]byte)
  19. return buf[:bp.poolSize] // just like make a new slice, but data may not be 0
  20. }
  21. func (bp *BufferPool) Put(x []byte) {
  22. if len(x) == bp.poolSize {
  23. bp.pool.Put(x)
  24. } else {
  25. x = nil // buf is not full, not allowed, New method returns a full buf
  26. }
  27. }