-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_manage.h
86 lines (77 loc) · 1.5 KB
/
cache_manage.h
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
#ifndef CACHE_MANAGE_H
#define CACHE_MANAGE_H
#include <iostream>
#include <queue>
#include <string>
#include <map>
using namespace std;
namespace omd
{
class CachBase
{
public:
virtual void *Get(string k) = 0;
virtual void Del(string k);
virtual void SetRealGet(void *(*)(string));
};
struct LRUNode
{
LRUNode *prev;
LRUNode *next;
void *data;
};
class LRU : public CachBase
{
public:
LRU(int cap = 64);
void *Get(string k)
{
auto v = data.find(k);
if (v != data.end())
{
return v->second;
}
int size = this->data.size();
LRUNode* one;
if (size == cap)
{
one=removeFront();
}else{
one=new(LRUNode);
}
moveToTail(one);
one->data=realGet(k);
}
void Del(string){
void(0);
}
void SetRealGet(void *(*realGet)(string))
{
this->realGet = realGet;
}
private:
LRUNode *removeFront()
{
assert(head == tail);
LRUNode *one = head->next;
head->next = one->next;
one->next->prev = one->prev;
return one;
}
void moveToTail(LRUNode *one)
{
assert(one != head);
assert(one != tail);
one->prev = tail->prev;
one->next = tail;
tail->prev->next = one;
tail->prev = one;
}
int cap;
LRUNode *head;
LRUNode *tail;
void *(*realGet)(string);
map<string, void *> data;
};
} // namespace omd
#endif