forked from smallnest/rpcx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer_pool.go
100 lines (90 loc) ยท 1.64 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
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
package util
import (
"math"
"sync"
)
type levelPool struct {
size int
pool sync.Pool
}
func newLevelPool(size int) *levelPool {
return &levelPool{
size: size,
pool: sync.Pool{
New: func() interface{} {
data := make([]byte, size)
return &data
},
},
}
}
type LimitedPool struct {
minSize int
maxSize int
pools []*levelPool
}
func NewLimitedPool(minSize, maxSize int) *LimitedPool {
if maxSize < minSize {
panic("maxSize can't be less than minSize")
}
const multiplier = 2
var pools []*levelPool
curSize := minSize
for curSize < maxSize {
pools = append(pools, newLevelPool(curSize))
curSize *= multiplier
}
pools = append(pools, newLevelPool(maxSize))
return &LimitedPool{
minSize: minSize,
maxSize: maxSize,
pools: pools,
}
}
func (p *LimitedPool) findPool(size int) *levelPool {
if size > p.maxSize {
return nil
}
idx := int(math.Ceil(math.Log2(float64(size) / float64(p.minSize))))
if idx < 0 {
idx = 0
}
if idx > len(p.pools)-1 {
return nil
}
return p.pools[idx]
}
func (p *LimitedPool) findPutPool(size int) *levelPool {
if size > p.maxSize {
return nil
}
if size < p.minSize {
return nil
}
idx := int(math.Floor(math.Log2(float64(size) / float64(p.minSize))))
if idx < 0 {
idx = 0
}
if idx > len(p.pools)-1 {
return nil
}
return p.pools[idx]
}
func (p *LimitedPool) Get(size int) *[]byte {
sp := p.findPool(size)
if sp == nil {
data := make([]byte, size)
return &data
}
buf := sp.pool.Get().(*[]byte)
*buf = (*buf)[:size]
return buf
}
func (p *LimitedPool) Put(b *[]byte) {
sp := p.findPutPool(cap(*b))
if sp == nil {
return
}
*b = (*b)[:cap(*b)]
sp.pool.Put(b)
}