pool: fixed a bug in PutBuffer

This commit is contained in:
nadoo committed 2020-08-06 18:07:20 +08:00
1 parent 16eee62947
commit 382f9cc519
3 files changed
+30 -28

No files matched your search

+18 -19
View File
@@ -4,40 +4,39 @@ import (
"sync"
)
var bufSizes = []int{
1 << 0, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7, 1 << 8, 1 << 9,
1 << 10, 2 << 10, 4 << 10, 8 << 10, 16 << 10, 32 << 10, 64 << 10,
}
const num = 17 // number of pools, pool size range: 1<<0 ~ 1<<16 bytes. (1Byte~64KBytes)
var bufPools = initPools(bufSizes)
var (
pools [num]sync.Pool
sizes [num]int
)
func initPools(sizes []int) []sync.Pool {
pools := make([]sync.Pool, len(sizes))
func init() {
// use range here to get a copy of index(different k) in each loop.
for k := range pools {
sizes[k] = 1 << k
pools[k].New = func() interface{} {
return make([]byte, sizes[k])
}
}
return pools
}
// GetBuffer returns a buffer from pool.
// GetBuffer gets a buffer from pool.
func GetBuffer(size int) []byte {
i := 0
for ; i < len(bufSizes)-1; i++ {
if size <= bufSizes[i] {
break
for i := 0; i < num; i++ {
if size <= sizes[i] {
return pools[i].Get().([]byte)[:size]
}
}
return bufPools[i].Get().([]byte)[:size]
return make([]byte, size)
}
// PutBuffer puts a buffer into pool.
func PutBuffer(p []byte) {
l := len(p)
for i, n := range bufSizes {
if l == n {
bufPools[i].Put(p)
func PutBuffer(buf []byte) {
c := cap(buf)
for i := 0; i < num; i++ {
if c == sizes[i] {
pools[i].Put(buf)
return
}
}