mirror of https://github.com/v2ray/v2ray-core
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.
57 lines
1.2 KiB
57 lines
1.2 KiB
6 years ago
|
package bytespool
|
||
9 years ago
|
|
||
6 years ago
|
import "sync"
|
||
8 years ago
|
|
||
7 years ago
|
func createAllocFunc(size int32) func() interface{} {
|
||
7 years ago
|
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.
|
||
7 years ago
|
const (
|
||
6 years ago
|
numPools = 4
|
||
7 years ago
|
sizeMulti = 4
|
||
|
)
|
||
|
|
||
|
var (
|
||
6 years ago
|
pool [numPools]sync.Pool
|
||
|
poolSize [numPools]int32
|
||
7 years ago
|
)
|
||
8 years ago
|
|
||
7 years ago
|
func init() {
|
||
6 years ago
|
size := int32(2048)
|
||
7 years ago
|
for i := 0; i < numPools; i++ {
|
||
7 years ago
|
pool[i] = sync.Pool{
|
||
7 years ago
|
New: createAllocFunc(size),
|
||
|
}
|
||
|
poolSize[i] = size
|
||
|
size *= sizeMulti
|
||
|
}
|
||
8 years ago
|
}
|
||
|
|
||
6 years ago
|
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
|
||
|
func Alloc(size int32) []byte {
|
||
7 years ago
|
for idx, ps := range poolSize {
|
||
|
if size <= ps {
|
||
|
return pool[idx].Get().([]byte)
|
||
|
}
|
||
|
}
|
||
|
return make([]byte, size)
|
||
7 years ago
|
}
|
||
9 years ago
|
|
||
6 years ago
|
// Free puts a byte slice into the internal pool.
|
||
|
func Free(b []byte) {
|
||
7 years ago
|
size := int32(cap(b))
|
||
7 years ago
|
b = b[0:cap(b)]
|
||
7 years ago
|
for i := numPools - 1; i >= 0; i-- {
|
||
7 years ago
|
if size >= poolSize[i] {
|
||
7 years ago
|
pool[i].Put(b) // nolint: megacheck
|
||
7 years ago
|
return
|
||
7 years ago
|
}
|
||
|
}
|
||
7 years ago
|
}
|