Skip to content

Commit

Permalink
Fix: encountering expired items during the traversal process will res…
Browse files Browse the repository at this point in the history
…ult in zero values in the output. (#163)
  • Loading branch information
DCjanus committed Jan 10, 2024
1 parent 97f49b4 commit 53739fc
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions expirable/expirable_lru.go
Expand Up @@ -220,11 +220,16 @@ func (c *LRU[K, V]) GetOldest() (key K, value V, ok bool) {
}

// Keys returns a slice of the keys in the cache, from oldest to newest.
// Expired entries are filtered out.
func (c *LRU[K, V]) Keys() []K {
c.mu.Lock()
defer c.mu.Unlock()
keys := make([]K, 0, len(c.items))
now := time.Now()
for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() {
if now.After(ent.ExpiresAt) {
continue
}
keys = append(keys, ent.Key)
}
return keys
Expand All @@ -235,15 +240,13 @@ func (c *LRU[K, V]) Keys() []K {
func (c *LRU[K, V]) Values() []V {
c.mu.Lock()
defer c.mu.Unlock()
values := make([]V, len(c.items))
i := 0
values := make([]V, 0, len(c.items))
now := time.Now()
for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() {
if now.After(ent.ExpiresAt) {
continue
}
values[i] = ent.Value
i++
values = append(values, ent.Value)
}
return values
}
Expand Down

0 comments on commit 53739fc

Please sign in to comment.