bufferpool.go 513 B

12345678910111213141516171819202122232425262728293031323334
  1. package iox
  2. import (
  3. "bytes"
  4. "sync"
  5. )
  6. type BufferPool struct {
  7. capability int
  8. pool *sync.Pool
  9. }
  10. func NewBufferPool(capability int) *BufferPool {
  11. return &BufferPool{
  12. capability: capability,
  13. pool: &sync.Pool{
  14. New: func() interface{} {
  15. return new(bytes.Buffer)
  16. },
  17. },
  18. }
  19. }
  20. func (bp *BufferPool) Get() *bytes.Buffer {
  21. buf := bp.pool.Get().(*bytes.Buffer)
  22. buf.Reset()
  23. return buf
  24. }
  25. func (bp *BufferPool) Put(buf *bytes.Buffer) {
  26. if buf.Cap() < bp.capability {
  27. bp.pool.Put(buf)
  28. }
  29. }