simplify code

pull/298/merge
Darien Raymond 2017-05-16 16:47:07 +02:00
parent c6a68755b6
commit a8da85eca5
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
1 changed files with 14 additions and 20 deletions

View File

@ -40,26 +40,22 @@ func (p *SyncPool) Allocate() *Buffer {
// Free implements Pool.Free(). // Free implements Pool.Free().
func (p *SyncPool) Free(buffer *Buffer) { func (p *SyncPool) Free(buffer *Buffer) {
rawBuffer := buffer.v if buffer.v != nil {
if rawBuffer == nil { p.allocator.Put(buffer.v)
return
} }
p.allocator.Put(rawBuffer)
} }
// BufferPool is a Pool that utilizes an internal cache. // BufferPool is a Pool that utilizes an internal cache.
type BufferPool struct { type BufferPool struct {
chain chan []byte chain chan []byte
allocator *sync.Pool sub Pool
} }
// NewBufferPool creates a new BufferPool with given buffer size, and internal cache size. // NewBufferPool creates a new BufferPool with given buffer size, and internal cache size.
func NewBufferPool(bufferSize, poolSize uint32) *BufferPool { func NewBufferPool(bufferSize, poolSize uint32) *BufferPool {
pool := &BufferPool{ pool := &BufferPool{
chain: make(chan []byte, poolSize), chain: make(chan []byte, poolSize),
allocator: &sync.Pool{ sub: NewSyncPool(bufferSize),
New: func() interface{} { return make([]byte, bufferSize) },
},
} }
for i := uint32(0); i < poolSize; i++ { for i := uint32(0); i < poolSize; i++ {
pool.chain <- make([]byte, bufferSize) pool.chain <- make([]byte, bufferSize)
@ -69,28 +65,26 @@ func NewBufferPool(bufferSize, poolSize uint32) *BufferPool {
// Allocate implements Pool.Allocate(). // Allocate implements Pool.Allocate().
func (p *BufferPool) Allocate() *Buffer { func (p *BufferPool) Allocate() *Buffer {
var b []byte
select { select {
case b = <-p.chain: case b := <-p.chain:
return &Buffer{
v: b,
pool: p,
}
default: default:
b = p.allocator.Get().([]byte) return p.sub.Allocate()
}
return &Buffer{
v: b,
pool: p,
} }
} }
// Free implements Pool.Free(). // Free implements Pool.Free().
func (p *BufferPool) Free(buffer *Buffer) { func (p *BufferPool) Free(buffer *Buffer) {
rawBuffer := buffer.v if buffer.v == nil {
if rawBuffer == nil {
return return
} }
select { select {
case p.chain <- rawBuffer: case p.chain <- buffer.v:
default: default:
p.allocator.Put(rawBuffer) p.sub.Free(buffer)
} }
} }