-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkey_value_store.cpp
More file actions
95 lines (83 loc) · 1.96 KB
/
key_value_store.cpp
File metadata and controls
95 lines (83 loc) · 1.96 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
#include "key_value_store.h"
// Implementation of class "Value"
bool Value::isAvailable() {
return m_available;
}
string Value::getValue() {
return m_str;
}
void Value::setValue(string new_str) {
m_str = new_str;
}
void Value::setAvailability(bool avail) {
m_available = avail;
}
// Implementation of class "evictionFIFO"
size_t evictionFIFO::getSize() {
return evictionQueue.size();
}
string evictionFIFO::getFrontElement() {
return evictionQueue.front();
}
void evictionFIFO::updateEvictionQueue(string new_key) {
if(!evictionQueue.empty())
evict();
evictionQueue.push(new_key);
}
void evictionFIFO::pushEntry(string key) {
evictionQueue.push(key);
}
void evictionFIFO::evict() {
evictionQueue.pop();
}
// Implementation of class "mapDB"
string MapDB::get(string key) {
if (cache.count(key))
return cache[key].getValue();
else {
string value = m_file.read(key);
if (value != "\0") {
Value newValue;
newValue.setValue(value);
if (evictionTable.getSize() < evictionTableSize) {
evictionTable.pushEntry(key);
cache[key] = newValue;
}
else {
string key_to_remove = evictionTable.getFrontElement();
remove(key_to_remove);
evictionTable.updateEvictionQueue(key);
cache[key] = newValue;
}
}
return value;
}
}
void MapDB::set(string key, string value) {
Value newValue;
newValue.setAvailability(false);
newValue.setValue(value);
if (cache.count(key)) {
Value retrieved_value = cache[key];
if (retrieved_value.isAvailable()) {
cache[key] = newValue;
m_file.modify(key,value);
}
}
else {
if (evictionTable.getSize() == evictionTableSize) {
string key_to_evict = evictionTable.getFrontElement();
cache.erase(key_to_evict);
evictionTable.updateEvictionQueue(key);
}
else
evictionTable.pushEntry(key);
cache.insert(pair <string, Value> (key, newValue));
m_file.modify(key, value);
}
newValue.setAvailability(true);
}
void MapDB::remove(string key) {
cache.erase(key);
m_file.remove(key);
}