You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/buf/buffer_pool.go

126 lines
2.5 KiB

package buf
import (
"os"
"strconv"
"sync"
)
8 years ago
// Pool provides functionality to generate and recycle buffers on demand.
type Pool interface {
8 years ago
// Allocate either returns a unused buffer from the pool, or generates a new one from system.
Allocate() *Buffer
8 years ago
// Free recycles the given buffer.
Free(*Buffer)
}
8 years ago
// SyncPool is a buffer pool based on sync.Pool
8 years ago
type SyncPool struct {
allocator *sync.Pool
}
8 years ago
// NewSyncPool creates a SyncPool with given buffer size.
8 years ago
func NewSyncPool(bufferSize uint32) *SyncPool {
pool := &SyncPool{
allocator: &sync.Pool{
New: func() interface{} { return make([]byte, bufferSize) },
},
}
return pool
}
8 years ago
// Allocate implements Pool.Allocate().
8 years ago
func (p *SyncPool) Allocate() *Buffer {
8 years ago
return &Buffer{
v: p.allocator.Get().([]byte),
pool: p,
}
8 years ago
}
8 years ago
// Free implements Pool.Free().
8 years ago
func (p *SyncPool) Free(buffer *Buffer) {
8 years ago
rawBuffer := buffer.v
8 years ago
if rawBuffer == nil {
return
}
p.allocator.Put(rawBuffer)
}
8 years ago
// BufferPool is a Pool that utilizes an internal cache.
type BufferPool struct {
chain chan []byte
allocator *sync.Pool
}
8 years ago
// 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) },
},
}
for i := uint32(0); i < poolSize; i++ {
pool.chain <- make([]byte, bufferSize)
}
return pool
}
8 years ago
// Allocate implements Pool.Allocate().
func (p *BufferPool) Allocate() *Buffer {
var b []byte
select {
case b = <-p.chain:
default:
b = p.allocator.Get().([]byte)
}
8 years ago
return &Buffer{
v: b,
pool: p,
}
}
8 years ago
// Free implements Pool.Free().
func (p *BufferPool) Free(buffer *Buffer) {
8 years ago
rawBuffer := buffer.v
if rawBuffer == nil {
return
}
select {
case p.chain <- rawBuffer:
default:
p.allocator.Put(rawBuffer)
}
}
const (
8 years ago
// Size of a regular buffer.
Size = 8 * 1024
// SizeSmall is the size of a small buffer.
8 years ago
SizeSmall = 2 * 1024
poolSizeEnvKey = "v2ray.buffer.size"
)
var (
mediumPool Pool
8 years ago
smallPool = NewSyncPool(SizeSmall)
)
func init() {
var size uint32 = 20
sizeStr := os.Getenv(poolSizeEnvKey)
if len(sizeStr) > 0 {
customSize, err := strconv.ParseUint(sizeStr, 10, 32)
if err == nil {
size = uint32(customSize)
}
}
if size > 0 {
totalByteSize := size * 1024 * 1024
8 years ago
mediumPool = NewBufferPool(Size, totalByteSize/Size)
} else {
8 years ago
mediumPool = NewSyncPool(Size)
}
}