bytepool.go 976 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. }
  8. // NewBytePool creates a new BytePool bounded to the given maxSize, with new
  9. // byte arrays sized based on width.
  10. func NewBytePool(maxSize int, width int) (bp *BytePool) {
  11. return &BytePool{
  12. c: make(chan []byte, maxSize),
  13. w: width,
  14. }
  15. }
  16. // Get gets a []byte from the BytePool, or creates a new one if none are
  17. // available in the pool.
  18. func (bp *BytePool) Get() (b []byte) {
  19. select {
  20. case b = <-bp.c:
  21. // reuse existing buffer
  22. default:
  23. // create new buffer
  24. b = make([]byte, bp.w)
  25. }
  26. return
  27. }
  28. // Put returns the given Buffer to the BytePool.
  29. func (bp *BytePool) Put(b []byte) {
  30. select {
  31. case bp.c <- b:
  32. // buffer went back into pool
  33. default:
  34. // buffer didn't go back into pool, just discard
  35. }
  36. }
  37. // Width returns the width of the byte arrays in this pool.
  38. func (bp *BytePool) Width() (n int) {
  39. return bp.w
  40. }