From 196ad901b19a4a741b71bc3c88927aa0af69273a Mon Sep 17 00:00:00 2001 From: Jonathan Bradley Date: Wed, 30 Aug 2023 21:57:45 -0400 Subject: DynArray gracefully handle attempting to reserve size of 0 --- src/dynamic-array.hpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'src/dynamic-array.hpp') diff --git a/src/dynamic-array.hpp b/src/dynamic-array.hpp index 703b5ed..ba48b8a 100644 --- a/src/dynamic-array.hpp +++ b/src/dynamic-array.hpp @@ -42,7 +42,7 @@ void DynArrayDestroy(DynArrayBase *arr); template inline DynArray::DynArray(int64_t count) { this->elementSize = sizeof(T); - this->Reserve(count); + if (count > 0) DynArrayReserve(this, count); } template inline DynArray::DynArray() { @@ -76,7 +76,8 @@ template inline bool DynArray::Has(const T &val) { template inline void DynArray::Push(const T &val) { if (this->elementCount + 1 > this->reservedCount) { - DynArrayReserve(this, int64_t(this->reservedCount * 1.5)); + auto safeReserveCount = this->reservedCount == 0 ? 1 : this->reservedCount; + DynArrayReserve(this, int64_t(safeReserveCount * 1.5)); } std::memcpy(this->ptr + (sizeof(T) * this->elementCount), &val, sizeof(T)); this->elementCount += 1; @@ -89,11 +90,16 @@ template inline T DynArray::Pop() { } template inline void DynArray::Reserve(int64_t count) { - return DynArrayReserve(this, count); + if (count > 0) { + return DynArrayReserve(this, count); + } + this->elementCount = this->elementCount > count ? count : this->elementCount; } template inline void DynArray::Resize(int64_t count) { - DynArrayReserve(this, count); + if (count > 0) { + DynArrayReserve(this, count); + } this->elementCount = count; } -- cgit v1.2.3