-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplacer.cpp
More file actions
108 lines (98 loc) · 2.22 KB
/
Copy pathreplacer.cpp
File metadata and controls
108 lines (98 loc) · 2.22 KB
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
106
107
108
#include "replacer.h"
namespace diskmap {
LRUReplacer::LRUReplacer() : head(nullptr), tail(nullptr), size(0) {}
LRUReplacer::~LRUReplacer() {
while (head != nullptr) {
Node *temp = head;
head = head->next;
delete temp;
}
}
void LRUReplacer::insert(int val) {
if (map.find(val) == map.end()) {
Node *node = new Node(val);
map[val] = node;
if (head == nullptr) {
head = node;
tail = node;
} else {
node->next = head;
head->prev = node;
head = node;
}
size++;
return;
}
// val already exists, move to head
Node *node = map[val];
if (node == head) {
return;
}
if (node == tail) {
tail = node->prev;
tail->next = nullptr;
} else {
node->prev->next = node->next;
node->next->prev = node->prev;
}
node->next = head;
head->prev = node;
head = node;
}
bool LRUReplacer::remove(int val) {
auto result = map.find(val);
if (result == map.end()) {
return false;
}
Node *node = result->second;
if (node == head && node == tail) {
head = nullptr;
tail = nullptr;
} else if (node == head) {
head = node->next;
head->prev = nullptr;
} else if (node == tail) {
tail = node->prev;
tail->next = nullptr;
} else {
node->prev->next = node->next;
node->next->prev = node->prev;
}
map.erase(val);
delete node;
size--;
return true;
}
int LRUReplacer::evict() {
if (head == nullptr) {
return -1;
}
int val = tail->val;
remove(val);
return val;
}
void DualPriorityReplacer::insert(int val, bool advise_eviction) {
// Insert into the appropriate list, preferring the important list if both
// would otherwise contain val after insertion
if (advise_eviction) {
if (!important.contains(val)) {
unimportant.insert(val);
}
} else {
important.insert(val);
unimportant.remove(val);
}
}
bool DualPriorityReplacer::remove(int val) {
// Short-circuit || should work, and val should be found in at most one list
// Order doesn't matter here
return unimportant.remove(val) || important.remove(val);
}
int DualPriorityReplacer::evict() {
int result = unimportant.evict();
if (result != -1) {
return result;
}
return important.evict();
}
} // namespace diskmap