@@ -8,18 +8,23 @@ import (
8
8
"sync"
9
9
)
10
10
11
- var defaultAllocator = NewAllocator ()
11
+ var DefaultAllocator = NewAllocator ()
12
12
13
- // Allocator for incoming frames, optimized to prevent overwriting after zeroing
14
- type Allocator struct {
13
+ type Allocator interface {
14
+ Get (size int ) []byte
15
+ Put (buf []byte ) error
16
+ }
17
+
18
+ // defaultAllocator for incoming frames, optimized to prevent overwriting after zeroing
19
+ type defaultAllocator struct {
15
20
buffers [11 ]sync.Pool
16
21
}
17
22
18
23
// NewAllocator initiates a []byte allocator for frames less than 65536 bytes,
19
24
// the waste(memory fragmentation) of space allocation is guaranteed to be
20
25
// no more than 50%.
21
- func NewAllocator () * Allocator {
22
- return & Allocator {
26
+ func NewAllocator () Allocator {
27
+ return & defaultAllocator {
23
28
buffers : [... ]sync.Pool { // 64B -> 64K
24
29
{New : func () any { return new ([1 << 6 ]byte ) }},
25
30
{New : func () any { return new ([1 << 7 ]byte ) }},
@@ -37,7 +42,7 @@ func NewAllocator() *Allocator {
37
42
}
38
43
39
44
// Get a []byte from pool with most appropriate cap
40
- func (alloc * Allocator ) Get (size int ) []byte {
45
+ func (alloc * defaultAllocator ) Get (size int ) []byte {
41
46
switch {
42
47
case size < 0 :
43
48
panic ("alloc.Get: len out of range" )
@@ -87,7 +92,7 @@ func (alloc *Allocator) Get(size int) []byte {
87
92
88
93
// Put returns a []byte to pool for future use,
89
94
// which the cap must be exactly 2^n
90
- func (alloc * Allocator ) Put (buf []byte ) error {
95
+ func (alloc * defaultAllocator ) Put (buf []byte ) error {
91
96
if cap (buf ) == 0 || cap (buf ) > 65536 {
92
97
return nil
93
98
}
0 commit comments