forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer_pool.go
63 lines (55 loc) · 1.12 KB
/
buffer_pool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package buf
import (
"sync"
)
const (
// Size of a regular buffer.
Size = 2 * 1024
)
func createAllocFunc(size int32) func() interface{} {
return func() interface{} {
return make([]byte, size)
}
}
// 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 = 5
sizeMulti = 4
)
var (
pool [numPools]sync.Pool
poolSize [numPools]int32
largeSize int32
)
func init() {
size := int32(Size)
for i := 0; i < numPools; i++ {
pool[i] = sync.Pool{
New: createAllocFunc(size),
}
poolSize[i] = size
largeSize = size
size *= sizeMulti
}
}
func newBytes(size int32) []byte {
for idx, ps := range poolSize {
if size <= ps {
return pool[idx].Get().([]byte)
}
}
return make([]byte, size)
}
func freeBytes(b []byte) {
size := int32(cap(b))
b = b[0:cap(b)]
for i := numPools - 1; i >= 0; i-- {
if size >= poolSize[i] {
pool[i].Put(b)
return
}
}
}