52 lines
1.4 KiB
C++
52 lines
1.4 KiB
C++
#ifndef MALACHSCRIPT_MEMORYPOOL_HPP
|
|
#define MALACHSCRIPT_MEMORYPOOL_HPP
|
|
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <stdexcept>
|
|
|
|
namespace MalachScript::Utils {
|
|
template <size_t steps> class MemoryPool {
|
|
public:
|
|
MemoryPool() { AllocateBlock(); }
|
|
MemoryPool(MemoryPool const&) = delete;
|
|
MemoryPool& operator=(MemoryPool const&) = delete;
|
|
|
|
~MemoryPool() {
|
|
for (auto c : _chunks) {
|
|
free(c);
|
|
}
|
|
}
|
|
|
|
template <class T, class... parameters> T* Create(parameters... args) {
|
|
auto* p = _tail + sizeof(T);
|
|
if (p >= _end) {
|
|
AllocateBlock();
|
|
p = _tail + sizeof(T);
|
|
}
|
|
auto* element = new (_tail) T(args...);
|
|
_tail = p;
|
|
return element;
|
|
}
|
|
|
|
private:
|
|
std::vector<uint8_t*> _chunks;
|
|
|
|
uint8_t* _tail = nullptr;
|
|
uint8_t* _end;
|
|
uint8_t* _head = nullptr;
|
|
|
|
void AllocateBlock() {
|
|
auto* newPtr = malloc(steps * sizeof(uint8_t*));
|
|
if (newPtr == nullptr) {
|
|
throw std::logic_error("Out of memory.");
|
|
}
|
|
_tail = _head = static_cast<uint8_t*>(newPtr);
|
|
_end = _head + (steps * sizeof(uint8_t*));
|
|
_chunks.push_back(_head);
|
|
}
|
|
};
|
|
}
|
|
|
|
#endif // MALACHSCRIPT_MEMORYPOOL_HPP
|