1
2
3
4
5
6 package buffer
7
8 import "sync"
9
10
11
12
13
14 type Buffer []byte
15
16
17 var bufPool = sync.Pool{
18 New: func() any {
19 b := make([]byte, 0, 1024)
20 return (*Buffer)(&b)
21 },
22 }
23
24 func New() *Buffer {
25 return bufPool.Get().(*Buffer)
26 }
27
28 func (b *Buffer) Free() {
29
30 const maxBufferSize = 16 << 10
31 if cap(*b) <= maxBufferSize {
32 *b = (*b)[:0]
33 bufPool.Put(b)
34 }
35 }
36
37 func (b *Buffer) Reset() {
38 b.SetLen(0)
39 }
40
41 func (b *Buffer) Write(p []byte) (int, error) {
42 *b = append(*b, p...)
43 return len(p), nil
44 }
45
46 func (b *Buffer) WriteString(s string) (int, error) {
47 *b = append(*b, s...)
48 return len(s), nil
49 }
50
51 func (b *Buffer) WriteByte(c byte) error {
52 *b = append(*b, c)
53 return nil
54 }
55
56 func (b *Buffer) String() string {
57 return string(*b)
58 }
59
60 func (b *Buffer) Len() int {
61 return len(*b)
62 }
63
64 func (b *Buffer) SetLen(n int) {
65 *b = (*b)[:n]
66 }
67
View as plain text