From a91502bd837b9745adcb5557d887fb329f5ddb52 Mon Sep 17 00:00:00 2001 From: Shivam Kumar Date: Tue, 5 Dec 2023 20:25:31 +0530 Subject: [PATCH] Fix Range panic when cache is empty --- cache.go | 7 +++++++ cache_test.go | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/cache.go b/cache.go index 93943da..a1547fc 100644 --- a/cache.go +++ b/cache.go @@ -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() diff --git a/cache_test.go b/cache_test.go index a7d5d1a..07bf8c5 100644 --- a/cache_test.go +++ b/cache_test.go @@ -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) {