aboutsummaryrefslogtreecommitdiff
path: root/internal/bufpool/capacity.go
blob: ecbd7d7639705620145d4db8224255babb3372a7 (about) (plain) (blame)
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
package bufpool

// ensureCapacity grows the underlying buffer to accommodate the requested
// number of bytes. Growth doubles the capacity by default unless a larger
// expansion is needed. If the previous storage was pooled and not oversized,
// it is returned to the pool.
func (buf *Buffer) ensureCapacity(needed int) {
	if cap(buf.buf) >= needed {
		return
	}

	classIdx, classCap, pooled := classFor(needed)

	var newBuf []byte

	if pooled {
		//nolint:forcetypeassert
		raw := bufferPools[classIdx].Get().(*[]byte)
		if cap(*raw) < classCap {
			*raw = make([]byte, 0, classCap)
		}

		newBuf = (*raw)[:len(buf.buf)]
	} else {
		newBuf = make([]byte, len(buf.buf), classCap)
	}

	copy(newBuf, buf.buf)
	buf.returnToPool()

	buf.buf = newBuf
	if pooled {
		buf.pool = poolIndex(classIdx) //#nosec G115
	} else {
		buf.pool = unpooled
	}
}