package lru import ( "container/list" "testing" ) type entry[K comparable, V any] struct { key K value V } // Cache is a fixed-capacity LRU cache. // Get and Put are O(1). type Cache[K comparable, V any] struct { capacity int items map[K]*list.Element order *list.List } // New creates an LRU cache that holds at most capacity entries. func New[K comparable, V any](capacity int) *Cache[K, V] { if capacity < 0 { capacity = 0 } return &Cache[K, V]{ capacity: capacity, items: make(map[K]*list.Element), order: list.New(), } } // Get returns a cached value and marks it as recently used. func (c *Cache[K, V]) Get(key K) (V, bool) { if elem, ok := c.items[key]; ok { c.order.MoveToFront(elem) return elem.Value.(entry[K, V]).value, true } var zero V return zero, false } // Put inserts or updates a value and evicts the least recently used entry // when the cache exceeds capacity. func (c *Cache[K, V]) Put(key K, value V) { if c.capacity == 0 { return } if elem, ok := c.items[key]; ok { elem.Value = entry[K, V]{key: key, value: value} c.order.MoveToFront(elem) return } elem := c.order.PushFront(entry[K, V]{key: key, value: value}) c.items[key] = elem if len(c.items) > c.capacity { c.evictOldest() } } // Len returns the number of entries currently stored. func (c *Cache[K, V]) Len() int { return len(c.items) } func (c *Cache[K, V]) evictOldest() { elem := c.order.Back() if elem == nil { return } c.order.Remove(elem) delete(c.items, elem.Value.(entry[K, V]).key) } func TestCacheEvictsLeastRecentlyUsed(t *testing.T) { cache := New[string, int](2) cache.Put("a", 1) cache.Put("b", 2) if value, ok := cache.Get("a"); !ok || value != 1 { t.Fatalf("expected a=1, got value=%d ok=%v", value, ok) } cache.Put("c", 3) if _, ok := cache.Get("b"); ok { t.Fatal("expected b to be evicted") } if value, ok := cache.Get("a"); !ok || value != 1 { t.Fatalf("expected a=1 to remain, got value=%d ok=%v", value, ok) } if value, ok := cache.Get("c"); !ok || value != 3 { t.Fatalf("expected c=3, got value=%d ok=%v", value, ok) } } func TestCacheUpdatesExistingEntry(t *testing.T) { cache := New[string, int](2) cache.Put("a", 1) cache.Put("b", 2) cache.Put("a", 10) cache.Put("c", 3) if value, ok := cache.Get("a"); !ok || value != 10 { t.Fatalf("expected updated a=10, got value=%d ok=%v", value, ok) } if _, ok := cache.Get("b"); ok { t.Fatal("expected b to be evicted") } if cache.Len() != 2 { t.Fatalf("expected len=2, got %d", cache.Len()) } }