From 912bbb2f1d3cef93d605be1afd29d51254499fc8 Mon Sep 17 00:00:00 2001 From: Klaus Post Date: Tue, 2 Apr 2024 08:56:18 -0700 Subject: [PATCH] Always return slice with cap (#19395) Documentation promised this - so we should do it as well. Try to get a buffer and stash if it isn't big enough. --- internal/grid/grid.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/internal/grid/grid.go b/internal/grid/grid.go index a26363f5b..447dae25a 100644 --- a/internal/grid/grid.go +++ b/internal/grid/grid.go @@ -87,12 +87,19 @@ var GetByteBuffer = func() []byte { // GetByteBufferCap returns a length 0 byte buffer with at least the given capacity. func GetByteBufferCap(wantSz int) []byte { - switch { - case wantSz <= defaultBufferSize: - return GetByteBuffer()[:0] - case wantSz <= maxBufferSize: + if wantSz < defaultBufferSize { + b := GetByteBuffer()[:0] + if cap(b) >= wantSz { + return b + } + PutByteBuffer(b) + } + if wantSz <= maxBufferSize { b := *internal32KByteBuffer.Get().(*[]byte) - return b[:0] + if cap(b) >= wantSz { + return b[:0] + } + internal32KByteBuffer.Put(&b) } return make([]byte, 0, wantSz) }