From 7cd40ea0dd3659ee599dc842739b9e68286ea213 Mon Sep 17 00:00:00 2001 From: Jonathan Bradley Date: Sat, 12 Aug 2023 11:04:42 -0400 Subject: Add DynamicArray --- src/dynamic-array.hpp | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/dynamic-array.hpp (limited to 'src/dynamic-array.hpp') diff --git a/src/dynamic-array.hpp b/src/dynamic-array.hpp new file mode 100644 index 0000000..29fb765 --- /dev/null +++ b/src/dynamic-array.hpp @@ -0,0 +1,55 @@ +#ifndef FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP +#define FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP + +#include "memory.hpp" + +#include +#include +#include + +#define BAKE_DYN_ARRAY(T) template struct DynArray; + +struct DynArrayBase { + char *ptr = nullptr; + int64_t elementSize = 0; + int64_t reservedSize = 0; +}; + +template +struct DynArray: DynArrayBase { + DynArray(); + ~DynArray(); + T operator[](std::size_t index); + T *GetPtr(); + void Reserve(int64_t count); + private: + using DynArrayBase::ptr; + using DynArrayBase::elementSize; + using DynArrayBase::reservedSize; +}; + +void inline DynArrayReserve(DynArrayBase *arr, int64_t count); +void inline DynArrayDestroy(DynArrayBase *arr); + +template inline DynArray::DynArray() { + this->elementSize = sizeof(T); +} + +template inline DynArray::~DynArray() { + DynArrayDestroy(this); +} + +template inline T DynArray::operator[](std::size_t index) { + assert(index < this->reservedSize && "Invalid DynArray index"); + return *reinterpret_cast((this->ptr + (sizeof(T) * index))); +} + +template inline T *DynArray::GetPtr() { + return reinterpret_cast(reinterpret_cast(this->ptr)); +} + +template inline void DynArray::Reserve(int64_t count) { + return DynArrayReserve(this, count); +} + +#endif /* FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP */ -- cgit v1.2.3