| 12 | /// @brief An array using a large virtual memory reservation to keep stable addresses. |
| 13 | template <typename T> |
| 14 | struct VirtualArray |
| 15 | { |
| 16 | VirtualArray() = default; |
| 17 | VirtualArray(size_t maxCapacity) { SC_CONTAINERS_ASSERT_RELEASE(reserve(maxCapacity)); } |
| 18 | ~VirtualArray() { clear(); } |
| 19 | |
| 20 | /// @brief Releases all reserved memory. |
| 21 | /// @warning Does not call destructors of contained elements (use clear() for that). |
| 22 | void release() |
| 23 | { |
| 24 | virtualMemory.release(); |
| 25 | capacityElements = 0; |
| 26 | sizeElements = 0; |
| 27 | } |
| 28 | |
| 29 | /// @brief Clears the stable array by calling the destructor of each element. |
| 30 | /// @note Does not release reserved memory (use release() for that). |
| 31 | void clear() |
| 32 | { |
| 33 | T* items = data(); |
| 34 | while (sizeElements > 0) |
| 35 | { |
| 36 | sizeElements--; |
| 37 | items[sizeElements].~T(); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /// @brief Clears the array calling destructors of each element and releases virtual memory. |
| 42 | [[nodiscard]] bool clearAndDecommit() |
| 43 | { |
| 44 | clear(); |
| 45 | return decommit(); |
| 46 | } |
| 47 | |
| 48 | /// @brief De-commits unused-memory, while still keeping the original virtual reservation |
| 49 | [[nodiscard]] bool decommit() { return virtualMemory.decommit(sizeElements * sizeof(T)); } |
| 50 | |
| 51 | /// @brief Resizes the stable array without initializing or calling destructors. |
| 52 | [[nodiscard]] bool resizeWithoutInitializing(size_t newSize) |
| 53 | { |
| 54 | if (not virtualMemory.commit(newSize * sizeof(T))) |
| 55 | return false; |
| 56 | sizeElements = newSize; |
| 57 | return true; |
| 58 | } |
| 59 | |
| 60 | /// @brief Resizes the stable array, calling constructors or destructors as needed. |
| 61 | [[nodiscard]] bool resize(size_t newSize) |
| 62 | { |
| 63 | T* items = data(); |
| 64 | const size_t oldSize = sizeElements; |
| 65 | if (newSize < oldSize) |
| 66 | { |
| 67 | size_t idx = oldSize; |
| 68 | do |
| 69 | { |
| 70 | items[--idx].~T(); |
| 71 | } while (idx != newSize); |