-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlow_lfu.go
115 lines (105 loc) · 2.16 KB
/
low_lfu.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package gcache
// NewLowLFU create a low-level lfu, use NewLFU unless you know exactly what you are doing.
func NewLowLFU(opt ...LowLFUOption) LowCache {
opts := defaultLowLFUOptions
for _, o := range opt {
o.apply(&opts)
}
if opts.expiry > 0 {
return newLowLFUEx(opts.capacity, opts.expiry)
}
return newLowLFU(opts.capacity)
}
type lowLFU struct {
keys map[interface{}]lfuValue
hot *lfuHeap
capacity int
}
func newLowLFU(capacity int) *lowLFU {
return &lowLFU{
keys: make(map[interface{}]lfuValue, capacity),
hot: newLFUHeap(capacity),
capacity: capacity,
}
}
func (l *lowLFU) ClearExpired() {
}
// Add the value to the cache, only when the key does not exist
func (l *lowLFU) Add(key, value interface{}) (added bool) {
_, exists := l.keys[key]
if !exists {
added = true
l.add(key, value)
}
return
}
func (l *lowLFU) add(key, value interface{}) (delkey, delval interface{}, deleted bool) {
// capacity limit reached, pop
if l.hot.Len() >= l.capacity {
deleted = true
v := l.hot.Remove(0)
delkey = v.GetKey()
delval = v.GetValue()
delete(l.keys, delkey)
}
// new value
v := newLFUValue(key, value, 0)
l.keys[key] = v
l.hot.Push(v)
return
}
func (l *lowLFU) moveHot(v lfuValue) {
v.Increment()
l.hot.Fix(v.GetIndex())
}
func (l *lowLFU) Put(key, value interface{}) (delkey, delval interface{}, deleted bool) {
v, exists := l.keys[key]
if exists {
deleted = true
delkey = key
delval = v.GetValue()
// put
v.SetValue(value)
// move hot
l.moveHot(v)
} else {
delkey, delval, deleted = l.add(key, value)
}
return
}
// Get return cache value
func (l *lowLFU) Get(key interface{}) (value interface{}, exists bool) {
v, exists := l.keys[key]
if !exists {
return
}
value = v.GetValue()
// move hot
l.moveHot(v)
return
}
func (l *lowLFU) Delete(key ...interface{}) (changed int) {
var (
v lfuValue
exists bool
)
for _, k := range key {
v, exists = l.keys[k]
if exists {
changed++
delete(l.keys, k)
l.hot.Remove(v.GetIndex())
}
}
return
}
func (l *lowLFU) Len() int {
return l.hot.Len()
}
func (l *lowLFU) Clear() {
l.hot.Clear()
for k := range l.keys {
delete(l.keys, k)
}
return
}