2016-12-09 05:35:27 -05:00
|
|
|
package buf
|
2016-04-12 10:52:57 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2018-03-11 18:06:04 -04:00
|
|
|
const (
|
|
|
|
// Size of a regular buffer.
|
|
|
|
Size = 2 * 1024
|
|
|
|
)
|
2016-11-21 16:08:34 -05:00
|
|
|
|
2018-03-11 18:06:04 -04:00
|
|
|
func createAllocFunc(size uint32) func() interface{} {
|
|
|
|
return func() interface{} {
|
|
|
|
return make([]byte, size)
|
2016-11-21 16:08:34 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-12 11:21:39 -04:00
|
|
|
const (
|
|
|
|
numPools = 5
|
|
|
|
sizeMulti = 4
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
pool [numPools]*sync.Pool
|
|
|
|
poolSize [numPools]uint32
|
|
|
|
)
|
2016-11-21 16:08:34 -05:00
|
|
|
|
2018-03-12 11:21:39 -04:00
|
|
|
func init() {
|
|
|
|
size := uint32(Size)
|
|
|
|
for i := 0; i < numPools; i++ {
|
|
|
|
pool[i] = &sync.Pool{
|
|
|
|
New: createAllocFunc(size),
|
|
|
|
}
|
|
|
|
poolSize[i] = size
|
|
|
|
size *= sizeMulti
|
|
|
|
}
|
2016-11-21 16:08:34 -05:00
|
|
|
}
|
|
|
|
|
2018-03-12 11:21:39 -04:00
|
|
|
func newBytes(size uint32) []byte {
|
|
|
|
for idx, ps := range poolSize {
|
|
|
|
if size <= ps {
|
|
|
|
return pool[idx].Get().([]byte)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return make([]byte, size)
|
2018-03-11 18:06:04 -04:00
|
|
|
}
|
2016-05-11 13:54:20 -04:00
|
|
|
|
2018-03-12 11:21:39 -04:00
|
|
|
func freeBytes(b []byte) {
|
|
|
|
size := uint32(cap(b))
|
2018-03-12 11:24:31 -04:00
|
|
|
b = b[0:cap(b)]
|
2018-03-12 11:21:39 -04:00
|
|
|
for i := numPools - 1; i >= 0; i-- {
|
|
|
|
ps := poolSize[i]
|
|
|
|
if size >= ps {
|
|
|
|
pool[i].Put(b)
|
|
|
|
}
|
|
|
|
}
|
2018-03-11 18:06:04 -04:00
|
|
|
}
|