-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru_cache.go
105 lines (80 loc) · 1.68 KB
/
lru_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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package lrucache
import (
"container/list"
"sync"
)
type ValueNode struct {
value any
node *list.Element
}
type LRUCache struct {
keys *list.List
data map[any]ValueNode
maxCapacity int
mu sync.RWMutex
}
func NewCache(maxCapacity int) LRUCache {
emptyMap := make(map[any]ValueNode)
l := list.New()
return LRUCache{keys: l, data: emptyMap, maxCapacity: maxCapacity}
}
func (c *LRUCache) Get(key any) (any, bool) {
c.mu.Lock()
defer c.mu.Unlock()
valueNode, ok := c.data[key]
if !ok {
return nil, false
}
// move the node to the front
c.keys.MoveToFront(valueNode.node)
return valueNode.value, true
}
func (c *LRUCache) Add(key, value any) {
c.mu.Lock()
defer c.mu.Unlock()
valueNode, ok := c.data[key]
// if key exists
if ok {
valueNode.value = value
c.data[key] = valueNode
c.keys.MoveToFront(valueNode.node)
return
}
// if key does not exists we need to check for the length and remove the least used one
if c.keys.Len() == c.maxCapacity {
if lastElem := c.keys.Back(); lastElem != nil {
delete(c.data, lastElem.Value)
c.keys.Remove(lastElem)
}
}
node := c.keys.PushFront(key)
newValueNode := ValueNode{
value: value,
node: node,
}
c.data[key] = newValueNode
}
func (c *LRUCache) Remove(key any) bool {
c.mu.Lock()
defer c.mu.Unlock()
valueNode, ok := c.data[key]
if !ok {
return false
}
c.keys.Remove(valueNode.node)
delete(c.data, key)
return true
}
func (c *LRUCache) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.keys.Len() // Wait for all goroutines to finish
}
func (c *LRUCache) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.keys.Init()
for k := range c.data {
delete(c.data, k)
}
}