-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils_pool.go
140 lines (117 loc) · 2.07 KB
/
utils_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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package parco
import "sync"
type (
Pool struct {
pool1 sync.Pool
pool2 sync.Pool
pool4 sync.Pool
pool8 sync.Pool
pool256 sync.Pool
poolAny sync.Pool
poolAnyMap map[int]sync.Pool
}
Pooler interface {
Get(size int) *[]byte
Put(*[]byte)
}
)
func newSyncPool(byteSize int) sync.Pool {
return sync.Pool{New: func() any {
b := make([]byte, byteSize)
return &b
}}
}
func NewPool() *Pool {
return &Pool{
pool1: newSyncPool(1),
pool2: newSyncPool(2),
pool4: newSyncPool(4),
pool8: newSyncPool(8),
pool256: newSyncPool(256),
poolAny: newSyncPool(1 << 13),
poolAnyMap: make(map[int]sync.Pool),
}
}
func (p *Pool) Get(size int) *[]byte {
switch size {
case 1:
return p.Get1()
case 2:
return p.Get2()
case 4:
return p.Get4()
case 8:
return p.Get8()
case 256:
return p.Get256()
default:
return p.GetAny()
}
}
func (p *Pool) Put(b *[]byte) {
switch len(*b) {
case 1:
p.Put1(b)
case 2:
p.Put2(b)
case 4:
p.Put4(b)
case 8:
p.Put8(b)
case 256:
p.Put256(b)
default:
p.PutAny(b)
}
}
func (p *Pool) Get1() *[]byte {
return p.pool1.Get().(*[]byte)
}
func (p *Pool) Put1(b *[]byte) {
p.pool1.Put(b)
}
func (p *Pool) Get2() *[]byte {
return p.pool2.Get().(*[]byte)
}
func (p *Pool) Put2(b *[]byte) {
p.pool2.Put(b)
}
func (p *Pool) Get4() *[]byte {
return p.pool4.Get().(*[]byte)
}
func (p *Pool) Put4(b *[]byte) {
p.pool4.Put(b)
}
func (p *Pool) Get8() *[]byte {
return p.pool8.Get().(*[]byte)
}
func (p *Pool) Put8(b *[]byte) {
p.pool4.Put(b)
}
func (p *Pool) Get256() *[]byte {
return p.pool256.Get().(*[]byte)
}
func (p *Pool) Put256(b *[]byte) {
p.pool256.Put(b)
}
func (p *Pool) GetAny() *[]byte {
return p.poolAny.Get().(*[]byte)
}
func (p *Pool) PutAny(b *[]byte) {
p.poolAny.Put(b)
}
func (p *Pool) GetAnyMap(size int) *[]byte {
pool, ok := p.poolAnyMap[size]
if !ok {
pool = newSyncPool(size)
p.poolAnyMap[size] = pool
}
return pool.Get().(*[]byte)
}
func (p *Pool) PutAnyMap(b *[]byte) {
pool, _ := p.poolAnyMap[len(*b)]
pool.Put(b)
}
var (
SinglePool = NewPool()
)