-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.go
54 lines (41 loc) · 955 Bytes
/
buffer.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
// File: "buffer.go"
// Code based on https://github.com/lmittmann/tint/blob/main/buffer.go
package xlog
import "sync"
const BUFFER_DEFAULT_CAP = 1 << 10 // 1K
const BUFFER_MAX_SIZE = 16 << 10 // 16K
type Buffer []byte
var bufPool = sync.Pool{
New: func() any {
b := make(Buffer, 0, BUFFER_DEFAULT_CAP)
return (*Buffer)(&b)
},
}
func NewBuffer() *Buffer {
return bufPool.Get().(*Buffer)
}
func (b *Buffer) Free() {
// To reduce peak allocation, return only smaller buffers to the pool
if cap(*b) <= BUFFER_MAX_SIZE {
*b = (*b)[:0]
bufPool.Put(b)
}
}
func (b *Buffer) Write(bytes []byte) int {
*b = append(*b, bytes...)
return len(bytes)
}
func (b *Buffer) WriteByte(char byte) {
*b = append(*b, char)
}
func (b *Buffer) WriteString(str string) int {
*b = append(*b, str...)
return len(str)
}
func (b *Buffer) WriteStringIf(ok bool, str string) int {
if !ok {
return 0
}
return b.WriteString(str)
}
// EOF: "buffer.go"