-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.cpp
40 lines (37 loc) · 1.22 KB
/
cache.cpp
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
#include "cache.h"
Cache::Cache(int capacity) : mCapacity(capacity), doublyLinkedList(), cacheData()
{
}
std::string Cache::find(const std::string &key)
{
auto result = cacheData.find(key);
if (result != cacheData.end())
{
auto &it = result->second;
doublyLinkedList.splice(doublyLinkedList.begin(), doublyLinkedList, it);
return it->second;
}
return "";
}
void Cache::upsert(const std::string &key, const std::string &value)
{
auto result = cacheData.find(key);
if (result != cacheData.end()) // update: does not increase the size
{
auto &it = result->second;
doublyLinkedList.splice(doublyLinkedList.begin(), doublyLinkedList, it);
it->second = value; // update
}
else // insert: could increase the size
{
if (doublyLinkedList.size() == mCapacity)
{
// remove the least recently accessed item
cacheData.erase(doublyLinkedList.back().first);
doublyLinkedList.pop_back();
}
// insert it at the front of the list (most recently accessed)
doublyLinkedList.emplace_front(key, value);
cacheData[key] = doublyLinkedList.begin();
}
}