Files
smux/alloc.go
T
xtaci f386d90508 Squashed commit of the following:
commit 486431f53deb10b0e6ee51b47785f6f06f0d5733
Author: xtaci <daniel820313@gmail.com>
Date:   Thu Dec 26 12:02:52 2019 +0800

    remove in-package pkg/errors

commit 213597603a726735678024ec6051800c46ed0bd0
Author: xtaci <daniel820313@gmail.com>
Date:   Thu Dec 26 11:58:36 2019 +0800

    fix poll

commit d1f7aeefbeb40da99d47ba2b7db5bd403c09ddba
Author: xtaci <daniel820313@gmail.com>
Date:   Thu Dec 26 11:17:28 2019 +0800

    fix error

commit 152918f9b531c06b42c764f0aff35d4bb9315713
Author: xtaci <daniel820313@gmail.com>
Date:   Wed Dec 25 23:27:18 2019 +0800

    poll for v1
2019-12-26 12:06:21 +08:00

69 lines
1.5 KiB
Go

package smux
import (
"errors"
"sync"
)
var defaultAllocator *Allocator
func init() {
defaultAllocator = NewAllocator()
}
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
type Allocator struct {
buffers []sync.Pool
}
// NewAllocator initiates a []byte allocator for frames less than 65536 bytes,
// the waste(memory fragmentation) of space allocation is guaranteed to be
// no more than 50%.
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
}
// Get a []byte from pool with most appropriate cap
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]
}
}
// Put returns a []byte to pool for future use,
// which the cap must be exactly 2^n
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
size >>= 1
for size > 0 {
size >>= 1
pos++
}
return pos
}