From 6d2a57485ea8d9973c5b76f5c8b0637baf63fcce Mon Sep 17 00:00:00 2001 From: Patrick Wuttke Date: Wed, 22 Jan 2025 11:47:28 +0100 Subject: [PATCH] Added dataAt() to TypelessBuffer and elementSize() to UntypedVector. --- source/mijin/container/typeless_buffer.hpp | 24 ++++++++++++++++++++++ source/mijin/container/untyped_vector.hpp | 6 ++++++ 2 files changed, 30 insertions(+) diff --git a/source/mijin/container/typeless_buffer.hpp b/source/mijin/container/typeless_buffer.hpp index 92752d5..139d686 100644 --- a/source/mijin/container/typeless_buffer.hpp +++ b/source/mijin/container/typeless_buffer.hpp @@ -61,6 +61,12 @@ public: template void append(std::span data); + + template + [[nodiscard]] T& dataAt(size_type offset) MIJIN_NOEXCEPT; + + template + [[nodiscard]] const T& dataAt(size_type offset) const MIJIN_NOEXCEPT; }; template @@ -158,6 +164,24 @@ void TypelessBuffer::append(std::span data) bytes_.resize(bytes_.size() + data.size_bytes()); std::memcpy(bytes_.data() + bytes_.size() - data.size_bytes(), data.data(), data.size_bytes()); } + +template +T& TypelessBuffer::dataAt(size_type offset) MIJIN_NOEXCEPT +{ + MIJIN_ASSERT(offset % alignof(T) == 0, "Offset must be correctly aligned."); + MIJIN_ASSERT(offset + sizeof(T) < bytes_.size(), "Buffer access out-of-range."); + + return *std::bit_cast(bytes_.data() + offset); +} + +template +const T& TypelessBuffer::dataAt(size_type offset) const MIJIN_NOEXCEPT +{ + MIJIN_ASSERT(offset % alignof(T) == 0, "Offset must be correctly aligned."); + MIJIN_ASSERT(offset + sizeof(T) < bytes_.size(), "Buffer access out-of-range."); + + return *std::bit_cast(bytes_.data() + offset); +} } // namespace mijin #endif // !defined(MIJIN_CONTAINER_TYPELESS_BUFFER_HPP_INCLUDED) diff --git a/source/mijin/container/untyped_vector.hpp b/source/mijin/container/untyped_vector.hpp index a09a9ed..67a537d 100644 --- a/source/mijin/container/untyped_vector.hpp +++ b/source/mijin/container/untyped_vector.hpp @@ -85,6 +85,12 @@ public: } return buffer_.byteCapacity() / elementSize_; } + + [[nodiscard]] + std::size_t elementSize() const MIJIN_NOEXCEPT + { + return elementSize_; + } }; }