| 1 |
package lfu |
| 2 |
|
| 3 |
import ( |
| 4 |
"container/heap" |
| 5 |
"time" |
| 6 |
|
| 7 |
"github.com/Code-Hex/go-generics-cache/policy/internal/policyutil" |
| 8 |
) |
| 9 |
|
| 10 |
type entry[K comparable, V any] struct { |
| 11 |
index int |
| 12 |
key K |
| 13 |
val V |
| 14 |
referenceCount int |
| 15 |
referencedAt time.Time |
| 16 |
} |
| 17 |
|
| 18 |
func newEntry[K comparable, V any](key K, val V) *entry[K, V] { |
| 19 |
return &entry[K, V]{ |
| 20 |
index: 0, |
| 21 |
key: key, |
| 22 |
val: val, |
| 23 |
referenceCount: policyutil.GetReferenceCount(val), |
| 24 |
referencedAt: time.Now(), |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
func (e *entry[K, V]) referenced() { |
| 29 |
e.referenceCount++ |
| 30 |
e.referencedAt = time.Now() |
| 31 |
} |
| 32 |
|
| 33 |
type priorityQueue[K comparable, V any] []*entry[K, V] |
| 34 |
|
| 35 |
func newPriorityQueue[K comparable, V any](cap int) *priorityQueue[K, V] { |
| 36 |
queue := make(priorityQueue[K, V], 0, cap) |
| 37 |
return &queue |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
var _ heap.Interface = (*priorityQueue[struct{}, interface{}])(nil) |
| 42 |
|
| 43 |
func (q priorityQueue[K, V]) Len() int { return len(q) } |
| 44 |
|
| 45 |
func (q priorityQueue[K, V]) Less(i, j int) bool { |
| 46 |
if q[i].referenceCount == q[j].referenceCount { |
| 47 |
return q[i].referencedAt.Before(q[j].referencedAt) |
| 48 |
} |
| 49 |
return q[i].referenceCount < q[j].referenceCount |
| 50 |
} |
| 51 |
|
| 52 |
func (q priorityQueue[K, V]) Swap(i, j int) { |
| 53 |
if len(q) < 2 { |
| 54 |
return |
| 55 |
} |
| 56 |
q[i], q[j] = q[j], q[i] |
| 57 |
q[i].index = i |
| 58 |
q[j].index = j |
| 59 |
} |
| 60 |
|
| 61 |
func (q *priorityQueue[K, V]) Push(x interface{}) { |
| 62 |
entry := x.(*entry[K, V]) |
| 63 |
entry.index = len(*q) |
| 64 |
*q = append(*q, entry) |
| 65 |
} |
| 66 |
|
| 67 |
func (q *priorityQueue[K, V]) Pop() interface{} { |
| 68 |
old := *q |
| 69 |
n := len(old) |
| 70 |
if n == 0 { |
| 71 |
return nil |
| 72 |
} |
| 73 |
entry := old[n-1] |
| 74 |
old[n-1] = nil |
| 75 |
entry.index = -1 |
| 76 |
new := old[0 : n-1] |
| 77 |
*q = new |
| 78 |
return entry |
| 79 |
} |
| 80 |
|
| 81 |
func (q *priorityQueue[K, V]) update(e *entry[K, V], val V) { |
| 82 |
e.val = val |
| 83 |
e.referenced() |
| 84 |
heap.Fix(q, e.index) |
| 85 |
} |