-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffers.go
75 lines (57 loc) · 1.09 KB
/
buffers.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package lsvd
import (
"context"
"sync"
)
const BufferSliceSize = 1024 * 1024
type Buffers struct {
slice []byte
next int
}
var buffersPool = sync.Pool{
New: func() any {
return &Buffers{
slice: make([]byte, BufferSliceSize),
}
},
}
func NewBuffers() *Buffers {
return buffersPool.Get().(*Buffers)
}
func ReturnBuffers(buf *Buffers) {
buf.next = 0
buffersPool.Put(buf)
}
type buffersKey struct{}
func B(ctx context.Context) *Buffers {
val := ctx.Value(buffersKey{})
if val == nil {
return &Buffers{}
}
return val.(*Buffers)
}
func (b *Buffers) Inject(ctx context.Context) context.Context {
return context.WithValue(ctx, buffersKey{}, b)
}
func (b *Buffers) Reset() {
b.next = 0
}
func (b *Buffers) Marker() int {
return b.next
}
func (b *Buffers) ResetTo(marker int) {
b.next = marker
}
func (b *Buffers) alloc(sz int) []byte {
if len(b.slice)-b.next < sz {
if sz > BufferSliceSize {
return make([]byte, sz)
}
dup := make([]byte, len(b.slice)+BufferSliceSize)
copy(dup, b.slice)
b.slice = dup
}
data := b.slice[b.next : b.next+sz]
b.next += sz
return data
}