Debian Codegraph @

policy/mru/mru.go

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