generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
73 lines (63 loc) · 1.31 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
package hw04lrucache
import (
"sync"
)
// Key is type of string.
type Key string
// Cache is interface of cache.
type Cache interface {
Set(key Key, value interface{}) bool
Get(key Key) (interface{}, bool)
Clear()
}
type lruCache struct {
mu sync.Mutex
capacity int
queue List
items map[Key]*ListItem
}
type cacheItem struct {
key Key
value interface{}
}
func (c *lruCache) Set(key Key, value interface{}) bool {
c.mu.Lock()
defer c.mu.Unlock()
item, ok := c.items[key]
if ok {
item.Value = cacheItem{key, value}
c.items[key] = item
c.queue.MoveToFront(item)
}
item = c.queue.PushFront(cacheItem{key, value})
c.items[key] = item
if c.queue.Len() > c.capacity {
lastItem := c.queue.Back()
c.queue.Remove(lastItem)
keyCI := lastItem.Value.(cacheItem).key
delete(c.items, keyCI)
}
return ok
}
func (c *lruCache) Get(key Key) (interface{}, bool) {
c.mu.Lock()
defer c.mu.Unlock()
item, ok := c.items[key]
if ok {
c.queue.MoveToFront(item)
return item.Value.(cacheItem).value, ok
}
return nil, ok
}
func (c *lruCache) Clear() {
c.items = make(map[Key]*ListItem)
c.queue = NewList()
}
// NewCache make a new chache instance.
func NewCache(capacity int) Cache {
return &lruCache{
capacity: capacity,
queue: NewList(),
items: make(map[Key]*ListItem, capacity),
}
}