Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable iteration of key/val pairs in expirable LRU #178

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion expirable/expirable_lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,16 @@ func (c *LRU[K, V]) Values() []V {
return values
}

// Range calls a function on key/value pairs in the cache, from oldest to newest,
// until the provided callback returns true. Expired entries are filtered out.
func (c *LRU[K, V]) Range(callback func(key K, value V) (done bool)) {
for _, ent := range c.entries() {
if callback(ent.Key, ent.Value) {
return
}
}
}

// Len returns the number of items in the cache.
func (c *LRU[K, V]) Len() int {
c.mu.Lock()
Expand Down Expand Up @@ -340,7 +350,23 @@ func (c *LRU[K, V]) removeFromBucket(e *internal.Entry[K, V]) {
delete(c.buckets[e.ExpireBucket].entries, e.Key)
}

// entries returns a slice of the current internal entries in the cache
func (c *LRU[K, V]) entries() []*internal.Entry[K, V] {
c.mu.Lock()
defer c.mu.Unlock()

entries := make([]*internal.Entry[K, V], 0, len(c.items))
now := time.Now()
for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() {
if now.After(ent.ExpiresAt) {
continue
}
entries = append(entries, ent)
}
return entries
}

// Cap returns the capacity of the cache
func (c *LRU[K, V]) Cap() int {
return c.size
}
}