forked from valyala/quicktemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytebuffer.go
49 lines (42 loc) · 1.11 KB
/
bytebuffer.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
package quicktemplate
import (
"sync"
)
// ByteBuffer implements io.Writer on top of byte slice.
//
// Recycle byte buffers via AcquireByteBuffer and ReleaseByteBuffer
// in order to reduce memory allocations.
type ByteBuffer struct {
// B is a byte slice backing byte buffer.
// All the data written via Write is appended here.
B []byte
}
// Write implements io.Writer.
func (bb *ByteBuffer) Write(p []byte) (int, error) {
bb.B = append(bb.B, p...)
return len(p), nil
}
// Reset resets the byte buffer.
func (bb *ByteBuffer) Reset() {
bb.B = bb.B[:0]
}
// AcquireByteBuffer returns new ByteBuffer from the pool.
//
// Return unneeded buffers to the pool by calling ReleaseByteBuffer
// in order to reduce memory allocations.
func AcquireByteBuffer() *ByteBuffer {
v := byteBufferPool.Get()
if v == nil {
return &ByteBuffer{}
}
return v.(*ByteBuffer)
}
// ReleaseByteBuffer retruns byte buffer to the pool.
//
// Do not access byte buffer after returning it to the pool,
// otherwise data races may occur.
func ReleaseByteBuffer(bb *ByteBuffer) {
bb.Reset()
byteBufferPool.Put(bb)
}
var byteBufferPool sync.Pool