Debian Codegraph @

policy/lfu/lfu.go

raw symbols SCIP
1 package lfu
2
3 import (
4 "container/heap"
5 )
6
7 // Cache is used a LFU (Least-frequently used) cache replacement policy.
8 //
9 // Counts how often an item is needed. Those that are used least often are discarded first.
10 // This works very similar to LRU except that instead of storing the value of how recently
11 // a block was accessed, we store the value of how many times it was accessed. So of course
12 // while running an access sequence we will replace a block which was used fewest times from our cache.
13 type Cache[K comparable, V any] struct {
14 cap int
15 queue *priorityQueue[K, V]
16 items map[K]*entry[K, V]
17 }
18
19 // Option is an option for LFU cache.
20 type Option func(*options)
21
22 type options struct {
23 capacity int
24 }
25
26 func newOptions() *options {
27 return &options{
28 capacity: 128,
29 }
30 }
31
32 // WithCapacity is an option to set cache capacity.
33 func WithCapacity(cap int) Option {
34 return func(o *options) {
35 o.capacity = cap
36 }
37 }
38
39 // NewCache creates a new non-thread safe LFU cache whose capacity is the default size (128).
40 func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] {
41 o := newOptions()
42 for _, optFunc := range opts {
43 optFunc(o)
44 }
45 return &Cache[K, V]{
46 cap: o.capacity,
47 queue: newPriorityQueue[K, V](o.capacity),
48 items: make(map[K]*entry[K, V], o.capacity),
49 }
50 }
51
52 // Get looks up a key's value from the cache.
53 func (c *Cache[K, V]) Get(key K) (zero V, _ bool) {
54 e, ok := c.items[key]
55 if !ok {
56 return
57 }
58 e.referenced()
59 heap.Fix(c.queue, e.index)
60 return e.val, true
61 }
62
63 // Set sets a value to the cache with key. replacing any existing value.
64 //
65 // If value satisfies "interface{ GetReferenceCount() int }", the value of
66 // the GetReferenceCount() method is used to set the initial value of reference count.
67 func (c *Cache[K, V]) Set(key K, val V) {
68 if e, ok := c.items[key]; ok {
69 c.queue.update(e, val)
70 return
71 }
72
73 if len(c.items) == c.cap {
74 evictedEntry := heap.Pop(c.queue)
75 if evictedEntry != nil {
76 delete(c.items, evictedEntry.(*entry[K, V]).key)
77 }
78 }
79
80 e := newEntry(key, val)
81 heap.Push(c.queue, e)
82 c.items[key] = e
83 }
84
85 // Keys returns the keys of the cache. the order is from oldest to newest.
86 func (c *Cache[K, V]) Keys() []K {
87 keys := make([]K, 0, len(c.items))
88 for _, entry := range *c.queue {
89 keys = append(keys, entry.key)
90 }
91 return keys
92 }
93
94 // Delete deletes the item with provided key from the cache.
95 func (c *Cache[K, V]) Delete(key K) {
96 if e, ok := c.items[key]; ok {
97 heap.Remove(c.queue, e.index)
98 delete(c.items, key)
99 }
100 }
101
102 // Len returns the number of items in the cache.
103 func (c *Cache[K, V]) Len() int {
104 return c.queue.Len()
105 }