-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
executable file
·76 lines (67 loc) · 1.42 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
package lrucache
import "sync"
type Key string
type Cache interface {
Set(key Key, value interface{}) bool
Get(key Key) (interface{}, bool)
Clear()
}
type lruCache struct {
capacity int
queue List
items map[Key]*ListItem
mutex *sync.Mutex
}
type cacheItem struct {
key Key
value interface{}
}
func (l *lruCache) Set(key Key, value interface{}) bool {
l.mutex.Lock()
defer l.mutex.Unlock()
tempCacheItem := cacheItem{
key: key,
value: value,
}
var isExist bool
if item, ok := l.items[key]; ok {
item.Value = tempCacheItem
l.queue.MoveToFront(item)
isExist = true
return isExist
} else {
item := l.queue.PushFront(tempCacheItem)
l.items[key] = item
if l.queue.Len() > l.capacity {
lastItem := l.queue.Back()
l.queue.Remove(lastItem)
delete(l.items, lastItem.Value.(cacheItem).key)
}
isExist = false
return isExist
}
}
func (l *lruCache) Get(key Key) (interface{}, bool) {
l.mutex.Lock()
defer l.mutex.Unlock()
var isExist bool
if item, ok := l.items[key]; ok {
l.queue.MoveToFront(item)
isExist = true
return l.queue.Front().Value.(cacheItem).value, isExist
}
isExist = false
return nil, isExist
}
func (l *lruCache) Clear() {
l.queue = NewList()
l.items = make(map[Key]*ListItem, l.capacity)
}
func NewCache(capacity int) Cache {
return &lruCache{
capacity: capacity,
queue: NewList(),
items: make(map[Key]*ListItem, capacity),
mutex: &sync.Mutex{},
}
}