Skip to content

Commit

Permalink
Correctly return slices to their respective buckets or discard them
Browse files Browse the repository at this point in the history
  • Loading branch information
jhesketh committed Dec 17, 2024
1 parent b8256be commit 1e76f29
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
8 changes: 7 additions & 1 deletion pkg/util/pool/bucketed_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,14 @@ func (p *BucketedPool[T, E]) Put(s T) {
}

bucketIndex := bits.Len(size - 1)
if bucketIndex >= len(p.buckets) {
return // Ignore slices larger than the largest bucket
}

// Ignore slices that do not align to the current power of 2
// (this will only happen where a slice did not originally come from the pool).
if size != (1 << bucketIndex) {
bucketIndex--
return
}

p.buckets[bucketIndex].Put(s[0:0])
Expand Down
18 changes: 18 additions & 0 deletions pkg/util/pool/bucketed_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,21 @@ func TestBucketedPool_AlwaysReturnsPowerOfTwoCapacities(t *testing.T) {
pool.Put(slice)
}
}

func TestBucketedPool_PutSizeCloseToMax(t *testing.T) {
maxSize := 100000
pool := NewBucketedPool(uint(maxSize), makeFunc)

// Create a slice with capacity that triggers the upper edge case
s := make([]int, 0, 65_000) // 86401 is close to maxSize but not aligned to power of 2

// Ensure Put does not panic when adding this slice
require.NotPanics(t, func() {
pool.Put(s)
}, "Put should not panic for sizes close to maxSize")

// Validate that a subsequent Get for a smaller size works fine
ret := pool.Get(1)
require.Equal(t, 1, cap(ret))
require.Len(t, ret, 0)
}

0 comments on commit 1e76f29

Please sign in to comment.