gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/pool/default-buffer-pool.go (about) 1 package pool 2 3 import "gitee.com/sy_183/go-common/option" 4 5 type DefaultBufferPool struct { 6 pool Pool[*Buffer] 7 buffer *Buffer 8 } 9 10 func NewDefaultBufferPool(size uint, reversed uint, poolProvider PoolProvider[*Buffer], poolOptions ...option.AnyOption) *DefaultBufferPool { 11 return &DefaultBufferPool{pool: poolProvider(func(p Pool[*Buffer]) *Buffer { 12 return NewBuffer(size, reversed).SetOnReleased(func(buffer *Buffer) { 13 p.Put(buffer) 14 }) 15 }, poolOptions...)} 16 } 17 18 func (p *DefaultBufferPool) getBuffer() *Buffer { 19 if p.buffer == nil { 20 buffer := p.pool.Get() 21 if buffer == nil { 22 return nil 23 } 24 p.buffer = buffer.Use() 25 } 26 return p.buffer 27 } 28 29 func (p *DefaultBufferPool) Get() []byte { 30 if buffer := p.getBuffer(); buffer != nil { 31 if buf := buffer.Get(); buf != nil { 32 return buf 33 } 34 p.buffer.Release() 35 p.buffer = nil 36 if buffer := p.getBuffer(); buffer != nil { 37 return buffer.Get() 38 } 39 } 40 return nil 41 } 42 43 func (p *DefaultBufferPool) Alloc(size uint) *Data { 44 if p.buffer == nil { 45 p.buffer = p.pool.Get().Use() 46 } 47 return p.buffer.Alloc(size) 48 }