-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmempool.h
108 lines (93 loc) · 2.66 KB
/
mempool.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#ifndef _FILE_ACCESSOR_H_
#define _FILE_ACCESSOR_H_
#include <iostream>
#include <fstream>
#include <string>
using std::fstream;
using std::string;
using std::ios;
template <typename T>
class MemoryPool {
const static off_t sizeof_off = sizeof(off_t);
const static off_t null_off = 0L;
const static off_t head_off = sizeof_off * 1L;
const static off_t tail_off = sizeof_off * 2L;
const static off_t del_top_off = sizeof_off * 3L;
const static int info_cnt = 4;
fstream file;
string file_name;
public:
MemoryPool(const MemoryPool &) = delete;
MemoryPool(const string &_name): file_name(_name) {
file.open(file_name);
if(!file) {
file.close();
file.open(file_name, ios::binary | ios::out);
off_t tmp = null_off;
for(int i = 0; i < info_cnt; ++i) {
file.write(reinterpret_cast<const char *>(&tmp), sizeof_off);
}
}
file.close();
file.open(file_name, ios::binary | ios::in | ios::out);
}
void getHead(off_t &head) {
read(head, head_off);
}
void getTail(off_t &tail) {
read(tail, tail_off);
}
void putHead(const off_t head) {
write(head, head_off);
}
void putTail(const off_t tail) {
write(tail, tail_off);
}
void clear() {
file.close();
file.open(file_name, ios::binary | ios::trunc | ios::out);
off_t tmp = null_off;
for(int i = 0; i < info_cnt; ++i) {
file.write(reinterpret_cast<const char *>(&tmp), sizeof_off);
}
file.close();
file.open(file_name, ios::binary | ios::in | ios::out);
}
template <typename U>
void read(U& obj, const off_t off = 0) {
file.seekg(off);
file.read(reinterpret_cast<char *>(&obj), sizeof(U));
}
template <typename U>
void write(const U& obj, const off_t off = 0) {
file.seekp(off);
file.write(reinterpret_cast<const char *>(&obj), sizeof(U));
}
off_t malloc() {
off_t del_top;
read(del_top, del_top_off);
off_t ret;
if(del_top) {
off_t del_nex;
read (del_nex, del_top);
write(del_nex, del_top_off);
ret = del_top + sizeof_off;
}
else {
file.seekp(sizeof_off, ios::end);
ret = file.tellp();
}
return ret;
}
void free(const off_t off) {
off_t tmp;
read (tmp, del_top_off);
write(tmp, off - sizeof_off);
tmp = off - sizeof_off;
write(tmp, del_top_off);
}
~MemoryPool() {
file.close();
}
};
#endif // _FILE_ACCESSOR_H_