buffer.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package alloc
  2. import (
  3. //"fmt"
  4. "time"
  5. )
  6. type Buffer struct {
  7. head []byte
  8. pool *bufferPool
  9. Value []byte
  10. }
  11. func (b *Buffer) Release() {
  12. b.pool.free(b)
  13. }
  14. func (b *Buffer) Clear() {
  15. b.Value = b.Value[:0]
  16. }
  17. func (b *Buffer) Append(data []byte) {
  18. b.Value = append(b.Value, data...)
  19. }
  20. func (b *Buffer) Slice(from, to int) {
  21. b.Value = b.Value[from:to]
  22. }
  23. func (b *Buffer) SliceFrom(from int) {
  24. b.Value = b.Value[from:]
  25. }
  26. func (b *Buffer) Len() int {
  27. return len(b.Value)
  28. }
  29. type bufferPool struct {
  30. chain chan *Buffer
  31. allocator func(*bufferPool) *Buffer
  32. minElements int
  33. maxElements int
  34. }
  35. func newBufferPool(allocator func(*bufferPool) *Buffer, minElements, maxElements int) *bufferPool {
  36. pool := &bufferPool{
  37. chain: make(chan *Buffer, maxElements*2),
  38. allocator: allocateSmall,
  39. minElements: minElements,
  40. maxElements: maxElements,
  41. }
  42. for i := 0; i < minElements; i++ {
  43. pool.chain <- allocator(pool)
  44. }
  45. go pool.cleanup(time.Tick(1 * time.Second))
  46. return pool
  47. }
  48. func (p *bufferPool) allocate() *Buffer {
  49. //fmt.Printf("Pool size: %d\n", len(p.chain))
  50. var b *Buffer
  51. select {
  52. case b = <-p.chain:
  53. default:
  54. b = p.allocator(p)
  55. }
  56. b.Value = b.head
  57. return b
  58. }
  59. func (p *bufferPool) free(buffer *Buffer) {
  60. select {
  61. case p.chain <- buffer:
  62. default:
  63. }
  64. //fmt.Printf("Pool size: %d\n", len(p.chain))
  65. }
  66. func (p *bufferPool) cleanup(tick <-chan time.Time) {
  67. for range tick {
  68. pSize := len(p.chain)
  69. for delta := pSize - p.minElements; delta > 0; delta-- {
  70. p.chain <- p.allocator(p)
  71. }
  72. for delta := p.maxElements - pSize; delta > 0; delta-- {
  73. <-p.chain
  74. }
  75. }
  76. }
  77. func allocateSmall(pool *bufferPool) *Buffer {
  78. b := &Buffer{
  79. head: make([]byte, 8*1024),
  80. }
  81. b.Value = b.head
  82. b.pool = pool
  83. return b
  84. }
  85. var smallPool = newBufferPool(allocateSmall, 256, 1024)
  86. func NewBuffer() *Buffer {
  87. return smallPool.allocate()
  88. }