-
Notifications
You must be signed in to change notification settings - Fork 10
/
bytearena.go
51 lines (42 loc) · 1.09 KB
/
bytearena.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package util
// ByteArena for reduce GC pressure, not concurrent safe
type ByteArena struct {
alloc []byte
chunkAllocMinSize int
chunkAllocMaxSize int
}
// NewByteArena is ctor for ByteArena
func NewByteArena(chunkAllocMinSize, chunkAllocMaxSize int) *ByteArena {
return &ByteArena{chunkAllocMinSize: chunkAllocMinSize, chunkAllocMaxSize: chunkAllocMaxSize}
}
// AllocBytes for allocate bytes
func (a *ByteArena) AllocBytes(n int) (bytes []byte) {
if cap(a.alloc)-len(a.alloc) < n {
bytes = a.reserveOrAlloc(n)
if bytes != nil {
return
}
}
pos := len(a.alloc)
bytes = a.alloc[pos : pos+n : pos+n]
a.alloc = a.alloc[:pos+n]
return
}
// UnsafeReset for reuse
func (a *ByteArena) UnsafeReset() {
a.alloc = a.alloc[:0]
}
func (a *ByteArena) reserveOrAlloc(n int) (bytes []byte) {
allocSize := cap(a.alloc) * 2
if allocSize < a.chunkAllocMinSize {
allocSize = a.chunkAllocMinSize
} else if allocSize > a.chunkAllocMaxSize {
allocSize = a.chunkAllocMaxSize
}
if allocSize <= n {
bytes = make([]byte, 0, n)
return
}
a.alloc = make([]byte, 0, allocSize)
return
}