Skip to content

Commit

Permalink
simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
DarienRaymond committed May 16, 2017
1 parent c6a6875 commit a8da85e
Showing 1 changed file with 14 additions and 20 deletions.
34 changes: 14 additions & 20 deletions common/buf/buffer_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,22 @@ func (p *SyncPool) Allocate() *Buffer {

// Free implements Pool.Free().
func (p *SyncPool) Free(buffer *Buffer) {
rawBuffer := buffer.v
if rawBuffer == nil {
return
if buffer.v != nil {
p.allocator.Put(buffer.v)
}
p.allocator.Put(rawBuffer)
}

// BufferPool is a Pool that utilizes an internal cache.
type BufferPool struct {
chain chan []byte
allocator *sync.Pool
chain chan []byte
sub Pool
}

// NewBufferPool creates a new BufferPool with given buffer size, and internal cache size.
func NewBufferPool(bufferSize, poolSize uint32) *BufferPool {
pool := &BufferPool{
chain: make(chan []byte, poolSize),
allocator: &sync.Pool{
New: func() interface{} { return make([]byte, bufferSize) },
},
sub: NewSyncPool(bufferSize),
}
for i := uint32(0); i < poolSize; i++ {
pool.chain <- make([]byte, bufferSize)
Expand All @@ -69,28 +65,26 @@ func NewBufferPool(bufferSize, poolSize uint32) *BufferPool {

// Allocate implements Pool.Allocate().
func (p *BufferPool) Allocate() *Buffer {
var b []byte
select {
case b = <-p.chain:
case b := <-p.chain:
return &Buffer{
v: b,
pool: p,
}
default:
b = p.allocator.Get().([]byte)
}
return &Buffer{
v: b,
pool: p,
return p.sub.Allocate()
}
}

// Free implements Pool.Free().
func (p *BufferPool) Free(buffer *Buffer) {
rawBuffer := buffer.v
if rawBuffer == nil {
if buffer.v == nil {
return
}
select {
case p.chain <- rawBuffer:
case p.chain <- buffer.v:
default:
p.allocator.Put(rawBuffer)
p.sub.Free(buffer)
}
}

Expand Down

0 comments on commit a8da85e

Please sign in to comment.