pool.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // +build !pool_sanitize
  2. package pbytes
  3. import "github.com/gobwas/pool"
  4. // Pool contains logic of reusing byte slices of various size.
  5. type Pool struct {
  6. pool *pool.Pool
  7. }
  8. // New creates new Pool that reuses slices which size is in logarithmic range
  9. // [min, max].
  10. //
  11. // Note that it is a shortcut for Custom() constructor with Options provided by
  12. // pool.WithLogSizeMapping() and pool.WithLogSizeRange(min, max) calls.
  13. func New(min, max int) *Pool {
  14. return &Pool{pool.New(min, max)}
  15. }
  16. // New creates new Pool with given options.
  17. func Custom(opts ...pool.Option) *Pool {
  18. return &Pool{pool.Custom(opts...)}
  19. }
  20. // Get returns probably reused slice of bytes with at least capacity of c and
  21. // exactly len of n.
  22. func (p *Pool) Get(n, c int) []byte {
  23. if n > c {
  24. panic("requested length is greater than capacity")
  25. }
  26. v, x := p.pool.Get(c)
  27. if v != nil {
  28. bts := v.([]byte)
  29. bts = bts[:n]
  30. return bts
  31. }
  32. return make([]byte, n, x)
  33. }
  34. // Put returns given slice to reuse pool.
  35. // It does not reuse bytes whose size is not power of two or is out of pool
  36. // min/max range.
  37. func (p *Pool) Put(bts []byte) {
  38. p.pool.Put(bts, cap(bts))
  39. }
  40. // GetCap returns probably reused slice of bytes with at least capacity of n.
  41. func (p *Pool) GetCap(c int) []byte {
  42. return p.Get(0, c)
  43. }
  44. // GetLen returns probably reused slice of bytes with at least capacity of n
  45. // and exactly len of n.
  46. func (p *Pool) GetLen(n int) []byte {
  47. return p.Get(n, n)
  48. }