-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.go
53 lines (46 loc) · 984 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
package bufferpool
type Buffer struct {
buf *[]byte
donated bool
}
func NewBuffer(buf []byte) *Buffer {
b := buf[0:len(buf):len(buf)]
return &Buffer{
// Having cap(buf) == len(buf) prevents the original buffer from being
// modified when new data is appended.
buf: &b,
donated: true,
}
}
func (b *Buffer) growIfNecessary(n int) {
if b.donated || len(*b.buf)+n > cap(*b.buf) {
if b.buf == nil && n < MinBufferSize {
n = MinBufferSize
}
newBuf := Get(len(*b.buf) + n)
*newBuf = (*newBuf)[:0]
*newBuf = append(*newBuf, *b.buf...)
if b.buf != nil && !b.donated {
Put(b.buf)
}
b.buf = newBuf
b.donated = false
}
}
func (b *Buffer) Write(p []byte) (int, error) {
b.growIfNecessary(len(p))
*b.buf = append(*b.buf, p...)
return len(p), nil
}
func (b *Buffer) Len() int {
return len(*b.buf)
}
func (b *Buffer) Bytes() []byte {
return *b.buf
}
func (b *Buffer) Reset() {
if b.buf != nil && !b.donated {
Put(b.buf)
}
b.buf = nil
}