Skip to content

Commit

Permalink
Return error instead of panicking
Browse files Browse the repository at this point in the history
Signed-off-by: Christian Haudum <christian.haudum@gmail.com>
  • Loading branch information
chaudum committed Jun 3, 2024
1 parent 96152ca commit b7c1f97
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
6 changes: 3 additions & 3 deletions pkg/util/mempool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,16 @@ func New(buckets []Bucket) *MemPool {
}

// Get satisfies Allocator interface
// Allocating a buffer from an exhausted pool/slab will return an error.
// Allocating a buffer that exceeds the largest slab size will cause a panic.
// Allocating a buffer from an exhausted pool/slab, or allocating a buffer that
// exceeds the largest slab size will return an error.
func (a *MemPool) Get(size int) ([]byte, error) {
for i := 0; i < len(a.slabs); i++ {
if a.slabs[i].size < size {
continue
}
return a.slabs[i].get(size)
}
panic(fmt.Sprintf("no slab found for size: %d", size))
return nil, fmt.Errorf("no slab found for size: %d", size)
}

// Put satisfies Allocator interface
Expand Down
10 changes: 4 additions & 6 deletions pkg/util/mempool/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,16 @@ func TestMemPool(t *testing.T) {

t.Run("empty pool", func(t *testing.T) {
pool := New([]Bucket{})
require.Panics(t, func() {
_, _ = pool.Get(128)
})
_, err := pool.Get(256)
require.Error(t, err)
})

t.Run("requested size too big", func(t *testing.T) {
pool := New([]Bucket{
{Size: 1, Capacity: 128},
})
require.Panics(t, func() {
_, _ = pool.Get(256)
})
_, err := pool.Get(256)
require.Error(t, err)
})

t.Run("requested size within bucket", func(t *testing.T) {
Expand Down

0 comments on commit b7c1f97

Please sign in to comment.