-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCache.cpp
More file actions
68 lines (60 loc) · 2.04 KB
/
Cache.cpp
File metadata and controls
68 lines (60 loc) · 2.04 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
#include "Cache.h"
#include <unordered_map>
#include <list>
#include <utility>
#include <iostream>
using namespace std;
Cache::Cache(size_t sizeLimit) : cacheSizeLimit(sizeLimit) {}
Cache::~Cache() {
for (auto it = cacheMap.begin(); it != cacheMap.end(); it++) {
delete[] it->second.first;
}
}
void Cache::addFileToCache(string &fileName, char *fileContent, size_t contentSize) {
lock_guard<mutex> lock(mtx_cache);
if (cacheMap.size() >= cacheSizeLimit) {
string lastFile = cacheOrder.back();
cacheOrder.pop_back();
delete[] cacheMap[lastFile].first;
cacheMap.erase(lastFile);
}
char *fileData = new char[contentSize];
memcpy(fileData, fileContent, contentSize);
cacheMap[fileName] = make_pair(fileData, contentSize);
cacheOrder.push_front(fileName);
}
bool Cache::getFileFromCache(string &fileName, char *&fileContent, size_t &contentSize) {
lock_guard<mutex> lock(mtx_cache);
if (cacheMap.find(fileName) == cacheMap.end()) {
return false;
}
cacheOrder.remove(fileName);
cacheOrder.push_front(fileName);
fileContent = new char[cacheMap[fileName].second];
memcpy(fileContent, cacheMap[fileName].first, cacheMap[fileName].second);
contentSize = cacheMap[fileName].second;
return true;
}
void Cache::invalidateFileInCache(string &fileName) {
lock_guard<mutex> lock(mtx_cache);
if (cacheMap.find(fileName) != cacheMap.end()) {
delete[] cacheMap[fileName].first;
cacheMap.erase(fileName);
// cacheOrder.remove(fileName);
cacheOrder.remove_if([&fileName](const string &item) { return item == fileName; });
cout<<"File invalidated in cache: "<<fileName<<endl;
printCache();
}
}
void Cache::printCache() {
cout<<"Cache order: ";
for (auto it = cacheOrder.begin(); it != cacheOrder.end(); it++) {
cout << *it << " ";
}
cout << endl;
cout<<"Cache map: ";
for (auto it = cacheMap.begin(); it != cacheMap.end(); it++) {
cout << it->first << " ";
}
cout << endl;
}