bufferpool.go 761 B

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