| 1 |
package fifo |
| 2 |
|
| 3 |
import ( |
| 4 |
"container/list" |
| 5 |
) |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
type Cache[K comparable, V any] struct { |
| 12 |
items map[K]*list.Element |
| 13 |
queue *list.List |
| 14 |
capacity int |
| 15 |
} |
| 16 |
|
| 17 |
type entry[K comparable, V any] struct { |
| 18 |
key K |
| 19 |
val V |
| 20 |
} |
| 21 |
|
| 22 |
|
| 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 |
|
| 36 |
func WithCapacity(cap int) Option { |
| 37 |
return func(o *options) { |
| 38 |
o.capacity = cap |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
|
| 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 |
|
| 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) |
| 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 |
|
| 71 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
} |