1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-02-20 23:47:21 -05:00

73 lines
1.5 KiB
Go
Raw Normal View History

2018-08-16 12:05:33 +02:00
package bytespool
2016-04-12 16:52:57 +02:00
2018-08-16 12:05:33 +02:00
import "sync"
2016-11-21 22:08:34 +01:00
2018-04-02 22:01:55 +02:00
func createAllocFunc(size int32) func() interface{} {
2018-03-11 23:06:04 +01:00
return func() interface{} {
return make([]byte, size)
2016-11-21 22:08:34 +01:00
}
}
2018-04-01 12:20:32 +02:00
// 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.
2018-03-12 16:21:39 +01:00
const (
2018-07-27 17:24:26 +02:00
numPools = 4
2018-03-12 16:21:39 +01:00
sizeMulti = 4
)
var (
2018-08-16 12:05:33 +02:00
pool [numPools]sync.Pool
poolSize [numPools]int32
2018-03-12 16:21:39 +01:00
)
2016-11-21 22:08:34 +01:00
2018-03-12 16:21:39 +01:00
func init() {
2018-08-16 12:05:33 +02:00
size := int32(2048)
2018-03-12 16:21:39 +01:00
for i := 0; i < numPools; i++ {
2018-03-16 16:22:22 +07:00
pool[i] = sync.Pool{
2018-03-12 16:21:39 +01:00
New: createAllocFunc(size),
}
poolSize[i] = size
size *= sizeMulti
}
2016-11-21 22:08:34 +01:00
}
2018-09-03 20:57:40 +02:00
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
// It may return nil if no such pool exists.
2018-12-03 23:39:21 +01:00
//
// v2ray:api:stable
2018-09-03 20:57:40 +02:00
func GetPool(size int32) *sync.Pool {
2018-03-12 16:21:39 +01:00
for idx, ps := range poolSize {
if size <= ps {
2018-09-03 20:57:40 +02:00
return &pool[idx]
2018-03-12 16:21:39 +01:00
}
}
2018-09-03 20:57:40 +02:00
return nil
}
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
2018-12-03 23:39:21 +01:00
//
// v2ray:api:stable
2018-09-03 20:57:40 +02:00
func Alloc(size int32) []byte {
pool := GetPool(size)
if pool != nil {
return pool.Get().([]byte)
}
2018-03-12 16:21:39 +01:00
return make([]byte, size)
2018-03-11 23:06:04 +01:00
}
2016-05-11 10:54:20 -07:00
2018-08-16 12:05:33 +02:00
// Free puts a byte slice into the internal pool.
2018-12-03 23:39:21 +01:00
//
// v2ray:api:stable
2018-08-16 12:05:33 +02:00
func Free(b []byte) {
2018-04-02 22:01:55 +02:00
size := int32(cap(b))
2018-03-12 16:24:31 +01:00
b = b[0:cap(b)]
2018-03-12 16:21:39 +01:00
for i := numPools - 1; i >= 0; i-- {
2018-03-28 22:23:49 +02:00
if size >= poolSize[i] {
pool[i].Put(b) // nolint: staticcheck
2018-03-16 16:22:22 +07:00
return
2018-03-12 16:21:39 +01:00
}
}
2018-03-11 23:06:04 +01:00
}