buffer.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package bytes
  2. import (
  3. "sync"
  4. )
  5. // Buffer buffer.
  6. type Buffer struct {
  7. buf []byte
  8. next *Buffer // next free buffer
  9. }
  10. // Bytes bytes.
  11. func (b *Buffer) Bytes() []byte {
  12. return b.buf
  13. }
  14. // Pool is a buffer pool.
  15. type Pool struct {
  16. lock sync.Mutex
  17. free *Buffer
  18. max int
  19. num int
  20. size int
  21. }
  22. // NewPool new a memory buffer pool struct.
  23. func NewPool(num, size int) (p *Pool) {
  24. p = new(Pool)
  25. p.init(num, size)
  26. return
  27. }
  28. // Init init the memory buffer.
  29. func (p *Pool) Init(num, size int) {
  30. p.init(num, size)
  31. }
  32. // init init the memory buffer.
  33. func (p *Pool) init(num, size int) {
  34. p.num = num
  35. p.size = size
  36. p.max = num * size
  37. p.grow()
  38. }
  39. // grow grow the memory buffer size, and update free pointer.
  40. func (p *Pool) grow() {
  41. var (
  42. i int
  43. b *Buffer
  44. bs []Buffer
  45. buf []byte
  46. )
  47. buf = make([]byte, p.max)
  48. bs = make([]Buffer, p.num)
  49. p.free = &bs[0]
  50. b = p.free
  51. for i = 1; i < p.num; i++ {
  52. b.buf = buf[(i-1)*p.size : i*p.size]
  53. b.next = &bs[i]
  54. b = b.next
  55. }
  56. b.buf = buf[(i-1)*p.size : i*p.size]
  57. b.next = nil
  58. }
  59. // Get get a free memory buffer.
  60. func (p *Pool) Get() (b *Buffer) {
  61. p.lock.Lock()
  62. if b = p.free; b == nil {
  63. p.grow()
  64. b = p.free
  65. }
  66. p.free = b.next
  67. p.lock.Unlock()
  68. return
  69. }
  70. // Put put back a memory buffer to free.
  71. func (p *Pool) Put(b *Buffer) {
  72. p.lock.Lock()
  73. b.next = p.free
  74. p.free = b
  75. p.lock.Unlock()
  76. }