-
Notifications
You must be signed in to change notification settings - Fork 796
/
slicesPool.go
61 lines (49 loc) · 1.09 KB
/
slicesPool.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
package cortexpb
import (
"math"
"sync"
)
const (
minPoolSizePower = 5
)
type byteSlicePools struct {
pools []sync.Pool
}
func newSlicePool(pools int) *byteSlicePools {
sp := byteSlicePools{}
sp.init(pools)
return &sp
}
func (sp *byteSlicePools) init(pools int) {
sp.pools = make([]sync.Pool, pools)
for i := 0; i < pools; i++ {
size := int(math.Pow(2, float64(i+minPoolSizePower)))
sp.pools[i] = sync.Pool{
New: func() interface{} {
buf := make([]byte, 0, size)
return &buf
},
}
}
}
func (sp *byteSlicePools) getSlice(size int) *[]byte {
index := int(math.Ceil(math.Log2(float64(size)))) - minPoolSizePower
if index >= len(sp.pools) {
buf := make([]byte, size)
return &buf
}
// if the size is < than the minPoolSizePower we return an array from the first pool
if index < 0 {
index = 0
}
s := sp.pools[index].Get().(*[]byte)
*s = (*s)[:size]
return s
}
func (sp *byteSlicePools) reuseSlice(s *[]byte) {
index := int(math.Floor(math.Log2(float64(cap(*s))))) - minPoolSizePower
if index >= len(sp.pools) || index < 0 {
return
}
sp.pools[index].Put(s)
}