package core import ( "container/list" "sync" ) // LRU is a bounded cache of module results keyed on immutable commit SHAs. // Bounded by entry COUNT, not bytes -- a diff of a huge commit and a ref // list cost the same one slot. If that bites, swap in a size-aware cache; // the Store interface is the only thing that has to hold. type LRU struct { mu sync.Mutex max int ll *list.List items map[string]*list.Element } type lruEntry struct { key string val any } func NewLRU(max int) *LRU { if max <= 0 { max = 2048 } return &LRU{max: max, ll: list.New(), items: map[string]*list.Element{}} } func (c *LRU) Get(key string) (any, bool) { c.mu.Lock() defer c.mu.Unlock() if el, ok := c.items[key]; ok { c.ll.MoveToFront(el) return el.Value.(*lruEntry).val, true } return nil, false } func (c *LRU) Put(key string, val any) { c.mu.Lock() defer c.mu.Unlock() if el, ok := c.items[key]; ok { c.ll.MoveToFront(el) el.Value.(*lruEntry).val = val return } c.items[key] = c.ll.PushFront(&lruEntry{key, val}) for c.ll.Len() > c.max { old := c.ll.Back() c.ll.Remove(old) delete(c.items, old.Value.(*lruEntry).key) } } func (c *LRU) Len() int { c.mu.Lock() defer c.mu.Unlock() return c.ll.Len() }