Debian Codegraph @

policy/lru/lru.go

raw symbols SCIP
1 package lru
2
3 import (
4 "container/list"
5 )
6
7 // Cache is used a LRU (Least recently used) cache replacement policy.
8 //
9 // Discards the least recently used items first. This algorithm requires
10 // keeping track of what was used when, which is expensive if one wants
11 // to make sure the algorithm always discards the least recently used item.
12 type Cache[K comparable, V any] struct {
13 cap int
14 list *list.List
15 items map[K]*list.Element
16 }
17
18 type entry[K comparable, V any] struct {
19 key K
20 val V
21 }
22
23 // Option is an option for LRU cache.
24 type Option func(*options)
25
26 type options struct {
27 capacity int
28 }
29
30 func newOptions() *options {
31 return &options{
32 capacity: 128,
33 }
34 }
35
36 // WithCapacity is an option to set cache capacity.
37 func WithCapacity(cap int) Option {
38 return func(o *options) {
39 o.capacity = cap
40 }
41 }
42
43 // NewCache creates a new non-thread safe LRU cache whose capacity is the default size (128).
44 func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] {
45 o := newOptions()
46 for _, optFunc := range opts {
47 optFunc(o)
48 }
49 return &Cache[K, V]{
50 cap: o.capacity,
51 list: list.New(),
52 items: make(map[K]*list.Element, o.capacity),
53 }
54 }
55
56 // Get looks up a key's value from the cache.
57 func (c *Cache[K, V]) Get(key K) (zero V, _ bool) {
58 e, ok := c.items[key]
59 if !ok {
60 return
61 }
62 // updates cache order
63 c.list.MoveToFront(e)
64 return e.Value.(*entry[K, V]).val, true
65 }
66
67 // Set sets a value to the cache with key. replacing any existing value.
68 func (c *Cache[K, V]) Set(key K, val V) {
69 if e, ok := c.items[key]; ok {
70 // updates cache order
71 c.list.MoveToFront(e)
72 entry := e.Value.(*entry[K, V])
73 entry.val = val
74 return
75 }
76
77 newEntry := &entry[K, V]{
78 key: key,
79 val: val,
80 }
81 e := c.list.PushFront(newEntry)
82 c.items[key] = e
83
84 if c.list.Len() > c.cap {
85 c.deleteOldest()
86 }
87 }
88
89 // Keys returns the keys of the cache. the order is from oldest to newest.
90 func (c *Cache[K, V]) Keys() []K {
91 keys := make([]K, 0, len(c.items))
92 for ent := c.list.Back(); ent != nil; ent = ent.Prev() {
93 entry := ent.Value.(*entry[K, V])
94 keys = append(keys, entry.key)
95 }
96 return keys
97 }
98
99 // Len returns the number of items in the cache.
100 func (c *Cache[K, V]) Len() int {
101 return c.list.Len()
102 }
103
104 // Delete deletes the item with provided key from the cache.
105 func (c *Cache[K, V]) Delete(key K) {
106 if e, ok := c.items[key]; ok {
107 c.delete(e)
108 }
109 }
110
111 func (c *Cache[K, V]) deleteOldest() {
112 e := c.list.Back()
113 c.delete(e)
114 }
115
116 func (c *Cache[K, V]) delete(e *list.Element) {
117 c.list.Remove(e)
118 entry := e.Value.(*entry[K, V])
119 delete(c.items, entry.key)
120 }