-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru.go
66 lines (55 loc) · 1.02 KB
/
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
package main
import (
"container/list"
"sync"
)
type LRU struct {
cap int
list *list.List
elem map[string]*list.Element
m sync.Mutex
}
type element struct {
key string
value *Record
}
func NewLRU(cap int) *LRU {
return &LRU{
cap: cap,
list: list.New(),
elem: make(map[string]*list.Element),
}
}
func (l *LRU) Get(key string) (*Record, bool) {
l.m.Lock()
defer l.m.Unlock()
if e, ok := l.elem[key]; ok {
v := e.Value
l.list.MoveToFront(e)
return v.(*element).value, true
}
return nil, false
}
func (l *LRU) Put(key string, r *Record) {
l.m.Lock()
defer l.m.Unlock()
e := &element{key: key, value: r}
l.list.PushFront(e)
l.elem[key] = l.list.Front()
if l.list.Len() > l.cap {
evicted := l.list.Back()
delete(l.elem, evicted.Value.(*element).key)
l.list.Remove(evicted)
}
}
func (l *LRU) Keys() []string {
l.m.Lock()
defer l.m.Unlock()
keys := make([]string, l.list.Len())
i := 0
for e := l.list.Front(); e != nil; e = e.Next() {
keys[i] = e.Value.(*element).key
i++
}
return keys
}