#ifndef GLTB_ALIGNEDHEAP #define GLTB_ALIGNEDHEAP #include #include "GLTB/referencedobject.h" namespace gltb { /** * Very simple, allocation-only heap for data objects with heterogeneous size, but * an arbitrary alignment requirement within the buffer; */ class AlignedHeap : ReferencedObject { public: AlignedHeap(size_t alignment) : alignment(alignment), buffer(nullptr), bufferSize(0) {} ~AlignedHeap() { if(buffer != nullptr) { free(buffer); } } /** * Important: Calling this function invalidates all previously obtained offset pointers. * * @return index of the allocation */ size_t allocate(size_t size) { size_t alignedSize; if(size % alignment == 0) { alignedSize = size; } else { alignedSize = ((size / alignment) + 1) * alignment; } bufferSize += alignedSize; if(buffer == nullptr) { buffer = (char*)malloc(bufferSize); } else { buffer = (char*)realloc(buffer, bufferSize); } offsets.push_back(bufferSize - alignedSize); return offsets.size() - 1; } template size_t allocate() { return allocate(sizeof(T)); } char *getOffset(size_t allocationIndex) { return buffer + offsets[allocationIndex]; } template T *getData(size_t allocationIndex) { return (T*)getOffset(allocationIndex); } size_t getBufferSize() { return bufferSize; } private: size_t alignment; size_t bufferSize; char *buffer; std::vector offsets; }; } #endif /* GLTB_ALIGNEDHEAP */