bufpool.go 804 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package main
  2. import (
  3. "bytes"
  4. "sync"
  5. )
  6. type bufPool struct {
  7. mutex sync.Mutex
  8. size int
  9. top *bufPoolEntry
  10. }
  11. type bufPoolEntry struct {
  12. buf *bytes.Buffer
  13. next *bufPoolEntry
  14. }
  15. func newBufPool(n int, size int) *bufPool {
  16. pool := bufPool{size: size}
  17. for i := 0; i < n; i++ {
  18. pool.grow()
  19. }
  20. return &pool
  21. }
  22. func (p *bufPool) grow() {
  23. var buf *bytes.Buffer
  24. buf = new(bytes.Buffer)
  25. if p.size > 0 {
  26. buf.Grow(p.size)
  27. }
  28. p.top = &bufPoolEntry{buf: buf, next: p.top}
  29. }
  30. func (p *bufPool) get() *bytes.Buffer {
  31. p.mutex.Lock()
  32. defer p.mutex.Unlock()
  33. if p.top == nil {
  34. p.grow()
  35. }
  36. buf := p.top.buf
  37. buf.Reset()
  38. p.top = p.top.next
  39. return buf
  40. }
  41. func (p *bufPool) put(buf *bytes.Buffer) {
  42. p.mutex.Lock()
  43. defer p.mutex.Unlock()
  44. p.top = &bufPoolEntry{buf: buf, next: p.top}
  45. }