bufferpool.go 947 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. }
  36. // NumPooled returns the number of items currently pooled.
  37. func (bp *BufferPool) NumPooled() int {
  38. return len(bp.c)
  39. }