Skip to content

Commit

Permalink
Fix Range panic when cache is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
ShivamKumar2002 committed Dec 5, 2023
1 parent 6c6fce4 commit a91502b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
7 changes: 7 additions & 0 deletions cache.go
Expand Up @@ -478,6 +478,13 @@ func (c *Cache[K, V]) Items() map[K]*Item[K, V] {
// Range stops the iteration.
func (c *Cache[K, V]) Range(fn func(item *Item[K, V]) bool) {
c.items.mu.RLock()

// Check if cache is empty
if c.items.lru.Len() == 0 {
c.items.mu.RUnlock()
return
}

for item := c.items.lru.Front(); item != c.items.lru.Back().Next(); item = item.Next() {
i := item.Value.(*Item[K, V])
c.items.mu.RUnlock()
Expand Down
7 changes: 7 additions & 0 deletions cache_test.go
Expand Up @@ -806,6 +806,13 @@ func Test_Cache_Range(t *testing.T) {
})

assert.Equal(t, []string{"5", "4"}, results)

emptyCache := New[string, string]()
assert.NotPanics(t, func() {
emptyCache.Range(func(item *Item[string, string]) bool {
return false
})
})
}

func Test_Cache_Metrics(t *testing.T) {
Expand Down

0 comments on commit a91502b

Please sign in to comment.