Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cherry-pick #7702 to 1.68.x #7792

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion mem/buffers.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ func newBuffer() *buffer {
//
// Note that the backing array of the given data is not copied.
func NewBuffer(data *[]byte, pool BufferPool) Buffer {
if pool == nil || IsBelowBufferPoolingThreshold(len(*data)) {
// Use the buffer's capacity instead of the length, otherwise buffers may
// not be reused under certain conditions. For example, if a large buffer
// is acquired from the pool, but fewer bytes than the buffering threshold
// are written to it, the buffer will not be returned to the pool.
if pool == nil || IsBelowBufferPoolingThreshold(cap(*data)) {
return (SliceBuffer)(*data)
}
b := newBuffer()
Expand Down
27 changes: 27 additions & 0 deletions mem/buffers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,33 @@ func (s) TestBuffer_NewBufferRefAndFree(t *testing.T) {
}
}

func (s) TestBuffer_NewBufferHandlesShortBuffers(t *testing.T) {
const threshold = 100

// Update the pooling threshold, since that's what's being tested.
internal.SetBufferPoolingThresholdForTesting.(func(int))(threshold)
t.Cleanup(func() {
internal.SetBufferPoolingThresholdForTesting.(func(int))(0)
})

// Make a pool with a buffer whose capacity is larger than the pooling
// threshold, but whose length is less than the threshold.
b := make([]byte, threshold/2, threshold*2)
pool := &singleBufferPool{
t: t,
data: &b,
}

// Get a Buffer, then free it. If NewBuffer decided that the Buffer
// shouldn't get pooled, Free will be a noop and singleBufferPool will not
// have been updated.
mem.NewBuffer(&b, pool).Free()

if pool.data != nil {
t.Fatalf("Buffer not returned to pool")
}
}

func (s) TestBuffer_FreeAfterFree(t *testing.T) {
buf := newBuffer([]byte("abcd"), mem.NopBufferPool{})
if buf.Len() != 4 {
Expand Down
Loading