#ifndef MALACHSCRIPT_MEMORYPOOL_HPP #define MALACHSCRIPT_MEMORYPOOL_HPP #include #include #include namespace MalachScript::Utils { template class MemoryPool { public: MemoryPool() { AllocateBlock(); } MemoryPool(MemoryPool const&) = delete; MemoryPool& operator=(MemoryPool const&) = delete; ~MemoryPool() { for (auto c : _chunks) { free(c); } } template 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 _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(newPtr); _end = _head + (steps * sizeof(uint8_t*)); _chunks.push_back(_head); } }; } #endif // MALACHSCRIPT_MEMORYPOOL_HPP