Implements namespace statement.
This commit is contained in:
49
src/Utils/MemoryPool.hpp
Normal file
49
src/Utils/MemoryPool.hpp
Normal file
@@ -0,0 +1,49 @@
|
||||
#ifndef MALACHSCRIPT_MEMORYPOOL_HPP
|
||||
#define MALACHSCRIPT_MEMORYPOOL_HPP
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace MalachScript::Utils {
|
||||
template <size_t initialSize, size_t steps>
|
||||
class MemoryPool {
|
||||
public:
|
||||
MemoryPool() : _offset(0), _capacity(initialSize) {
|
||||
auto *ptr = malloc(_capacity);
|
||||
if (ptr == nullptr) {
|
||||
throw std::logic_error("Out of memory.");
|
||||
}
|
||||
_memory = static_cast<uint8_t*>(ptr);
|
||||
}
|
||||
|
||||
~MemoryPool(){
|
||||
free(_memory);
|
||||
}
|
||||
|
||||
template <class T, class... parameters> T* Create(parameters... args){
|
||||
if (_offset + sizeof(T) >= _capacity) {
|
||||
IncreaseStep();
|
||||
}
|
||||
auto* element = new (_memory + _offset) T(args...);
|
||||
_offset += sizeof(T);
|
||||
return element;
|
||||
}
|
||||
|
||||
private:
|
||||
size_t _offset;
|
||||
size_t _capacity;
|
||||
uint8_t* _memory = nullptr;
|
||||
|
||||
void IncreaseStep(){
|
||||
_capacity += steps;
|
||||
auto newPtr = realloc(_memory, _capacity);
|
||||
if (newPtr == nullptr) {
|
||||
throw std::logic_error("Out of memory.");
|
||||
}
|
||||
_memory = static_cast<uint8_t*>(newPtr);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif // MALACHSCRIPT_MEMORYPOOL_HPP
|
||||
Reference in New Issue
Block a user