summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-pools/bytes.go
blob: 76fe18616bad8729cdf66f54ece3cef14c6d4577 (plain)
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
package pools

import (
	"sync"

	"codeberg.org/gruf/go-bytes"
)

// BufferPool is a pooled allocator for bytes.Buffer objects
type BufferPool interface {
	// Get fetches a bytes.Buffer from pool
	Get() *bytes.Buffer

	// Put places supplied bytes.Buffer in pool
	Put(*bytes.Buffer)
}

// NewBufferPool returns a newly instantiated bytes.Buffer pool
func NewBufferPool(size int) BufferPool {
	return &bufferPool{
		pool: sync.Pool{
			New: func() interface{} {
				return &bytes.Buffer{B: make([]byte, 0, size)}
			},
		},
		size: size,
	}
}

// bufferPool is our implementation of BufferPool
type bufferPool struct {
	pool sync.Pool
	size int
}

func (p *bufferPool) Get() *bytes.Buffer {
	return p.pool.Get().(*bytes.Buffer)
}

func (p *bufferPool) Put(buf *bytes.Buffer) {
	if buf.Cap() < p.size {
		return
	}
	buf.Reset()
	p.pool.Put(buf)
}