summaryrefslogtreecommitdiff
path: root/src/dynamic-array.hpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/dynamic-array.hpp')
-rw-r--r--src/dynamic-array.hpp55
1 files changed, 55 insertions, 0 deletions
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 <cstdint>
+#include <cstring>
+#include <cassert>
+
+#define BAKE_DYN_ARRAY(T) template struct DynArray<T>;
+
+struct DynArrayBase {
+ char *ptr = nullptr;
+ int64_t elementSize = 0;
+ int64_t reservedSize = 0;
+};
+
+template <typename T>
+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 <typename T> inline DynArray<T>::DynArray() {
+ this->elementSize = sizeof(T);
+}
+
+template <typename T> inline DynArray<T>::~DynArray() {
+ DynArrayDestroy(this);
+}
+
+template <typename T> inline T DynArray<T>::operator[](std::size_t index) {
+ assert(index < this->reservedSize && "Invalid DynArray<T> index");
+ return *reinterpret_cast<T *>((this->ptr + (sizeof(T) * index)));
+}
+
+template <typename T> inline T *DynArray<T>::GetPtr() {
+ return reinterpret_cast<T *>(reinterpret_cast<void *>(this->ptr));
+}
+
+template <typename T> inline void DynArray<T>::Reserve(int64_t count) {
+ return DynArrayReserve(this, count);
+}
+
+#endif /* FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP */