1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-29 23:36:25 -04:00
v2fly/common/buf/buffer_pool.go

64 lines
1.1 KiB
Go
Raw Normal View History

2016-12-09 05:35:27 -05:00
package buf
2016-04-12 10:52:57 -04:00
import (
"sync"
)
2018-03-11 18:06:04 -04:00
const (
// Size of a regular buffer.
Size = 2 * 1024
)
2016-11-21 16:08:34 -05:00
2018-04-02 16:01:55 -04:00
func createAllocFunc(size int32) func() interface{} {
2018-03-11 18:06:04 -04:00
return func() interface{} {
return make([]byte, size)
2016-11-21 16:08:34 -05:00
}
}
2018-04-01 06:20:32 -04: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 11:21:39 -04:00
const (
2018-07-27 11:24:26 -04:00
numPools = 4
2018-03-12 11:21:39 -04:00
sizeMulti = 4
)
var (
2018-04-01 06:20:32 -04:00
pool [numPools]sync.Pool
2018-04-02 16:01:55 -04:00
poolSize [numPools]int32
largeSize int32
2018-03-12 11:21:39 -04:00
)
2016-11-21 16:08:34 -05:00
2018-03-12 11:21:39 -04:00
func init() {
2018-04-02 16:01:55 -04:00
size := int32(Size)
2018-03-12 11:21:39 -04:00
for i := 0; i < numPools; i++ {
2018-03-16 05:22:22 -04:00
pool[i] = sync.Pool{
2018-03-12 11:21:39 -04:00
New: createAllocFunc(size),
}
poolSize[i] = size
2018-04-01 06:20:32 -04:00
largeSize = size
2018-03-12 11:21:39 -04:00
size *= sizeMulti
}
2016-11-21 16:08:34 -05:00
}
2018-04-02 16:01:55 -04:00
func newBytes(size int32) []byte {
2018-03-12 11:21:39 -04:00
for idx, ps := range poolSize {
if size <= ps {
return pool[idx].Get().([]byte)
}
}
return make([]byte, size)
2018-03-11 18:06:04 -04:00
}
2016-05-11 13:54:20 -04:00
2018-03-12 11:21:39 -04:00
func freeBytes(b []byte) {
2018-04-02 16:01:55 -04:00
size := int32(cap(b))
2018-03-12 11:24:31 -04:00
b = b[0:cap(b)]
2018-03-12 11:21:39 -04:00
for i := numPools - 1; i >= 0; i-- {
2018-03-28 16:23:49 -04:00
if size >= poolSize[i] {
2018-05-28 17:05:11 -04:00
pool[i].Put(b) // nolint: megacheck
2018-03-16 05:22:22 -04:00
return
2018-03-12 11:21:39 -04:00
}
}
2018-03-11 18:06:04 -04:00
}