2020-08-13 20:12:22 +00:00
|
|
|
package leveledbytebufferpool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/bits"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/bytesutil"
|
|
|
|
)
|
|
|
|
|
|
|
|
// pools contains pools for byte slices of various capacities.
|
|
|
|
//
|
2020-08-16 19:12:19 +00:00
|
|
|
// pools[0] is for capacities from 0 to 8
|
|
|
|
// pools[1] is for capacities from 9 to 16
|
|
|
|
// pools[2] is for capacities from 17 to 32
|
|
|
|
// ...
|
|
|
|
// pools[n] is for capacities from 2^(n+2)+1 to 2^(n+3)
|
2020-08-13 20:12:22 +00:00
|
|
|
//
|
|
|
|
var pools [30]sync.Pool
|
|
|
|
|
|
|
|
// Get returns byte buffer with the given capacity.
|
|
|
|
func Get(capacity int) *bytesutil.ByteBuffer {
|
2020-08-28 06:44:08 +00:00
|
|
|
id, capacityNeeded := getPoolIDAndCapacity(capacity)
|
2020-08-13 20:12:22 +00:00
|
|
|
for i := 0; i < 2; i++ {
|
2020-08-16 19:12:19 +00:00
|
|
|
if id < 0 || id >= len(pools) {
|
2020-08-13 20:12:22 +00:00
|
|
|
break
|
|
|
|
}
|
2020-08-16 19:12:19 +00:00
|
|
|
if v := pools[id].Get(); v != nil {
|
|
|
|
return v.(*bytesutil.ByteBuffer)
|
|
|
|
}
|
|
|
|
id++
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
2020-08-14 22:40:51 +00:00
|
|
|
return &bytesutil.ByteBuffer{
|
2020-08-16 19:12:19 +00:00
|
|
|
B: make([]byte, 0, capacityNeeded),
|
2020-08-14 22:40:51 +00:00
|
|
|
}
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Put returns bb to the pool.
|
|
|
|
func Put(bb *bytesutil.ByteBuffer) {
|
|
|
|
capacity := cap(bb.B)
|
2020-08-28 06:44:08 +00:00
|
|
|
id, _ := getPoolIDAndCapacity(capacity)
|
2020-08-13 20:12:22 +00:00
|
|
|
bb.Reset()
|
2020-08-16 19:12:19 +00:00
|
|
|
pools[id].Put(bb)
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
|
|
|
|
2020-08-28 06:44:08 +00:00
|
|
|
func getPoolIDAndCapacity(size int) (int, int) {
|
2020-08-16 19:12:19 +00:00
|
|
|
size--
|
2020-08-13 20:12:22 +00:00
|
|
|
if size < 0 {
|
|
|
|
size = 0
|
|
|
|
}
|
|
|
|
size >>= 3
|
2020-08-16 19:12:19 +00:00
|
|
|
id := bits.Len(uint(size))
|
|
|
|
if id > len(pools) {
|
|
|
|
id = len(pools) - 1
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|
2020-08-16 19:12:19 +00:00
|
|
|
return id, (1 << (id + 3))
|
2020-08-13 20:12:22 +00:00
|
|
|
}
|