-
Notifications
You must be signed in to change notification settings - Fork 37
/
lru.go
71 lines (61 loc) · 1.25 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
67
68
69
70
71
package main
import (
"container/list"
"fmt"
"sync"
)
type LruCache struct {
size int
values *list.List
cacheMap map[interface{}]*list.Element
lock sync.Mutex
}
func NewLruList(size int) *LruCache {
values := list.New()
return &LruCache{
size: size,
values: values,
cacheMap: make(map[interface{}]*list.Element, size),
}
}
func (l *LruCache) Put(k, v interface{}) {
l.lock.Lock()
defer l.lock.Unlock()
if l.values.Len() == l.size {
back := l.values.Back()
l.values.Remove(back)
delete(l.cacheMap, back)
}
front := l.values.PushFront(v)
l.cacheMap[k] = front
}
func (l *LruCache) Get(k interface{}) (interface{}, bool) {
v, ok := l.cacheMap[k]
if ok {
l.values.MoveToFront(v)
return v, true
} else {
return nil, false
}
}
func (l *LruCache) Size() int {
return l.values.Len()
}
func (l *LruCache) String() {
for i := l.values.Front(); i != nil; i = i.Next() {
fmt.Print(i.Value, "\t")
}
}
func (l *LruCache) List() []interface{} {
var data []interface{}
for i := l.values.Front(); i != nil; i = i.Next() {
data = append(data, i.Value)
}
return data
}
func (l *LruCache) Clear() {
l.lock.Lock()
defer l.lock.Unlock()
l.values = list.New()
l.cacheMap = make(map[interface{}]*list.Element, l.size)
}