-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
59 lines (42 loc) · 907 Bytes
/
example_test.go
File metadata and controls
59 lines (42 loc) · 907 Bytes
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
package hashqueue
type Cache interface {
Put(key string, val interface{})
Get(key string) (val interface{}, exists bool)
Keys() map[string]struct{}
}
type lru struct {
hq *HashQueue
maxCap, extCap int
}
func NewLRU(maxCap, extCap int) Cache {
return &lru{
hq: New(),
maxCap: maxCap,
extCap: extCap,
}
}
func (t *lru) gc() {
if t.hq.Len() > t.extCap {
for t.hq.Len() > t.maxCap { // while over capacity
t.hq.PopBack()
}
}
}
func (t *lru) Put(key string, val interface{}) {
t.hq.PushFront(key, val)
t.gc() // try gc
return
}
func (t *lru) Get(key string) (val interface{}, exists bool) {
if val, exists = t.hq.Get(key); exists {
t.hq.MoveToFront(key) // move to front of lru
}
return
}
func (t *lru) Keys() map[string]struct{} {
keys := make(map[string]struct{})
for _, k := range t.hq.Keys() {
keys[string(k)] = struct{}{}
}
return keys
}