buffer_pool.go 795 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package buf
  2. import (
  3. "sync"
  4. )
  5. // Pool provides functionality to generate and recycle buffers on demand.
  6. type Pool struct {
  7. allocator *sync.Pool
  8. }
  9. // NewPool creates a SyncPool with given buffer size.
  10. func NewPool(bufferSize uint32) *Pool {
  11. pool := &Pool{
  12. allocator: &sync.Pool{
  13. New: func() interface{} { return make([]byte, bufferSize) },
  14. },
  15. }
  16. return pool
  17. }
  18. // Allocate either returns a unused buffer from the pool, or generates a new one from system.
  19. func (p *Pool) Allocate() *Buffer {
  20. return &Buffer{
  21. v: p.allocator.Get().([]byte),
  22. pool: p,
  23. }
  24. }
  25. // // Free recycles the given buffer.
  26. func (p *Pool) Free(buffer *Buffer) {
  27. if buffer.v != nil {
  28. p.allocator.Put(buffer.v)
  29. }
  30. }
  31. const (
  32. // Size of a regular buffer.
  33. Size = 2 * 1024
  34. )
  35. var mediumPool = NewPool(Size)