From c619bbdcc120c20602f1893c76e4e7e30aff8761 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=B6khan=20=C3=96zelo=C4=9Flu?= <33967642+gozeloglu@users.noreply.github.com> Date: Tue, 30 May 2023 13:33:03 +0300 Subject: [PATCH] Add `Range` method --- cache.go | 17 +++++++++++++++++ cache_test.go | 12 ++++++++++++ 2 files changed, 29 insertions(+) diff --git a/cache.go b/cache.go index 2c9df9a..c58a327 100644 --- a/cache.go +++ b/cache.go @@ -561,6 +561,23 @@ func (c *Cache[K, V]) OnEviction(fn func(context.Context, EvictionReason, *Item[ } } +// Range iterate over all items and calls fn function. It calls fn function +// until it returns false. +func (c *Cache[K, V]) Range(fn func(item *Item[K, V]) bool) { + c.items.mu.RLock() + 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() + if !fn(i) { + return + } + + if item.Next() != nil { + c.items.mu.RLock() + } + } +} + // Loader is an interface that handles missing data loading. type Loader[K comparable, V any] interface { // Load should execute a custom item retrieval logic and diff --git a/cache_test.go b/cache_test.go index 977a6f8..65d9b02 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1006,6 +1006,18 @@ func Test_Cache_OnEviction(t *testing.T) { assert.NotContains(t, cache.events.eviction.fns, uint64(1)) } +func Test_Cache_Range(t *testing.T) { + c := prepCache(DefaultTTL, "1", "2", "3", "4", "5") + var results []string + + c.Range(func(item *Item[string, string]) bool { + results = append(results, item.Key()) + return item.Key() != "4" + }) + + assert.Equal(t, []string{"5", "4"}, results) +} + func Test_LoaderFunc_Load(t *testing.T) { var called bool