bufPool.go 773 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package utl
  2. import (
  3. "sync"
  4. )
  5. var (
  6. DefBufPool *BufPool
  7. )
  8. func init() {
  9. DefBufPool = NewBufPool(uint32(1024 * 2))
  10. }
  11. // Pool of buffer
  12. type BufPool struct {
  13. p *sync.Pool
  14. size uint32
  15. }
  16. // Create a pool of buffers.
  17. // the size of each buffer is specified by `size`
  18. func NewBufPool(size uint32) *BufPool {
  19. return &BufPool{
  20. p: &sync.Pool{
  21. New: func() interface{} {
  22. return make([]byte, size)
  23. },
  24. },
  25. size: size,
  26. }
  27. }
  28. // Get a sized buffer from pool
  29. func (self *BufPool) Get() []byte {
  30. return self.p.Get().([]byte)
  31. }
  32. // Get default buffer size of the pool. which is passed by NewBufPool()
  33. func (self *BufPool) GetSize() uint32 {
  34. return self.size
  35. }
  36. // Return the buffer retrieve by Get()
  37. func (self *BufPool) Put(data []byte) {
  38. self.p.Put(data)
  39. }