forked from p4gefau1t/trojan-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.go
75 lines (62 loc) · 1.21 KB
/
buffer.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
64
65
66
67
68
69
70
71
72
73
74
75
package vmess
import (
"bytes"
"errors"
"math/bits"
"sync"
)
func init() {
bufPools = InitBufPools()
writeBufPool = InitWriteBufPool()
}
//
// Read buffer
//
var bufPools []sync.Pool
func InitBufPools() []sync.Pool {
pools := make([]sync.Pool, 17) // 1B -> 64K
for k := range pools {
i := k
pools[k].New = func() interface{} {
return make([]byte, 1<<uint32(i))
}
}
return pools
}
func msb(size int) uint16 {
return uint16(bits.Len32(uint32(size)) - 1)
}
func GetBuffer(size int) []byte {
if size <= 0 || size > 65536 {
return nil
}
bits := msb(size)
if size == 1<<bits {
return bufPools[bits].Get().([]byte)[:size]
}
return bufPools[bits+1].Get().([]byte)[:size]
}
func PutBuffer(buf []byte) error {
bits := msb(cap(buf))
if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1<<bits {
return errors.New("incorrect buffer size")
}
bufPools[bits].Put(buf)
return nil
}
//
// Write buffer
//
var writeBufPool sync.Pool
func InitWriteBufPool() sync.Pool {
return sync.Pool{
New: func() interface{} { return &bytes.Buffer{} },
}
}
func GetWriteBuffer() *bytes.Buffer {
return writeBufPool.Get().(*bytes.Buffer)
}
func PutWriteBuffer(buf *bytes.Buffer) {
buf.Reset()
writeBufPool.Put(buf)
}