diff --git a/source/mijin/container/typeless_buffer.hpp b/source/mijin/container/typeless_buffer.hpp index 4ce0acb..92752d5 100644 --- a/source/mijin/container/typeless_buffer.hpp +++ b/source/mijin/container/typeless_buffer.hpp @@ -37,9 +37,12 @@ public: private: std::vector bytes_; public: + auto operator<=>(const TypelessBuffer&) const noexcept = default; + [[nodiscard]] void* data() noexcept { return bytes_.data(); } [[nodiscard]] const void* data() const noexcept { return bytes_.data(); } [[nodiscard]] size_type byteSize() const noexcept { return bytes_.size(); } + [[nodiscard]] size_type byteCapacity() const noexcept { return bytes_.capacity(); } [[nodiscard]] bool empty() const noexcept { return bytes_.empty(); } void resize(size_type numBytes) { bytes_.resize(numBytes); } void reserve(size_type numBytes) { bytes_.reserve(numBytes); } diff --git a/source/mijin/container/untyped_vector.hpp b/source/mijin/container/untyped_vector.hpp new file mode 100644 index 0000000..a09a9ed --- /dev/null +++ b/source/mijin/container/untyped_vector.hpp @@ -0,0 +1,91 @@ + +#pragma once + +#if !defined(MIJIN_CONTAINER_UNTYPED_VECTOR_HPP_INCLUDED) +#define MIJIN_CONTAINER_UNTYPED_VECTOR_HPP_INCLUDED 1 + +#include +#include "./typeless_buffer.hpp" + +namespace mijin +{ +class UntypedVector +{ +public: + using size_type = std::size_t; +private: + std::size_t elementSize_ = 0; + TypelessBuffer buffer_; +public: + explicit UntypedVector(size_type elementSize = 0, size_type count = 0) : elementSize_(elementSize) + { + resize(count); + } + + std::span operator[](size_type index) + { + return at(index); + } + + std::span operator[](size_type index) const + { + return at(index); + } + + auto operator<=>(const UntypedVector&) const noexcept = default; + + void resize(size_type count) + { + MIJIN_ASSERT(elementSize_ > 0, "Cannot allocate without element size."); + buffer_.resize(count * elementSize_); + } + + void reserve(size_type count) + { + MIJIN_ASSERT(elementSize_ > 0, "Cannot allocate without element size."); + buffer_.reserve(count * elementSize_); + } + + [[nodiscard]] + std::span at(size_type index) + { + if (index > size()) + { + throw std::out_of_range("Index out of range."); + } + return buffer_.makeSpan().subspan(index * elementSize_, elementSize_); + } + + [[nodiscard]] + std::span at(size_type index) const + { + if (index > size()) + { + throw std::out_of_range("Index out of range."); + } + return buffer_.makeSpan().subspan(index * elementSize_, elementSize_); + } + + [[nodiscard]] + size_type size() const MIJIN_NOEXCEPT + { + if (elementSize_ == 0) + { + return 0; + } + return buffer_.byteSize() / elementSize_; + } + + [[nodiscard]] + size_type capacity() const MIJIN_NOEXCEPT + { + if (elementSize_ == 0) + { + return 0; + } + return buffer_.byteCapacity() / elementSize_; + } +}; +} + +#endif // !defined(MIJIN_CONTAINER_UNTYPED_VECTOR_HPP_INCLUDED) \ No newline at end of file