-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCache.cpp
More file actions
98 lines (92 loc) · 2.36 KB
/
Cache.cpp
File metadata and controls
98 lines (92 loc) · 2.36 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
#include "Cache.h"
#include <cstring>
#include <list>
#include <vector>
using namespace std;
Cache::Cache(int size) {
myRemainingSize = size;
cacheMap = new map<KeyNode, CacheNode>;
pthread_mutex_init(&mutex, NULL);
}
int Cache::getFromCache(char* desiredKey, char * output) {
pthread_mutex_lock(&mutex);
string sKey(desiredKey);
KeyNode desiredKeyNode(sKey, MAX_AGE);
map<KeyNode, CacheNode>::iterator it;
vector<pair<KeyNode, CacheNode> > v;
int ret;
if(containsKey(desiredKeyNode) == cacheMap->end()) {
pthread_mutex_unlock(&mutex);
return -1;
}
for(it = cacheMap->begin(); it != cacheMap->end(); it++) {
KeyNode kn = it->first;
CacheNode cn = it->second;
v.push_back(make_pair(kn, cn));
if(kn == desiredKeyNode) {
v.back().first.age = MAX_AGE;
output = (char*) malloc(sizeof(char) * cn.size);
memcpy(output, cn.data, cn.size);
ret = cn.size;
}
else {
v.back().first.age = kn.age - 1;
}
cacheMap->erase(kn);
}
while(!v.empty()) {
cacheMap->insert(v.back());
v.pop_back();
}
pthread_mutex_unlock(&mutex);
return ret;
}
void Cache::addToCache(char* key, char* data, int size) {
pthread_mutex_lock(&mutex);
string sKey(key);
KeyNode newKn(sKey, MAX_AGE);
char * sdata = (char*) malloc(sizeof(char) * size);
memcpy(sdata, data, size);
//string sdata(data);
map<KeyNode, CacheNode>::iterator exists = containsKey(newKn);
if(exists != cacheMap->end()) {
int oldSize = exists->second.size;
cacheMap->erase(exists);
myRemainingSize += oldSize;
}
if(myRemainingSize >= size) {
pair<KeyNode, CacheNode> p = make_pair(newKn, CacheNode(sdata,size));
cacheMap->insert(p);
myRemainingSize -= size;
pthread_mutex_unlock(&mutex);
return;
}
else{
map<KeyNode, CacheNode>::iterator it;
for(it = cacheMap->begin(); it != cacheMap->end();) {
CacheNode cn = it->second;
myRemainingSize += cn.size;
cacheMap->erase(it);
if(myRemainingSize >= size) {
pair<KeyNode, CacheNode> p = make_pair(newKn, CacheNode(sdata,size));
cacheMap->insert(p);
myRemainingSize -= size;
break;
}
else{
++ it;
}
}
}
pthread_mutex_unlock(&mutex);
}
map<KeyNode, CacheNode>::iterator Cache::containsKey(KeyNode desiredKeyNode) {
map<KeyNode, CacheNode>::iterator it;
for(it = cacheMap->begin(); it != cacheMap->end(); it++) {
KeyNode kn = it->first;
if(kn == desiredKeyNode) {
return it;
}
}
return it;
}