bufferpool.go 684 B

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