Implements namespace statement.

This commit is contained in:
2020-10-09 11:54:43 +02:00
parent 2fb1b68ead
commit 43f080cc48
6 changed files with 69 additions and 32 deletions

49
src/Utils/MemoryPool.hpp Normal file
View 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