package lru import ( "container/list" "testing" ) type entry[K comparable, V any] struct { key K value V } // Cache stores up to capacity entries, evicting the least recently used. type Cache[K comparable, V any] struct { capacity int items map[K]*list.Element order *list.List } // New creates an LRU cache. A non-positive capacity stores no entries. func New[K comparable, V any](capacity int) *Cache[K, V] { return &Cache[K, V]{ capacity: capacity, items: make(map[K]*list.Element), order: list.New(), } } // Get returns a value and marks its key as most recently used. func (c *Cache[K, V]) Get(key K) (V, bool) { if element, ok := c.items[key]; ok { c.order.MoveToFront(element) return element.Value.(entry[K, V]).value, true } var zero V return zero, false } // Put inserts or updates a value. func (c *Cache[K, V]) Put(key K, value V) { if c.capacity <= 0 { return } if element, ok := c.items[key]; ok { element.Value = entry[K, V]{key: key, value: value} c.order.MoveToFront(element) return } element := c.order.PushFront(entry[K, V]{key: key, value: value}) c.items[key] = element if c.order.Len() > c.capacity { oldest := c.order.Back() evicted := oldest.Value.(entry[K, V]) delete(c.items, evicted.key) c.order.Remove(oldest) } } // Len returns the number of cached entries. func (c *Cache[K, V]) Len() int { return c.order.Len() } func TestCacheEvictsLeastRecentlyUsed(t *testing.T) { cache := New[string, int](2) cache.Put("a", 1) cache.Put("b", 2) cache.Get("a") 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, got %v, %v", value, ok) } } func TestCacheUpdatesExistingEntry(t *testing.T) { cache := New[string, int](1) cache.Put("a", 1) cache.Put("a", 2) if cache.Len() != 1 { t.Fatalf("expected length 1, got %d", cache.Len()) } if value, ok := cache.Get("a"); !ok || value != 2 { t.Fatalf("expected a=2, got %v, %v", value, ok) } }