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/bytespool/pool.go

67 lines
1.4 KiB

package bytespool
import "sync"
8 years ago
func createAllocFunc(size int32) func() interface{} {
return func() interface{} {
return make([]byte, size)
8 years ago
}
}
7 years ago
// The following parameters controls the size of buffer pools.
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
// Package buf is guaranteed to not use buffers larger than the largest pool.
// Other packets may use larger buffers.
const (
numPools = 4
sizeMulti = 4
)
var (
pool [numPools]sync.Pool
poolSize [numPools]int32
)
8 years ago
func init() {
size := int32(2048)
for i := 0; i < numPools; i++ {
pool[i] = sync.Pool{
New: createAllocFunc(size),
}
poolSize[i] = size
size *= sizeMulti
}
8 years ago
}
6 years ago
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
// It may return nil if no such pool exists.
func GetPool(size int32) *sync.Pool {
for idx, ps := range poolSize {
if size <= ps {
6 years ago
return &pool[idx]
}
}
6 years ago
return nil
}
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
func Alloc(size int32) []byte {
pool := GetPool(size)
if pool != nil {
return pool.Get().([]byte)
}
return make([]byte, size)
}
// Free puts a byte slice into the internal pool.
func Free(b []byte) {
size := int32(cap(b))
b = b[0:cap(b)]
for i := numPools - 1; i >= 0; i-- {
7 years ago
if size >= poolSize[i] {
pool[i].Put(b) // nolint: megacheck
return
}
}
}