Added UntypedVector type.

This commit is contained in:
Patrick 2024-12-25 01:56:45 +01:00
parent 3c7b7212b9
commit 43e772bb89
2 changed files with 94 additions and 0 deletions

View File

@ -37,9 +37,12 @@ public:
private:
std::vector<std::byte> 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); }

View File

@ -0,0 +1,91 @@
#pragma once
#if !defined(MIJIN_CONTAINER_UNTYPED_VECTOR_HPP_INCLUDED)
#define MIJIN_CONTAINER_UNTYPED_VECTOR_HPP_INCLUDED 1
#include <stdexcept>
#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<std::byte> operator[](size_type index)
{
return at(index);
}
std::span<const std::byte> 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<std::byte> at(size_type index)
{
if (index > size())
{
throw std::out_of_range("Index out of range.");
}
return buffer_.makeSpan<std::byte>().subspan(index * elementSize_, elementSize_);
}
[[nodiscard]]
std::span<const std::byte> at(size_type index) const
{
if (index > size())
{
throw std::out_of_range("Index out of range.");
}
return buffer_.makeSpan<std::byte>().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)