-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru.go
99 lines (84 loc) · 2.26 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
90
91
92
93
94
95
96
97
98
99
package main
import (
"container/list"
"fmt"
)
//LRUCache definition for Least Recently Used Cache implementation.
type LRUCache struct {
capacity int //defines a cache object of the specified capacity.
list *list.List //DoublyLinkedList for backing the cache value.
elements map[int]*list.Element //Map to store list pointer of cache mapped to key
}
//KeyPair: defines the cache structure to be stored in LRUCache
type KeyPair struct {
key int
value int
}
//New: creates a new LRUCache object with the defined capacity
func New(capacity int) LRUCache {
return LRUCache{
capacity: capacity,
list: new(list.List),
elements: make(map[int]*list.Element, capacity),
}
}
func (cache *LRUCache) Get(key int) int {
if node, ok := cache.elements[key]; ok {
value := node.Value.(*list.Element).Value.(KeyPair).value
cache.list.MoveToFront(node)
return value
}
return -1
}
func (cache *LRUCache) Put(key int, value int) {
if node, ok := cache.elements[key]; ok {
node.Value.(*list.Element).Value = KeyPair{key: key, value: value}
cache.list.MoveToFront(node)
return
} else {
if cache.list.Len() == cache.capacity {
idx := cache.list.Back().Value.(*list.Element).Value.(KeyPair).key
delete(cache.elements, idx)
cache.list.Remove(cache.list.Back())
}
}
node := &list.Element{
Value: KeyPair{
key: key,
value: value,
},
}
pointer := cache.list.PushFront(node)
cache.elements[key] = pointer
}
func (cache *LRUCache) Print() {
for key, value := range cache.elements {
fmt.Printf("Key:%d,Value:%+v\n", key, value.Value.(*list.Element).Value.(KeyPair).value)
}
}
//Keys: returns all the keys present in LRUCache
func (cache *LRUCache) Keys() []interface{} {
var keys []interface{}
for k := range cache.elements {
keys = append(keys, k)
}
return keys
}
func (cache *LRUCache) RecentlyUsed() interface{} {
return cache.list.Front().Value.(*list.Element).Value.(KeyPair).value
}
//Remove: removes the entry for the respective key
func (cache *LRUCache) Remove(key int) {
if node, ok := cache.elements[key]; ok {
delete(cache.elements, key)
cache.list.Remove(node)
}
}
//Purge: clears LRUCache
func (cache *LRUCache) Purge() {
cache.capacity = 0
cache.elements = nil
cache.list = nil
}
func main() {
}