buffer_pool.go 1016 B

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