diff --git a/include/blt/std/memory.h b/include/blt/std/memory.h index e65040e..2f6e70d 100755 --- a/include/blt/std/memory.h +++ b/include/blt/std/memory.h @@ -327,11 +327,11 @@ namespace blt public: static_vector() = default; - inline bool push_back(T copy) + inline bool push_back(const T& copy) { if (size_ >= MAX_SIZE) return false; - buffer_[size_++] = std::move(copy); + buffer_[size_++] = copy; return true; } @@ -339,10 +339,16 @@ namespace blt { if (size_ >= MAX_SIZE) return false; - buffer_[size_++] = std::forward(move); + buffer_[size_++] = std::move(move); return true; } + inline T& at(size_t index) + { + if (index >= MAX_SIZE) + throw std::runtime_error("Array index " + std::to_string(index) + " out of bounds! (Max size: " + std::to_string(MAX_SIZE) + ')'); + } + inline T& operator[](size_t index) { return buffer_[index]; @@ -353,11 +359,23 @@ namespace blt return buffer_[index]; } + inline void reserve(size_t size) + { + if (size > MAX_SIZE) + size = MAX_SIZE; + size_ = size; + } + [[nodiscard]] inline size_t size() const { return size_; } + [[nodiscard]] inline size_t capacity() const + { + return MAX_SIZE; + } + inline T* data() { return buffer_; @@ -373,14 +391,14 @@ namespace blt return buffer_; } - inline ptr_iterator begin() + inline T* begin() { - return ptr_iterator{buffer_}; + return buffer_; } - inline ptr_iterator end() + inline T* end() { - return ptr_iterator{&buffer_[size_]}; + return &buffer_[size_]; } }; diff --git a/tests/include/memory_test.h b/tests/include/memory_test.h index c2bbdd3..4b6141e 100644 --- a/tests/include/memory_test.h +++ b/tests/include/memory_test.h @@ -26,14 +26,14 @@ namespace blt::test::memory void access(); - void ranges(); + void static_vector_test(); static inline void run() { copy(); move(); access(); - ranges(); + static_vector_test(); } } diff --git a/tests/src/memory_test.cpp b/tests/src/memory_test.cpp index 9eb7dee..85e8900 100644 --- a/tests/src/memory_test.cpp +++ b/tests/src/memory_test.cpp @@ -99,7 +99,38 @@ void blt::test::memory::access() } -void blt::test::memory::ranges() +void blt::test::memory::static_vector_test() { - BLT_TRACE_STREAM << '\n'; + blt::static_vector vec; + + for (size_t i = 0; i < 16; i++) + vec[i] = static_cast(i * 2); + + for (size_t i = 0; i < 16; i++) + BLT_DEBUG_STREAM << vec[i] << ' '; + BLT_DEBUG_STREAM << '\n'; + + vec[3] = 120; + vec[7] = 230; + + vec.reserve(vec.capacity()); + + for (auto v : vec) + BLT_DEBUG_STREAM << v << ' '; + BLT_DEBUG_STREAM << '\n'; + + vec.reserve(0); + + for (size_t i = 0; i < vec.capacity(); i++) + { + if (!vec.push_back(static_cast(i))) + BLT_INFO("Failed to insert on %d", i); + } + + if (!vec.push_back(10)) + BLT_INFO("Vector unable to push, current size vs capacity: %d vs %d", vec.size(), vec.capacity()); + + for (auto v : vec) + BLT_DEBUG_STREAM << v << ' '; + BLT_DEBUG_STREAM << '\n'; }