-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolicy_lru.go
69 lines (60 loc) · 1.21 KB
/
policy_lru.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
package localcache
import (
"github.com/MoeYang/go-localcache/datastruct/list"
)
type policyLRU struct {
cap int
cache *localCache // the cache obj
list *list.List
}
func newPolicyLRU(cap int, cache *localCache) policy {
return &policyLRU{
cap: cap,
cache: cache,
list: list.New(),
}
}
func (p *policyLRU) add(obj interface{}) {
ele, ok := obj.(*list.Element)
if !ok {
return
}
// need to del when list is full
if p.list.Len() >= p.cap {
lastEle := p.list.Back()
if lastEle != nil {
// del from cache
p.cache.del(lastEle.Value.(*element).key)
}
}
// push ele to first of list
p.list.PushElementFront(ele)
}
func (p *policyLRU) hit(obj interface{}) {
ele, ok := obj.(*list.Element)
if !ok {
return
}
p.list.MoveToFront(ele)
}
func (p *policyLRU) del(obj interface{}) {
ele, ok := obj.(*list.Element)
if !ok {
return
}
p.list.Remove(ele)
}
func (p *policyLRU) flush() {
p.list = list.New()
}
// unpack decode a *list.Element and return *element
func (p *policyLRU) unpack(obj interface{}) *element {
ele, ok := obj.(*list.Element)
if !ok {
return nil
}
return ele.Value.(*element)
}
func (p *policyLRU) pack(ele *element) interface{} {
return p.list.NewElement(ele)
}