-
Notifications
You must be signed in to change notification settings - Fork 0
/
lrucache.go
91 lines (75 loc) · 1.46 KB
/
lrucache.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
package lrucache
import (
"container/list"
"sync"
"time"
)
type entry struct {
key string
value interface{}
addedAt time.Time
}
type Cache struct {
mu sync.Mutex
list *list.List
table map[string]*list.Element
maxLen int
}
func New(maxLen int) *Cache {
return &Cache{
list: list.New(),
table: make(map[string]*list.Element, maxLen),
maxLen: maxLen,
}
}
func (c *Cache) Get(key string) (interface{}, bool) {
return c.get(key)
}
func (c *Cache) get(key string) (interface{}, bool) {
c.mu.Lock()
el := c.table[key]
if el == nil {
c.mu.Unlock()
return nil, false
}
entry := el.Value.(*entry)
c.list.MoveToFront(el)
value := entry.value
c.mu.Unlock()
return value, true
}
func (c *Cache) Set(key string, value interface{}) {
c.mu.Lock()
if el := c.table[key]; el != nil {
entry := el.Value.(*entry)
entry.value = value
c.promote(el, entry)
} else {
c.addNew(key, value)
}
c.mu.Unlock()
}
func (c *Cache) addNew(key string, value interface{}) {
newEntry := &entry{
key: key,
value: value,
addedAt: time.Now(),
}
element := c.list.PushFront(newEntry)
c.table[key] = element
c.check()
}
func (c *Cache) promote(el *list.Element, entry *entry) {
entry.addedAt = time.Now()
c.list.MoveToFront(el)
}
func (c *Cache) deleteElement(el *list.Element) {
c.list.Remove(el)
delete(c.table, el.Value.(*entry).key)
}
func (c *Cache) check() {
for c.list.Len() > c.maxLen {
el := c.list.Back()
c.deleteElement(el)
}
}