-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearAllocator.hpp
57 lines (40 loc) · 1014 Bytes
/
LinearAllocator.hpp
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
#ifndef LINEAR_ALLOCATOR_H
#define LINEAR_ALLOCATOR_H
#include <vector>
using std::vector;
template<typename T>
class LinearAllocator {
constexpr static size_t BUFFER_SIZE = 1024 * 1024 * 1024;
private:
vector<char *> buffers;
char *current_buffer;
size_t current_buffer_watermark;
public:
LinearAllocator() {
add_buffer();
}
~LinearAllocator() {
cleanup();
}
inline void cleanup() noexcept {
for(auto &buffer: buffers) {
delete buffer;
}
}
inline void add_buffer() noexcept {
char *new_buffer = new char[BUFFER_SIZE];
buffers.emplace_back(new_buffer);
current_buffer = new_buffer;
current_buffer_watermark = 0;
}
inline T *allocate(size_t quantity) noexcept {
char *old = current_buffer + current_buffer_watermark;
current_buffer_watermark += (quantity * sizeof(T));
if(current_buffer_watermark >= BUFFER_SIZE) {
add_buffer();
old = current_buffer;
}
return (T *) old;
}
};
#endif /* LINEAR_ALLOCATOR_H */