1package sync
2
3import (
4 "bytes"
5 "sync"
6)
7
8var (
9 byteSlice = sync.Pool{
10 New: func() interface{} {
11 b := make([]byte, 16*1024)
12 return &b
13 },
14 }
15 bytesBuffer = sync.Pool{
16 New: func() interface{} {
17 return bytes.NewBuffer(nil)
18 },
19 }
20)
21
22// GetByteSlice returns a *[]byte that is managed by a sync.Pool.
23// The initial slice length will be 16384 (16kb).
24//
25// After use, the *[]byte should be put back into the sync.Pool
26// by calling PutByteSlice.
27func GetByteSlice() *[]byte {
28 buf := byteSlice.Get().(*[]byte)
29 return buf
30}
31
32// PutByteSlice puts buf back into its sync.Pool.
33func PutByteSlice(buf *[]byte) {
34 byteSlice.Put(buf)
35}
36
37// GetBytesBuffer returns a *bytes.Buffer that is managed by a sync.Pool.
38// Returns a buffer that is reset and ready for use.
39//
40// After use, the *bytes.Buffer should be put back into the sync.Pool
41// by calling PutBytesBuffer.
42func GetBytesBuffer() *bytes.Buffer {
43 buf := bytesBuffer.Get().(*bytes.Buffer)
44 buf.Reset()
45 return buf
46}
47
48// PutBytesBuffer puts buf back into its sync.Pool.
49func PutBytesBuffer(buf *bytes.Buffer) {
50 bytesBuffer.Put(buf)
51}