Debian Codegraph @

policy/fifo/fifo.go

raw symbols SCIP
1 package fifo
2
3 import (
4 "container/list"
5 )
6
7 // Cache is used a FIFO (First in first out) cache replacement policy.
8 //
9 // In FIFO the item that enter the cache first is evicted first
10 // w/o any regard of how often or how many times it was accessed before.
11 type Cache[K comparable, V any] struct {
12 items map[K]*list.Element
13 queue *list.List // keys
14 capacity int
15 }
16
17 type entry[K comparable, V any] struct {
18 key K
19 val V
20 }
21
22 // Option is an option for FIFO cache.
23 type Option func(*options)
24
25 type options struct {
26 capacity int
27 }
28
29 func newOptions() *options {
30 return &options{
31 capacity: 128,
32 }
33 }
34
35 // WithCapacity is an option to set cache capacity.
36 func WithCapacity(cap int) Option {
37 return func(o *options) {
38 o.capacity = cap
39 }
40 }
41
42 // NewCache creates a new non-thread safe FIFO cache whose capacity is the default size (128).
43 func NewCache[K comparable, V any](opts ...Option) *Cache[K, V] {
44 o := newOptions()
45 for _, optFunc := range opts {
46 optFunc(o)
47 }
48 return &Cache[K, V]{
49 items: make(map[K]*list.Element, o.capacity),
50 queue: list.New(),
51 capacity: o.capacity,
52 }
53 }
54
55 // Set sets any item to the cache. replacing any existing item.
56 func (c *Cache[K, V]) Set(key K, val V) {
57 if c.queue.Len() == c.capacity {
58 e := c.dequeue()
59 delete(c.items, e.Value.(*entry[K, V]).key)
60 }
61 c.Delete(key) // delete old key if already exists specified key.
62 entry := &entry[K, V]{
63 key: key,
64 val: val,
65 }
66 e := c.queue.PushBack(entry)
67 c.items[key] = e
68 }
69
70 // Get gets an item from the cache.
71 // Returns the item or zero value, and a bool indicating whether the key was found.
72 func (c *Cache[K, V]) Get(k K) (val V, ok bool) {
73 got, found := c.items[k]
74 if !found {
75 return
76 }
77 return got.Value.(*entry[K, V]).val, true
78 }
79
80 // Keys returns cache keys.
81 func (c *Cache[K, V]) Keys() []K {
82 keys := make([]K, 0, len(c.items))
83 for e := c.queue.Front(); e != nil; e = e.Next() {
84 keys = append(keys, e.Value.(*entry[K, V]).key)
85 }
86 return keys
87 }
88
89 // Delete deletes the item with provided key from the cache.
90 func (c *Cache[K, V]) Delete(key K) {
91 if e, ok := c.items[key]; ok {
92 c.queue.Remove(e)
93 delete(c.items, key)
94 }
95 }
96
97 // Len returns the number of items in the cache.
98 func (c *Cache[K, V]) Len() int {
99 return c.queue.Len()
100 }
101
102 func (c *Cache[K, V]) dequeue() *list.Element {
103 e := c.queue.Front()
104 c.queue.Remove(e)
105 return e
106 }