1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-29 10:45:22 +00:00

simplify code

This commit is contained in:
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

View File

@ -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)
@ -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)
}
}