bufferpool.go 827 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package bpool
  2. import (
  3. "bytes"
  4. )
  5. // BufferPool implements a pool of bytes.Buffers in the form of a bounded
  6. // channel.
  7. type BufferPool struct {
  8. c chan *bytes.Buffer
  9. }
  10. // NewBufferPool creates a new BufferPool bounded to the given size.
  11. func NewBufferPool(size int) (bp *BufferPool) {
  12. return &BufferPool{
  13. c: make(chan *bytes.Buffer, size),
  14. }
  15. }
  16. // Get gets a Buffer from the BufferPool, or creates a new one if none are
  17. // available in the pool.
  18. func (bp *BufferPool) Get() (b *bytes.Buffer) {
  19. select {
  20. case b = <-bp.c:
  21. // reuse existing buffer
  22. default:
  23. // create new buffer
  24. b = bytes.NewBuffer([]byte{})
  25. }
  26. return
  27. }
  28. // Put returns the given Buffer to the BufferPool.
  29. func (bp *BufferPool) Put(b *bytes.Buffer) {
  30. b.Reset()
  31. select {
  32. case bp.c <- b:
  33. default: // Discard the buffer if the pool is full.
  34. }
  35. }