summaryrefslogtreecommitdiff
path: root/src/dynamic-array.hpp
diff options
context:
space:
mode:
authorJonathan Bradley <jcb@pikum.xyz>2023-08-18 09:42:24 -0400
committerJonathan Bradley <jcb@pikum.xyz>2023-08-18 10:10:16 -0400
commit51bc40dd03be65868095c1ff8ed185b109d29ede (patch)
tree24d3fc57b92591677370bdfc16a9ddefd16f0acf /src/dynamic-array.hpp
parent90ae5cdba22681488f2cb638e8abedaebbd29be1 (diff)
add Push and Pop to DynArray<T>
Diffstat (limited to 'src/dynamic-array.hpp')
-rw-r--r--src/dynamic-array.hpp33
1 files changed, 29 insertions, 4 deletions
diff --git a/src/dynamic-array.hpp b/src/dynamic-array.hpp
index c671599..3fc2d08 100644
--- a/src/dynamic-array.hpp
+++ b/src/dynamic-array.hpp
@@ -13,7 +13,8 @@
struct DynArrayBase {
char *ptr = nullptr;
int64_t elementSize = 0;
- int64_t reservedSize = 0;
+ int64_t elementCount = 0;
+ int64_t reservedCount = 0;
};
template <typename T>
@@ -22,11 +23,15 @@ struct DynArray: DynArrayBase {
~DynArray();
T operator[](std::size_t index);
T *GetPtr();
+ void Push(const T &val);
+ T Pop();
void Reserve(int64_t count);
- private:
+ void Resize(int64_t count);
+ protected:
using DynArrayBase::ptr;
using DynArrayBase::elementSize;
- using DynArrayBase::reservedSize;
+ using DynArrayBase::elementCount;
+ using DynArrayBase::reservedCount;
};
void inline DynArrayReserve(DynArrayBase *arr, int64_t count);
@@ -41,7 +46,8 @@ template <typename T> inline DynArray<T>::~DynArray() {
}
template <typename T> inline T DynArray<T>::operator[](std::size_t index) {
- assert(index < this->reservedSize && "Invalid DynArray<T> index");
+ assert(index < this->elementCount && "Invalid DynArray<T>[] index - out of bounds");
+ assert(index < this->reservedCount && "Invalid DynArray<T>[] index - out of reserved bounds");
return *reinterpret_cast<T *>((this->ptr + (sizeof(T) * index)));
}
@@ -49,8 +55,27 @@ template <typename T> inline T *DynArray<T>::GetPtr() {
return reinterpret_cast<T *>(reinterpret_cast<void *>(this->ptr));
}
+template <typename T> inline void DynArray<T>::Push(const T &val) {
+ if (this->elementCount + 1 > this->reservedCount) {
+ DynArrayReserve(this, int64_t(this->reservedCount * 1.5));
+ }
+ std::memcpy(this->ptr + (sizeof(T) * this->elementCount), &val, sizeof(T));
+ this->elementCount += 1;
+}
+
+template <typename T> inline T DynArray<T>::Pop() {
+ assert(this->elementCount == 0 && "Invalid DynArray<T>::Pop() - Contains no elements");
+ this->elementCount -= 1;
+ return *reinterpret_cast<T *>((this->ptr + (sizeof(T) * this->elementCount)));
+}
+
template <typename T> inline void DynArray<T>::Reserve(int64_t count) {
return DynArrayReserve(this, count);
}
+template <typename T> inline void DynArray<T>::Resize(int64_t count) {
+ DynArrayReserve(this, count);
+ this->elementCount = count;
+}
+
#endif /* FOUR_ZED_ZED_DYNAMIC_ARRAY_HPP */