fix: invoke the LRU eviction callback

NewLRUCacheWithOnEvict accepted an onEvict func and discarded it: the struct
held no such field and Put never called it, so every caller passing a callback
got silence. Store it and call it on capacity eviction. The root package had no
tests; these cover the callback, LRU recency, and the nil-callback path.
This commit is contained in:
2026-08-21 00:11:43 -07:00
parent c115555b50
commit 9502dbf6e9
2 changed files with 62 additions and 1 deletions
+7 -1
View File
@@ -11,6 +11,7 @@ type LRUCache[K comparable, V any] struct {
capacity int
elements map[K]*list.Element
lru *list.List
onEvict func(K, V)
}
// NewLRUCache creates a new LRU cache
@@ -32,6 +33,7 @@ func NewLRUCacheWithOnEvict[K comparable, V any](size int, onEvict func(K, V)) *
capacity: size,
elements: make(map[K]*list.Element),
lru: list.New(),
onEvict: onEvict,
}
}
@@ -55,7 +57,11 @@ func (c *LRUCache[K, V]) Put(key K, value V) {
back := c.lru.Back()
if back != nil {
c.lru.Remove(back)
delete(c.elements, back.Value.(*cacheEntry[K, V]).key)
evicted := back.Value.(*cacheEntry[K, V])
delete(c.elements, evicted.key)
if c.onEvict != nil {
c.onEvict(evicted.key, evicted.value)
}
}
}
+55
View File
@@ -0,0 +1,55 @@
// Copyright (C) 2019-2025, Lux Industries, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package container
import "testing"
func TestLRUCacheEvictsLeastRecentlyUsed(t *testing.T) {
c := NewLRUCache[string, int](2)
c.Put("a", 1)
c.Put("b", 2)
c.Get("a") // "b" is now the least recently used
c.Put("c", 3)
if _, ok := c.Get("b"); ok {
t.Error("b should have been evicted")
}
if v, ok := c.Get("a"); !ok || v != 1 {
t.Errorf("a = %v, %v; want 1, true", v, ok)
}
if got := c.Len(); got != 2 {
t.Errorf("Len = %d; want 2", got)
}
}
func TestLRUCacheOnEvict(t *testing.T) {
type entry struct {
key string
val int
}
var got []entry
c := NewLRUCacheWithOnEvict(2, func(k string, v int) {
got = append(got, entry{k, v})
})
c.Put("a", 1)
c.Put("b", 2)
if len(got) != 0 {
t.Fatalf("evicted %v before capacity was exceeded", got)
}
c.Put("c", 3)
if len(got) != 1 {
t.Fatalf("got %d evictions; want 1", len(got))
}
if got[0] != (entry{"a", 1}) {
t.Errorf("evicted %v; want {a 1}", got[0])
}
}
func TestLRUCacheNilOnEvict(t *testing.T) {
c := NewLRUCache[string, int](1)
c.Put("a", 1)
c.Put("b", 2) // must not panic evicting "a" with no callback set
}