bufpool.go 850 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. if p.size == 0 {
  25. buf = new(bytes.Buffer)
  26. } else {
  27. buf = bytes.NewBuffer(make([]byte, p.size, p.size))
  28. }
  29. p.top = &bufPoolEntry{buf: buf, next: p.top}
  30. }
  31. func (p *bufPool) get() *bytes.Buffer {
  32. p.mutex.Lock()
  33. defer p.mutex.Unlock()
  34. if p.top == nil {
  35. p.grow()
  36. }
  37. buf := p.top.buf
  38. buf.Reset()
  39. p.top = p.top.next
  40. return buf
  41. }
  42. func (p *bufPool) put(buf *bytes.Buffer) {
  43. p.mutex.Lock()
  44. defer p.mutex.Unlock()
  45. p.top = &bufPoolEntry{buf: buf, next: p.top}
  46. }