mirror of https://github.com/v2ray/v2ray-core
simplify code
parent
c6a68755b6
commit
a8da85eca5
|
@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue