diff --git a/luna/include/luna/Vector.h b/luna/include/luna/Vector.h new file mode 100644 index 00000000..d86e9e4b --- /dev/null +++ b/luna/include/luna/Vector.h @@ -0,0 +1,114 @@ +#pragma once +#include +#include +#include +#include + +template class Vector +{ + public: + typedef T* Iterator; + typedef const T* ConstIterator; + + Vector() + { + } + + Result try_reserve(usize capacity) + { + return resize(capacity); + } + + void reserve(usize capacity) + { + resize(capacity).release_value(); + } + + Result try_append(T item) + { + if (m_capacity == m_size) TRY(resize(m_capacity + 8)); + + new (&m_data[m_size]) T(move(item)); + + m_size++; + + return {}; + } + + Option try_pop() + { + if (m_size == 0) return {}; + + m_size--; + + return move(m_data[m_size]); + } + + const T& operator[](usize index) const + { + check(index < m_size); + return m_data[m_size]; + } + + T& operator[](usize index) + { + check(index < m_size); + return m_data[m_size]; + } + + Iterator begin() + { + return m_data; + } + + ConstIterator begin() const + { + return m_data; + } + + Iterator end() + { + return m_data + m_size; + } + + ConstIterator end() const + { + return m_data + m_size; + } + + const T* data() const + { + return m_data; + } + + T* data() + { + return m_data; + } + + usize capacity() const + { + return m_capacity; + } + + usize size() const + { + return m_size; + } + + private: + T* m_data { nullptr }; + usize m_capacity { 0 }; + usize m_size { 0 }; + + Result resize(usize new_capacity) + { + void* ptr = TRY(realloc_impl(m_data, new_capacity)); + if (new_capacity < m_capacity) memcpy(ptr, m_data, new_capacity); + else + memcpy(ptr, m_data, m_capacity); + m_capacity = new_capacity; + m_data = (T*)ptr; + return {}; + } +};