pool.go 1.4 KB

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