2016-04-12 10:52:57 -04:00
|
|
|
package alloc
|
|
|
|
|
|
|
|
import (
|
2016-08-25 05:21:32 -04:00
|
|
|
"os"
|
|
|
|
"strconv"
|
2016-04-12 10:52:57 -04:00
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2016-07-28 10:24:15 -04:00
|
|
|
type Pool interface {
|
|
|
|
Allocate() *Buffer
|
|
|
|
Free(*Buffer)
|
|
|
|
}
|
|
|
|
|
2016-04-12 10:52:57 -04:00
|
|
|
type BufferPool struct {
|
|
|
|
chain chan []byte
|
|
|
|
allocator *sync.Pool
|
|
|
|
}
|
|
|
|
|
2016-08-25 05:21:32 -04:00
|
|
|
func NewBufferPool(bufferSize, poolSize uint32) *BufferPool {
|
2016-04-12 10:52:57 -04:00
|
|
|
pool := &BufferPool{
|
|
|
|
chain: make(chan []byte, poolSize),
|
|
|
|
allocator: &sync.Pool{
|
|
|
|
New: func() interface{} { return make([]byte, bufferSize) },
|
|
|
|
},
|
|
|
|
}
|
2016-08-25 05:21:32 -04:00
|
|
|
for i := uint32(0); i < poolSize; i++ {
|
2016-04-12 10:52:57 -04:00
|
|
|
pool.chain <- make([]byte, bufferSize)
|
|
|
|
}
|
|
|
|
return pool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *BufferPool) Allocate() *Buffer {
|
|
|
|
var b []byte
|
|
|
|
select {
|
|
|
|
case b = <-p.chain:
|
|
|
|
default:
|
|
|
|
b = p.allocator.Get().([]byte)
|
|
|
|
}
|
2016-07-15 08:24:20 -04:00
|
|
|
return CreateBuffer(b, p)
|
2016-04-12 10:52:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *BufferPool) Free(buffer *Buffer) {
|
|
|
|
rawBuffer := buffer.head
|
|
|
|
if rawBuffer == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case p.chain <- rawBuffer:
|
|
|
|
default:
|
|
|
|
p.allocator.Put(rawBuffer)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-11 13:54:20 -04:00
|
|
|
const (
|
2016-06-18 11:14:30 -04:00
|
|
|
SmallBufferSize = 1600 - defaultOffset
|
2016-08-25 05:21:32 -04:00
|
|
|
|
|
|
|
mediumBufferByteSize = 8 * 1024
|
|
|
|
BufferSize = mediumBufferByteSize - defaultOffset
|
|
|
|
|
|
|
|
largeBufferByteSize = 64 * 1024
|
|
|
|
LargeBufferSize = largeBufferByteSize - defaultOffset
|
|
|
|
|
|
|
|
PoolSizeEnvKey = "v2ray.buffer.size"
|
2016-05-11 13:54:20 -04:00
|
|
|
)
|
|
|
|
|
2016-08-25 05:21:32 -04:00
|
|
|
var (
|
|
|
|
smallPool = NewBufferPool(1600, 256)
|
|
|
|
mediumPool *BufferPool
|
|
|
|
largePool *BufferPool
|
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
totalByteSize := size * 1024 * 1024
|
|
|
|
mediumPool = NewBufferPool(mediumBufferByteSize, totalByteSize/4*3/mediumBufferByteSize)
|
|
|
|
largePool = NewBufferPool(largeBufferByteSize, totalByteSize/4/largeBufferByteSize)
|
|
|
|
}
|