File: buffer.go

package info (click to toggle)
golang-github-cilium-ebpf 0.17.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,684 kB
  • sloc: ansic: 1,259; makefile: 127; python: 113; awk: 29; sh: 24
file content (31 lines) | stat: -rw-r--r-- 812 bytes parent folder | download | duplicates (2)
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
package internal

import (
	"bytes"
	"sync"
)

var bytesBufferPool = sync.Pool{
	New: func() interface{} {
		return new(bytes.Buffer)
	},
}

// NewBuffer retrieves a [bytes.Buffer] from a pool an re-initialises it.
//
// The returned buffer should be passed to [PutBuffer].
func NewBuffer(buf []byte) *bytes.Buffer {
	wr := bytesBufferPool.Get().(*bytes.Buffer)
	// Reinitialize the Buffer with a new backing slice since it is returned to
	// the caller by wr.Bytes() below. Pooling is faster despite calling
	// NewBuffer. The pooled alloc is still reused, it only needs to be zeroed.
	*wr = *bytes.NewBuffer(buf)
	return wr
}

// PutBuffer releases a buffer to the pool.
func PutBuffer(buf *bytes.Buffer) {
	// Release reference to the backing buffer.
	*buf = *bytes.NewBuffer(nil)
	bytesBufferPool.Put(buf)
}