byteslice.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package bpool
  2. // WrapByteSlice wraps a []byte as a ByteSlice
  3. func WrapByteSlice(full []byte, headerLength int) ByteSlice {
  4. return ByteSlice{
  5. full: full,
  6. current: full[headerLength:],
  7. head: headerLength,
  8. end: len(full),
  9. }
  10. }
  11. // ByteSlice provides a wrapper around []byte with some added convenience
  12. type ByteSlice struct {
  13. full []byte
  14. current []byte
  15. head int
  16. end int
  17. }
  18. // ResliceTo reslices the end of the current slice.
  19. func (b ByteSlice) ResliceTo(end int) ByteSlice {
  20. return ByteSlice{
  21. full: b.full,
  22. current: b.current[:end],
  23. head: b.head,
  24. end: b.head + end,
  25. }
  26. }
  27. // Bytes returns the current slice
  28. func (b ByteSlice) Bytes() []byte {
  29. return b.current
  30. }
  31. // BytesWithHeader returns the current slice preceded by the header
  32. func (b ByteSlice) BytesWithHeader() []byte {
  33. return b.full[:b.end]
  34. }
  35. // Full returns the full original buffer underlying the ByteSlice
  36. func (b ByteSlice) Full() []byte {
  37. return b.full
  38. }
  39. // ByteSlicePool is a bool of byte slices
  40. type ByteSlicePool interface {
  41. // Get gets a byte slice from the pool
  42. GetSlice() ByteSlice
  43. // Put returns a byte slice to the pool
  44. PutSlice(ByteSlice)
  45. // NumPooled returns the number of currently pooled items
  46. NumPooled() int
  47. }
  48. // NewByteSlicePool creates a new ByteSlicePool bounded to the
  49. // given maxSize, with new byte arrays sized based on width
  50. func NewByteSlicePool(maxSize int, width int) ByteSlicePool {
  51. return NewHeaderPreservingByteSlicePool(maxSize, width, 0)
  52. }
  53. // NewHeaderPreservingByteSlicePool creates a new ByteSlicePool bounded to the
  54. // given maxSize, with new byte arrays sized based on width and headerLength
  55. // preserved at the beginning of the slice.
  56. func NewHeaderPreservingByteSlicePool(maxSize int, width int, headerLength int) ByteSlicePool {
  57. return &BytePool{
  58. c: make(chan []byte, maxSize),
  59. w: width + headerLength,
  60. h: headerLength,
  61. }
  62. }
  63. // GetSlice implements the method from interface ByteSlicePool
  64. func (bp *BytePool) GetSlice() ByteSlice {
  65. return WrapByteSlice(bp.Get(), bp.h)
  66. }
  67. // PutSlice implements the method from interface ByteSlicePool
  68. func (bp *BytePool) PutSlice(b ByteSlice) {
  69. bp.Put(b.Full())
  70. }