bytepool.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package bpool
  2. // BytePool implements a leaky pool of []byte in the form of a bounded
  3. // channel.
  4. type BytePool struct {
  5. c chan []byte
  6. w int
  7. h int
  8. }
  9. // NewBytePool creates a new BytePool bounded to the given maxSize, with new
  10. // byte arrays sized based on width.
  11. func NewBytePool(maxSize int, width int) (bp *BytePool) {
  12. return &BytePool{
  13. c: make(chan []byte, maxSize),
  14. w: width,
  15. }
  16. }
  17. // Get gets a []byte from the BytePool, or creates a new one if none are
  18. // available in the pool.
  19. func (bp *BytePool) Get() (b []byte) {
  20. select {
  21. case b = <-bp.c:
  22. // reuse existing buffer
  23. default:
  24. // create new buffer
  25. b = make([]byte, bp.w)
  26. }
  27. return
  28. }
  29. // Put returns the given Buffer to the BytePool.
  30. func (bp *BytePool) Put(b []byte) {
  31. if cap(b) < bp.w {
  32. // someone tried to put back a too small buffer, discard it
  33. return
  34. }
  35. select {
  36. case bp.c <- b[:bp.w]:
  37. // buffer went back into pool
  38. default:
  39. // buffer didn't go back into pool, just discard
  40. }
  41. }
  42. // NumPooled returns the number of items currently pooled.
  43. func (bp *BytePool) NumPooled() int {
  44. return len(bp.c)
  45. }
  46. // Width returns the width of the byte arrays in this pool.
  47. func (bp *BytePool) Width() (n int) {
  48. return bp.w
  49. }