Files
smux/alloc.go
T
2019-05-14 14:03:58 +08:00

66 lines
1.1 KiB
Go

package smux
import (
"sync"
"github.com/pkg/errors"
)
var defaultAllocator *Allocator
func init() {
defaultAllocator = NewAllocator()
}
// allocator for incoming frames
// to prevent write after zeroing
type Allocator struct {
buffers []sync.Pool
}
func NewAllocator() *Allocator {
alloc := new(Allocator)
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
for k := range alloc.buffers {
i := k
alloc.buffers[k].New = func() interface{} {
return make([]byte, 1<<uint32(i))
}
}
return alloc
}
func (alloc *Allocator) Get(size int) []byte {
if size <= 0 || size > 65536 {
return nil
}
bits := msb(size)
if size == 1<<bits {
return alloc.buffers[bits].Get().([]byte)[:size]
} else {
return alloc.buffers[bits+1].Get().([]byte)[:size]
}
}
func (alloc *Allocator) Put(buf []byte) error {
bits := msb(cap(buf))
if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1<<bits {
return errors.New("allocator Put() incorrect buffer size")
}
alloc.buffers[bits].Put(buf)
return nil
}
// msb return the pos of most significiant bit
func msb(size int) uint16 {
var pos uint16
for {
size >>= 1
if size == 0 {
return pos
}
pos++
}
}