1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-01 03:25:23 +00:00
v2fly/common/buf/buffer_pool.go

57 lines
805 B
Go
Raw Normal View History

2016-12-09 10:35:27 +00:00
package buf
2016-04-12 14:52:57 +00:00
import (
"sync"
)
2018-03-11 22:06:04 +00:00
const (
// Size of a regular buffer.
Size = 2 * 1024
)
2016-11-21 21:08:34 +00:00
2018-03-11 22:06:04 +00:00
func createAllocFunc(size uint32) func() interface{} {
return func() interface{} {
return make([]byte, size)
2016-11-21 21:08:34 +00:00
}
}
2018-03-12 15:21:39 +00:00
const (
numPools = 5
sizeMulti = 4
)
var (
pool [numPools]*sync.Pool
poolSize [numPools]uint32
)
2016-11-21 21:08:34 +00:00
2018-03-12 15:21:39 +00:00
func init() {
size := uint32(Size)
for i := 0; i < numPools; i++ {
pool[i] = &sync.Pool{
New: createAllocFunc(size),
}
poolSize[i] = size
size *= sizeMulti
}
2016-11-21 21:08:34 +00:00
}
2018-03-12 15:21:39 +00:00
func newBytes(size uint32) []byte {
for idx, ps := range poolSize {
if size <= ps {
return pool[idx].Get().([]byte)
}
}
return make([]byte, size)
2018-03-11 22:06:04 +00:00
}
2016-05-11 17:54:20 +00:00
2018-03-12 15:21:39 +00:00
func freeBytes(b []byte) {
size := uint32(cap(b))
for i := numPools - 1; i >= 0; i-- {
ps := poolSize[i]
if size >= ps {
pool[i].Put(b)
}
}
2018-03-11 22:06:04 +00:00
}