-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU.go
89 lines (79 loc) · 1.84 KB
/
LRU.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
package hashmap
import (
"errors"
"github.com/zawlinnnaing/data-structures-algorithms-go/src/linkedlists/doubly"
)
type LRU[K comparable, V comparable] struct {
length int
lookup map[K]*doubly.DoublyNode[V]
reverseLookup map[*doubly.DoublyNode[V]]K
head *doubly.DoublyNode[V]
tail *doubly.DoublyNode[V]
capacity int
}
func (cache *LRU[K, V]) Get(key K) (value V, err error) {
node := cache.lookup[key]
if node == nil {
return value, errors.New("Value not found")
}
cache.detach(node)
cache.prepend(node)
return node.Data, err
}
func (cache *LRU[K, V]) Update(key K, value V) {
node := cache.lookup[key]
if node == nil {
node = doubly.NewNode[V](value)
cache.prepend(node)
cache.length += 1
cache.lookup[key] = node
cache.reverseLookup[node] = key
cache.trimCache()
} else {
cache.detach(node)
cache.prepend(node)
node.Data = value
}
}
func (cache *LRU[K, V]) detach(node *doubly.DoublyNode[V]) {
if node.Prev != nil {
node.Prev.Next = node.Next
}
if node.Next != nil {
node.Next.Prev = node.Prev
}
if cache.head == node {
cache.head = node.Next
}
if cache.tail == node {
cache.tail = node.Prev
}
node.Next = nil
node.Prev = nil
}
func (cache *LRU[K, V]) prepend(node *doubly.DoublyNode[V]) {
if cache.head == nil {
cache.head = node
cache.tail = node
return
}
node.Next = cache.head
cache.head.Prev = node
}
func (cache *LRU[K, V]) trimCache() {
if cache.length <= cache.capacity {
return
}
key := cache.reverseLookup[cache.tail]
delete(cache.lookup, key)
delete(cache.reverseLookup, cache.tail)
cache.detach(cache.tail)
}
func NewLRU[K comparable, V comparable](capacity int) *LRU[K, V] {
return &LRU[K, V]{
length: 0,
capacity: capacity,
reverseLookup: make(map[*doubly.DoublyNode[V]]K),
lookup: make(map[K]*doubly.DoublyNode[V]),
}
}