|
| 1 | +#include "FixedSizeAllocator.h" |
| 2 | + |
| 3 | +#include <stdexcept> |
| 4 | + |
| 5 | +namespace dae |
| 6 | +{ |
| 7 | + |
| 8 | + FixedSizeAllocator::FixedSizeAllocator(uint32_t numOfBlock, uint32_t sizeOfEachBlock) |
| 9 | + : m_numOfBlocks{numOfBlock} |
| 10 | + , m_sizeOfEachBlock{sizeOfEachBlock} |
| 11 | + , m_numFreeBlocks{numOfBlock} |
| 12 | + , m_numInitialized{0} |
| 13 | + , m_memStart {new uint8_t[numOfBlock * sizeOfEachBlock]} |
| 14 | + , m_next{m_memStart} |
| 15 | + { |
| 16 | + } |
| 17 | + |
| 18 | + FixedSizeAllocator::~FixedSizeAllocator() |
| 19 | + { |
| 20 | + delete[] m_memStart; |
| 21 | + } |
| 22 | + |
| 23 | + void * FixedSizeAllocator::Acquire(size_t nbBytes) |
| 24 | + { |
| 25 | + if (nbBytes > m_sizeOfEachBlock or m_numFreeBlocks == 0) |
| 26 | + { |
| 27 | + throw std::bad_alloc(); |
| 28 | + } |
| 29 | + if (m_numInitialized < m_numOfBlocks) |
| 30 | + { |
| 31 | + auto p = reinterpret_cast<uint32_t *>(AddFromIndex(m_numInitialized)); |
| 32 | + *p = m_numInitialized + 1; |
| 33 | + m_numInitialized++; |
| 34 | + } |
| 35 | + void *ret = nullptr; |
| 36 | + if (m_numFreeBlocks > 0) |
| 37 | + { |
| 38 | + ret = m_next; |
| 39 | + --m_numFreeBlocks; |
| 40 | + if (m_numFreeBlocks != 0) |
| 41 | + { |
| 42 | + m_next = AddFromIndex(*m_next); |
| 43 | + } |
| 44 | + else |
| 45 | + { |
| 46 | + m_next = nullptr; |
| 47 | + } |
| 48 | + } |
| 49 | + return ret; |
| 50 | + } |
| 51 | + |
| 52 | + void FixedSizeAllocator::Release(void *pointerToBuffer) |
| 53 | + { |
| 54 | + // Not sure if this is necessary |
| 55 | + // if (pointerToBuffer == nullptr) |
| 56 | + // { |
| 57 | + // throw std::runtime_error("Pointer is null"); |
| 58 | + // } |
| 59 | + // if (m_numFreeBlocks == m_numOfBlocks) |
| 60 | + // { |
| 61 | + // throw std::runtime_error("All blocks are free"); |
| 62 | + // } |
| 63 | + if (pointerToBuffer < m_memStart or pointerToBuffer >= m_memStart + m_numOfBlocks * m_sizeOfEachBlock) |
| 64 | + { |
| 65 | + throw std::runtime_error("Pointer is out of range"); |
| 66 | + } |
| 67 | + if (m_next != nullptr) |
| 68 | + { |
| 69 | + *reinterpret_cast<uint32_t *>(pointerToBuffer) = IndexFromAddr(m_next); |
| 70 | + m_next = reinterpret_cast<uint8_t *>(pointerToBuffer); |
| 71 | + } |
| 72 | + else |
| 73 | + { |
| 74 | + *reinterpret_cast<uint32_t *>(pointerToBuffer) = m_numOfBlocks; |
| 75 | + m_next = reinterpret_cast<uint8_t *>(pointerToBuffer); |
| 76 | + } |
| 77 | + ++m_numFreeBlocks; |
| 78 | + } |
| 79 | + |
| 80 | + auto FixedSizeAllocator::AddFromIndex(uint32_t i) const -> uint8_t * |
| 81 | + { |
| 82 | + return m_memStart + i * m_sizeOfEachBlock; |
| 83 | + } |
| 84 | + |
| 85 | + auto FixedSizeAllocator::IndexFromAddr(uint8_t const *p) const -> uint32_t |
| 86 | + { |
| 87 | + return static_cast<uint32_t>(p - m_memStart) / m_sizeOfEachBlock; |
| 88 | + } |
| 89 | +} |
0 commit comments