summaryrefslogtreecommitdiff
path: root/vendor/git.iim.gay/grufwub/go-bytes/pool.go
blob: edd6859c19ccfb9a9feb7b9b328c11809fce1aeb (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
package bytes

import (
	"bytes"
	"sync"
)

type SizedBufferPool struct {
	pool sync.Pool
	len  int
	cap  int
}

func (p *SizedBufferPool) Init(len, cap int) {
	p.pool.New = func() interface{} {
		buf := NewBuffer(make([]byte, len, cap))
		return &buf
	}
	p.len = len
	p.cap = cap
}

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

func (p *SizedBufferPool) Release(buf *bytes.Buffer) {
	// If not enough cap, ignore
	if buf.Cap() < p.cap {
		return
	}

	// Set length to expected
	buf.Reset()
	buf.Grow(p.len)

	// Place in pool
	p.pool.Put(buf)
}