Skip to content

Commit

Permalink
Add Range method
Browse files Browse the repository at this point in the history
  • Loading branch information
gozeloglu committed May 30, 2023
1 parent 7b99ae7 commit c619bbd
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
17 changes: 17 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit c619bbd

Please sign in to comment.