This repository has been archived by the owner on Sep 29, 2020. It is now read-only.
generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
80 lines (68 loc) · 1.36 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
79
80
package hw04_lru_cache //nolint:golint,stylecheck
import "sync"
// Cache ...
type Cache interface {
Set(key string, value interface{}) bool
Get(key string) (interface{}, bool)
Clear()
}
type lruCache struct {
cap int
queue List
cacheMap map[string]cacheItem
mux sync.Mutex
}
func (c *lruCache) Set(key string, value interface{}) bool {
c.mux.Lock()
defer c.mux.Unlock()
if item, ok := c.cacheMap[key]; ok {
c.queue.MoveToFront(item.qPointer)
item.val = value
c.cacheMap[key] = item
return ok
}
cItem := cacheItem{
val: value,
qPointer: c.queue.PushFront(key),
}
c.cacheMap[key] = cItem
c.rotate()
return false
}
func (c *lruCache) Get(key string) (interface{}, bool) {
c.mux.Lock()
defer c.mux.Unlock()
v, ok := c.cacheMap[key]
if ok {
c.queue.MoveToFront(v.qPointer)
}
return v.val, ok
}
func (c *lruCache) rotate() {
if c.queue.Len() <= c.cap {
return
}
elem := c.queue.Back()
if elem != nil {
delete(c.cacheMap, elem.Value.(string))
c.queue.Remove(elem)
}
}
func (c *lruCache) Clear() {
c.mux.Lock()
defer c.mux.Unlock()
c.queue = NewList()
c.cacheMap = make(map[string]cacheItem)
}
type cacheItem struct {
val interface{}
qPointer *listItem
}
// NewCache ...
func NewCache(capacity int) Cache {
return &lruCache{
cap: capacity,
queue: NewList(),
cacheMap: make(map[string]cacheItem),
}
}