Skip to content

Commit a91502b

Browse files
Fix Range panic when cache is empty
1 parent 6c6fce4 commit a91502b

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

cache.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,13 @@ func (c *Cache[K, V]) Items() map[K]*Item[K, V] {
478478
// Range stops the iteration.
479479
func (c *Cache[K, V]) Range(fn func(item *Item[K, V]) bool) {
480480
c.items.mu.RLock()
481+
482+
// Check if cache is empty
483+
if c.items.lru.Len() == 0 {
484+
c.items.mu.RUnlock()
485+
return
486+
}
487+
481488
for item := c.items.lru.Front(); item != c.items.lru.Back().Next(); item = item.Next() {
482489
i := item.Value.(*Item[K, V])
483490
c.items.mu.RUnlock()

cache_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -806,6 +806,13 @@ func Test_Cache_Range(t *testing.T) {
806806
})
807807

808808
assert.Equal(t, []string{"5", "4"}, results)
809+
810+
emptyCache := New[string, string]()
811+
assert.NotPanics(t, func() {
812+
emptyCache.Range(func(item *Item[string, string]) bool {
813+
return false
814+
})
815+
})
809816
}
810817

811818
func Test_Cache_Metrics(t *testing.T) {

0 commit comments

Comments
 (0)