summaryrefslogtreecommitdiff
path: root/src/dynamic-array.hpp
diff options
context:
space:
mode:
authorJonathan Bradley <jcb@pikum.xyz>2023-08-12 11:04:42 -0400
committerJonathan Bradley <jcb@pikum.xyz>2023-08-12 11:04:42 -0400
commit7cd40ea0dd3659ee599dc842739b9e68286ea213 (patch)
tree5090387a93ba621efb19ce72326a9739560b8693 /src/dynamic-array.hpp
parentc379a02e66d0e93a2f0b8e11d828ca9c0513698b (diff)
Add DynamicArray
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 */