1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-01 19:45:24 +00:00
v2fly/common/alloc/buffer_pool.go

61 lines
1.1 KiB
Go
Raw Normal View History

2016-04-12 14:52:57 +00:00
package alloc
import (
"sync"
)
2016-07-28 14:24:15 +00:00
type Pool interface {
Allocate() *Buffer
Free(*Buffer)
}
2016-04-12 14:52:57 +00:00
type BufferPool struct {
chain chan []byte
allocator *sync.Pool
}
func NewBufferPool(bufferSize, poolSize int) *BufferPool {
pool := &BufferPool{
chain: make(chan []byte, poolSize),
allocator: &sync.Pool{
New: func() interface{} { return make([]byte, bufferSize) },
},
}
2016-07-15 13:17:06 +00:00
for i := 0; i < poolSize; i++ {
2016-04-12 14:52:57 +00: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 12:24:20 +00:00
return CreateBuffer(b, p)
2016-04-12 14:52:57 +00: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 17:54:20 +00:00
const (
SmallBufferSize = 1600 - defaultOffset
2016-05-11 17:54:20 +00:00
BufferSize = 8*1024 - defaultOffset
LargeBufferSize = 64*1024 - defaultOffset
)
2016-08-01 15:47:31 +00:00
var smallPool = NewBufferPool(1600, 256)
var mediumPool = NewBufferPool(8*1024, 1024)
2016-07-15 13:16:35 +00:00
var largePool = NewBufferPool(64*1024, 32)