| 1 |
package lfu |
| 2 |
|
| 3 |
import ( |
| 4 |
"container/heap" |
| 5 |
) |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 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 |
|
| 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 |
|
| 33 |
func WithCapacity(cap int) Option { |
| 34 |
return func(o *options) { |
| 35 |
o.capacity = cap |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
|
| 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 |
|
| 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 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 103 |
func (c *Cache[K, V]) Len() int { |
| 104 |
return c.queue.Len() |
| 105 |
} |