-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_cache.h
More file actions
84 lines (75 loc) · 2.08 KB
/
ip_cache.h
File metadata and controls
84 lines (75 loc) · 2.08 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
#include <list>
#include <unordered_map>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class ip_cache {
// constant time insertion and constant time erase, can work as stack / queue.
// Methods: pop_back, pop_front, push_back, push_back
public:
// lru_map has a pair that stores the iterator in the lru and the corresponding index in the ip_pool
static unordered_map<string, pair<list<string>::iterator, int>> lru_map;
static list<string> lru;
static int cap;
void show_cache()
{
cout << endl
<< "THE CACHE: [ ";
for (auto ip : lru)
{
cout << ip << " , ";
}
cout << " ]" << endl;
}
void add(string ip, int ip_pool_index)
{
if (lru.size() == cap)
{
lru_map.erase(lru.front());
lru.pop_front();
}
lru.push_front(ip);
lru_map[ip] = make_pair(lru.begin(), ip_pool_index);
}
void update_cache(string ip)
{
auto it1 = lru_map[ip].first;
auto it2 = std::next(it1, 1);
if (it2 != lru.end())
{
// store next val in a temporary var
auto temp = *it2;
// swap lru elements
*it2 = ip;
*it1 = temp;
// swap map iterator
lru_map[ip].first = it2;
lru_map[temp].first = it1;
}
}
int find_ip(string ip, int& ip_pool_index)
{
if (lru_map.find(ip) == lru_map.end())
{
add(ip, ip_pool_index);
return -1;
}
else
{
// ip is repeated
update_cache(ip);
return lru_map[ip].second;
}
}
void show_cache_analysis(vector<string> ip_pool)
{
cout << endl
<< "Client and Server IP's mapping: " << endl;
for (auto& ci : lru_map)
{
cout << "Client Ip: " << ci.first << " Maps to Server Ip: " << ip_pool[ci.second.second] << " * = " << *ci.second.first << endl;
}
}
};