-
Notifications
You must be signed in to change notification settings - Fork 92
/
lrucache.go
124 lines (102 loc) · 1.98 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package lrucache
import (
"container/list"
"sync"
"time"
)
type entry struct {
key string
value []byte
addedAt time.Time
}
type Cache struct {
mu sync.Mutex
list *list.List
table map[string]*list.Element
expiration time.Duration
maxLen int
}
func New(maxLen int, expiration time.Duration) *Cache {
return &Cache{
list: list.New(),
table: make(map[string]*list.Element, maxLen),
expiration: expiration,
maxLen: maxLen,
}
}
func (c *Cache) Get(key string) ([]byte, bool) {
return c.get(key)
}
func (c *Cache) get(key string) ([]byte, bool) {
c.mu.Lock()
el := c.table[key]
if el == nil {
c.mu.Unlock()
return nil, false
}
entry := el.Value.(*entry)
if time.Since(entry.addedAt) > c.expiration {
c.deleteElement(el)
c.mu.Unlock()
return nil, false
}
c.list.MoveToFront(el)
value := entry.value
c.mu.Unlock()
return value, true
}
func (c *Cache) Set(key string, value []byte) {
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) Delete(key string) bool {
c.mu.Lock()
defer c.mu.Unlock()
el := c.table[key]
if el == nil {
return false
}
c.deleteElement(el)
return true
}
func (c *Cache) Len() int {
return c.list.Len()
}
func (c *Cache) Flush() error {
c.mu.Lock()
c.list = list.New()
c.table = make(map[string]*list.Element, c.maxLen)
c.mu.Unlock()
return nil
}
func (c *Cache) addNew(key string, value []byte) {
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)
}
}