parent
d03f72f6c9
commit
d49f187da6
@ -0,0 +1,62 @@
|
||||
package lfu
|
||||
|
||||
import (
|
||||
"cache"
|
||||
"container/heap"
|
||||
)
|
||||
|
||||
type entry struct {
|
||||
key string
|
||||
value any
|
||||
//权重或优先级
|
||||
weight int
|
||||
//下标
|
||||
index int
|
||||
}
|
||||
|
||||
func (e *entry) Len() int {
|
||||
return cache.CalcLen(e.value) + 8
|
||||
}
|
||||
|
||||
type queue []*entry
|
||||
|
||||
// Len
|
||||
//
|
||||
// @Description: 长度
|
||||
// @receiver e
|
||||
// @return int
|
||||
func (q queue) Len() int {
|
||||
return len(q)
|
||||
}
|
||||
|
||||
func (q queue) Less(i, j int) bool {
|
||||
return q[i].weight < q[j].weight
|
||||
}
|
||||
|
||||
func (q queue) Swap(i, j int) {
|
||||
q[i], q[j] = q[j], q[i]
|
||||
q[i].index = i
|
||||
q[j].index = j
|
||||
}
|
||||
|
||||
func (q *queue) Push(x any) {
|
||||
n := len(*q)
|
||||
en := x.(*entry)
|
||||
en.index = n
|
||||
*q = append(*q, en)
|
||||
}
|
||||
|
||||
func (q *queue) Pop() any {
|
||||
old := *q
|
||||
n := len(old)
|
||||
en := old[n-1]
|
||||
en.index = -1
|
||||
*q = old[0 : n-1]
|
||||
return en
|
||||
}
|
||||
|
||||
func (q *queue) update(en *entry, value any, weight int) {
|
||||
en.value = value
|
||||
en.weight = weight
|
||||
heap.Fix(q, en.index)
|
||||
}
|
Loading…
Reference in new issue