generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
78 lines (61 loc) · 1.34 KB
/
cache.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
package hw04lrucache
import "sync"
type Key string
type Cache interface {
Set(key Key, value interface{}) bool
Get(key Key) (interface{}, bool)
Clear()
}
type keyValuePair struct {
key Key
value interface{}
}
type lruCache struct {
Cache // Remove me after realization.
capacity int
queue List
items map[Key]*ListItem
mtx sync.RWMutex
}
func NewCache(capacity int) Cache {
return &lruCache{
capacity: capacity,
queue: NewList(),
items: make(map[Key]*ListItem, capacity),
}
}
func (lc *lruCache) Set(key Key, value interface{}) bool {
lc.mtx.Lock()
defer lc.mtx.Unlock()
item, found := lc.items[key]
if found {
lc.queue.PushFront(item)
item.Value = keyValuePair{key, value}
return true
}
for lc.queue.Len() >= lc.capacity {
itemToDelete := lc.queue.Back()
keyToDelete := itemToDelete.Value.(keyValuePair).key
delete(lc.items, keyToDelete)
lc.queue.Remove(itemToDelete)
}
item = lc.queue.PushFront(keyValuePair{key, value})
lc.items[key] = item
return false
}
func (lc *lruCache) Get(key Key) (interface{}, bool) {
lc.mtx.RLock()
defer lc.mtx.RUnlock()
item, ok := lc.items[key]
if ok {
lc.queue.MoveToFront(item)
return item.Value.(keyValuePair).value, true
}
return nil, false
}
func (lc *lruCache) Clear() {
lc.mtx.Lock()
defer lc.mtx.Unlock()
clear(lc.items)
lc.queue = NewList()
}