Migration This is my new public git source viewer. Source coming soon. Please contact with concerns/bugs. Contact me

internal/core/cache.go

38fa4e6cd9bb9dbf0ae23ef02e50b1c75cd84ebb · 1.2 KB · 61 lines raw

1 package core
2
3 import (
4 "container/list"
5 "sync"
6 )
7
8 // LRU is a bounded cache of module results keyed on immutable commit SHAs.
9 // Bounded by entry COUNT, not bytes -- a diff of a huge commit and a ref
10 // list cost the same one slot. If that bites, swap in a size-aware cache;
11 // the Store interface is the only thing that has to hold.
12 type LRU struct {
13 mu sync.Mutex
14 max int
15 ll *list.List
16 items map[string]*list.Element
17 }
18
19 type lruEntry struct {
20 key string
21 val any
22 }
23
24 func NewLRU(max int) *LRU {
25 if max <= 0 {
26 max = 2048
27 }
28 return &LRU{max: max, ll: list.New(), items: map[string]*list.Element{}}
29 }
30
31 func (c *LRU) Get(key string) (any, bool) {
32 c.mu.Lock()
33 defer c.mu.Unlock()
34 if el, ok := c.items[key]; ok {
35 c.ll.MoveToFront(el)
36 return el.Value.(*lruEntry).val, true
37 }
38 return nil, false
39 }
40
41 func (c *LRU) Put(key string, val any) {
42 c.mu.Lock()
43 defer c.mu.Unlock()
44 if el, ok := c.items[key]; ok {
45 c.ll.MoveToFront(el)
46 el.Value.(*lruEntry).val = val
47 return
48 }
49 c.items[key] = c.ll.PushFront(&lruEntry{key, val})
50 for c.ll.Len() > c.max {
51 old := c.ll.Back()
52 c.ll.Remove(old)
53 delete(c.items, old.Value.(*lruEntry).key)
54 }
55 }
56
57 func (c *LRU) Len() int {
58 c.mu.Lock()
59 defer c.mu.Unlock()
60 return c.ll.Len()
61 }