feat(Binary): add Writer, ByteBuffer, DecodeBudget, and explicit endian codecs (M-BINARY-02, M-BINARY-03)
This commit is contained in:
1 parent
9ac76bbcf9
commit
eacb8a4602
10 files changed
+1130
-130
No files matched your search
@@ -0,0 +1,149 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Binary
|
||||
{
|
||||
|
||||
enum class BinaryErrorCode : std::int32_t
|
||||
{
|
||||
truncated = 1,
|
||||
buffer_full,
|
||||
out_of_bounds,
|
||||
unsupported_endian,
|
||||
budget_exceeded,
|
||||
depth_exceeded,
|
||||
allocation_failed,
|
||||
invalid_bool,
|
||||
size_overflow
|
||||
};
|
||||
|
||||
[[nodiscard]] constexpr Void::Result::ErrorCode
|
||||
to_error_code(BinaryErrorCode code) noexcept
|
||||
{
|
||||
return Void::Result::ErrorCode{
|
||||
Void::Result::kBinaryErrorDomain,
|
||||
static_cast<std::int32_t>(code)};
|
||||
}
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_error(Void::Result::ErrorKind kind,
|
||||
BinaryErrorCode code,
|
||||
std::string message)
|
||||
{
|
||||
return Void::Result::Error{
|
||||
kind,
|
||||
std::move(message),
|
||||
to_error_code(code)};
|
||||
}
|
||||
|
||||
struct DecodeLimits
|
||||
{
|
||||
std::size_t max_field_bytes = 16 * 1024 * 1024;
|
||||
std::size_t max_total_bytes = 64 * 1024 * 1024;
|
||||
unsigned max_depth = 64;
|
||||
};
|
||||
|
||||
class DecodeBudget
|
||||
{
|
||||
public:
|
||||
class DepthGuard
|
||||
{
|
||||
public:
|
||||
DepthGuard() noexcept = default;
|
||||
explicit DepthGuard(DecodeBudget* budget) noexcept : budget_{budget} {}
|
||||
DepthGuard(const DepthGuard&) = delete;
|
||||
DepthGuard& operator=(const DepthGuard&) = delete;
|
||||
|
||||
DepthGuard(DepthGuard&& other) noexcept
|
||||
: budget_{std::exchange(other.budget_, nullptr)}
|
||||
{
|
||||
}
|
||||
|
||||
DepthGuard& operator=(DepthGuard&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
release();
|
||||
budget_ = std::exchange(other.budget_, nullptr);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
~DepthGuard() { release(); }
|
||||
|
||||
private:
|
||||
void release() noexcept
|
||||
{
|
||||
if (budget_ && budget_->depth_ > 0) {
|
||||
--budget_->depth_;
|
||||
}
|
||||
budget_ = nullptr;
|
||||
}
|
||||
|
||||
DecodeBudget* budget_{nullptr};
|
||||
};
|
||||
|
||||
DecodeBudget() noexcept = default;
|
||||
explicit DecodeBudget(DecodeLimits limits) noexcept : limits_{limits} {}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> consume_field(std::size_t bytes)
|
||||
{
|
||||
if (bytes > limits_.max_field_bytes) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::budget_exceeded,
|
||||
"Binary::DecodeBudget: field byte count " +
|
||||
std::to_string(bytes) +
|
||||
" exceeds max_field_bytes (" +
|
||||
std::to_string(limits_.max_field_bytes) + ")")};
|
||||
}
|
||||
if (bytes > limits_.max_total_bytes - consumed_bytes_) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::budget_exceeded,
|
||||
"Binary::DecodeBudget: total byte budget exceeded")};
|
||||
}
|
||||
consumed_bytes_ += bytes;
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<DepthGuard> enter_scope()
|
||||
{
|
||||
if (depth_ >= limits_.max_depth) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::depth_exceeded,
|
||||
"Binary::DecodeBudget: nesting depth exceeds max_depth (" +
|
||||
std::to_string(limits_.max_depth) + ")")};
|
||||
}
|
||||
++depth_;
|
||||
return DepthGuard{this};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t consumed_bytes() const noexcept
|
||||
{
|
||||
return consumed_bytes_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t remaining_bytes() const noexcept
|
||||
{
|
||||
return limits_.max_total_bytes - consumed_bytes_;
|
||||
}
|
||||
|
||||
[[nodiscard]] unsigned depth() const noexcept { return depth_; }
|
||||
|
||||
[[nodiscard]] DecodeLimits limits() const noexcept { return limits_; }
|
||||
|
||||
private:
|
||||
DecodeLimits limits_{};
|
||||
std::size_t consumed_bytes_{0};
|
||||
unsigned depth_{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Binary
|
||||
@@ -0,0 +1,257 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Binary/Budget.hpp>
|
||||
#include <Void/Binary/Reader.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <memory_resource>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Binary
|
||||
{
|
||||
|
||||
inline constexpr std::size_t kDefaultMaxByteBufferBytes = 16 * 1024 * 1024;
|
||||
|
||||
/// Immutable owning byte container produced by zero-copy ByteBuffer::freeze().
|
||||
class FrozenBytes
|
||||
{
|
||||
public:
|
||||
FrozenBytes() noexcept = default;
|
||||
|
||||
explicit FrozenBytes(std::pmr::vector<std::byte> storage) noexcept
|
||||
: m_storage{std::move(storage)}
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] std::span<const std::byte> view() const noexcept
|
||||
{
|
||||
return m_storage;
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::byte* data() const noexcept
|
||||
{
|
||||
return m_storage.data();
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return m_storage.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept { return m_storage.empty(); }
|
||||
|
||||
[[nodiscard]] Reader reader() const noexcept { return Reader{view()}; }
|
||||
|
||||
private:
|
||||
std::pmr::vector<std::byte> m_storage;
|
||||
};
|
||||
|
||||
/// PMR-backed growing binary output buffer bounded by an explicit byte ceiling.
|
||||
/// Allocation failure and capacity exhaustion preserve previously committed bytes.
|
||||
class ByteBuffer
|
||||
{
|
||||
public:
|
||||
ByteBuffer() noexcept
|
||||
: ByteBuffer(kDefaultMaxByteBufferBytes, std::pmr::get_default_resource())
|
||||
{
|
||||
}
|
||||
|
||||
explicit ByteBuffer(
|
||||
std::size_t max_bytes,
|
||||
std::pmr::memory_resource* resource = std::pmr::get_default_resource()) noexcept
|
||||
: m_data{resource ? resource : std::pmr::get_default_resource()},
|
||||
m_max_bytes{max_bytes}
|
||||
{
|
||||
}
|
||||
|
||||
template <typename R>
|
||||
requires(std::convertible_to<R, std::pmr::memory_resource*> &&
|
||||
!std::integral<std::remove_cvref_t<R>> &&
|
||||
!std::same_as<std::remove_cvref_t<R>, std::nullptr_t>)
|
||||
explicit ByteBuffer(R resource,
|
||||
std::size_t max_bytes = kDefaultMaxByteBufferBytes) noexcept
|
||||
: ByteBuffer(max_bytes, static_cast<std::pmr::memory_resource*>(resource))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> reserve(std::size_t capacity)
|
||||
{
|
||||
if (capacity > m_max_bytes) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::budget_exceeded,
|
||||
std::format(
|
||||
"Binary::ByteBuffer::reserve: requested {} bytes exceeds max_bytes ({})",
|
||||
capacity, m_max_bytes))};
|
||||
}
|
||||
try {
|
||||
m_data.reserve(capacity);
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::allocation_failed,
|
||||
"Binary::ByteBuffer::reserve: upstream allocation failed")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
append(std::span<const std::byte> bytes)
|
||||
{
|
||||
if (bytes.empty()) {
|
||||
return {};
|
||||
}
|
||||
const std::size_t old_size = m_data.size();
|
||||
if (bytes.size() > m_max_bytes - old_size) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::budget_exceeded,
|
||||
std::format(
|
||||
"Binary::ByteBuffer::append: adding {} bytes at size {} exceeds max_bytes ({})",
|
||||
bytes.size(), old_size, m_max_bytes))};
|
||||
}
|
||||
|
||||
const std::byte* const cur_begin = m_data.data();
|
||||
const std::byte* const cur_end = cur_begin + old_size;
|
||||
const bool self_aliased =
|
||||
!m_data.empty() &&
|
||||
!std::less<const std::byte*>{}(bytes.data(), cur_begin) &&
|
||||
std::less<const std::byte*>{}(bytes.data(), cur_end);
|
||||
const std::size_t alias_offset =
|
||||
self_aliased ? static_cast<std::size_t>(bytes.data() - cur_begin) : 0;
|
||||
|
||||
try {
|
||||
m_data.reserve(old_size + bytes.size());
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::allocation_failed,
|
||||
"Binary::ByteBuffer::append: upstream allocation failed")};
|
||||
}
|
||||
|
||||
if (self_aliased) {
|
||||
const std::byte* const src = m_data.data() + alias_offset;
|
||||
m_data.insert(m_data.end(), src, src + bytes.size());
|
||||
} else {
|
||||
m_data.insert(m_data.end(), bytes.begin(), bytes.end());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
write(T value, std::endian byteOrder)
|
||||
{
|
||||
if (byteOrder != std::endian::little && byteOrder != std::endian::big) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
BinaryErrorCode::unsupported_endian,
|
||||
"Binary::ByteBuffer::write: unsupported byte order")};
|
||||
}
|
||||
if constexpr (std::endian::native != std::endian::little &&
|
||||
std::endian::native != std::endian::big) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::unsupported,
|
||||
BinaryErrorCode::unsupported_endian,
|
||||
"Binary::ByteBuffer::write: mixed-endian targets are unsupported")};
|
||||
} else {
|
||||
if (byteOrder != std::endian::native) {
|
||||
value = std::byteswap(value);
|
||||
}
|
||||
const auto bytes =
|
||||
std::bit_cast<std::array<std::byte, sizeof(T)>>(value);
|
||||
return append(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<void> writeLittle(T value)
|
||||
{
|
||||
return write<T>(value, std::endian::little);
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<void> writeBig(T value)
|
||||
{
|
||||
return write<T>(value, std::endian::big);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> writeBool(bool value)
|
||||
{
|
||||
return write<std::uint8_t>(
|
||||
value ? std::uint8_t{1} : std::uint8_t{0}, std::endian::little);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
writeF32(float value, std::endian byteOrder)
|
||||
{
|
||||
static_assert(std::numeric_limits<float>::is_iec559 &&
|
||||
sizeof(float) == sizeof(std::uint32_t));
|
||||
return write<std::uint32_t>(std::bit_cast<std::uint32_t>(value), byteOrder);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
writeF64(double value, std::endian byteOrder)
|
||||
{
|
||||
static_assert(std::numeric_limits<double>::is_iec559 &&
|
||||
sizeof(double) == sizeof(std::uint64_t));
|
||||
return write<std::uint64_t>(std::bit_cast<std::uint64_t>(value), byteOrder);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> writeString(std::string_view value)
|
||||
{
|
||||
return append(std::as_bytes(std::span{value.data(), value.size()}));
|
||||
}
|
||||
|
||||
[[nodiscard]] FrozenBytes freeze() noexcept
|
||||
{
|
||||
std::pmr::vector<std::byte> moved{m_data.get_allocator()};
|
||||
moved.swap(m_data);
|
||||
return FrozenBytes{std::move(moved)};
|
||||
}
|
||||
|
||||
void clear() noexcept { m_data.clear(); }
|
||||
|
||||
[[nodiscard]] std::span<const std::byte> view() const noexcept
|
||||
{
|
||||
return m_data;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept { return m_data.size(); }
|
||||
|
||||
[[nodiscard]] std::size_t capacity() const noexcept
|
||||
{
|
||||
return m_data.capacity();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept { return m_data.empty(); }
|
||||
|
||||
[[nodiscard]] std::size_t max_bytes() const noexcept { return m_max_bytes; }
|
||||
|
||||
[[nodiscard]] std::size_t remaining_budget() const noexcept
|
||||
{
|
||||
return m_max_bytes - m_data.size();
|
||||
}
|
||||
|
||||
private:
|
||||
std::pmr::vector<std::byte> m_data;
|
||||
std::size_t m_max_bytes{kDefaultMaxByteBufferBytes};
|
||||
};
|
||||
|
||||
} // namespace Void::Binary
|
||||
+272
-122
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Binary/Budget.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
@@ -11,146 +12,295 @@
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Binary
|
||||
{
|
||||
/// Bounds-checked, non-owning reader for binary formats.
|
||||
class Reader
|
||||
{
|
||||
public:
|
||||
/// Bounds-checked, non-owning reader for binary formats.
|
||||
class Reader
|
||||
{
|
||||
public:
|
||||
class Transaction
|
||||
{
|
||||
public:
|
||||
explicit Transaction(Reader& reader) noexcept
|
||||
: m_reader{&reader}, m_saved{reader.checkpoint()}
|
||||
{
|
||||
}
|
||||
|
||||
explicit constexpr Reader(std::span<const std::byte> bytes) noexcept
|
||||
: m_bytes(bytes)
|
||||
{
|
||||
}
|
||||
Transaction(const Transaction&) = delete;
|
||||
Transaction& operator=(const Transaction&) = delete;
|
||||
|
||||
[[nodiscard]] constexpr std::size_t position() const noexcept
|
||||
{
|
||||
return m_position;
|
||||
}
|
||||
Transaction(Transaction&& other) noexcept
|
||||
: m_reader{std::exchange(other.m_reader, nullptr)},
|
||||
m_saved{other.m_saved},
|
||||
m_committed{std::exchange(other.m_committed, true)}
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::size_t size() const noexcept
|
||||
{
|
||||
return m_bytes.size();
|
||||
}
|
||||
Transaction& operator=(Transaction&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
rollback_if_uncommitted();
|
||||
m_reader = std::exchange(other.m_reader, nullptr);
|
||||
m_saved = other.m_saved;
|
||||
m_committed = std::exchange(other.m_committed, true);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::size_t remaining() const noexcept
|
||||
{
|
||||
return m_bytes.size() - m_position;
|
||||
}
|
||||
~Transaction() { rollback_if_uncommitted(); }
|
||||
|
||||
[[nodiscard]] constexpr bool empty() const noexcept
|
||||
{
|
||||
return remaining() == 0;
|
||||
}
|
||||
void commit() noexcept { m_committed = true; }
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> seek(std::size_t position)
|
||||
{
|
||||
if (position > m_bytes.size()) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Binary::Reader::seek: offset {} exceeds size {}",
|
||||
position, m_bytes.size()));
|
||||
}
|
||||
m_position = position;
|
||||
return {};
|
||||
}
|
||||
private:
|
||||
void rollback_if_uncommitted() noexcept
|
||||
{
|
||||
if (m_reader && !m_committed) {
|
||||
(void)m_reader->seek(m_saved);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> skip(std::size_t count)
|
||||
{
|
||||
if (count > remaining()) {
|
||||
return truncated("skip", count);
|
||||
}
|
||||
m_position += count;
|
||||
return {};
|
||||
}
|
||||
Reader* m_reader{nullptr};
|
||||
std::size_t m_saved{0};
|
||||
bool m_committed{false};
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
|
||||
readBytes(std::size_t count)
|
||||
{
|
||||
if (count > remaining()) {
|
||||
return std::unexpected{truncatedError("readBytes", count)};
|
||||
}
|
||||
const auto result = m_bytes.subspan(m_position, count);
|
||||
m_position += count;
|
||||
return result;
|
||||
}
|
||||
explicit constexpr Reader(std::span<const std::byte> bytes) noexcept
|
||||
: m_bytes(bytes)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
|
||||
peekBytes(std::size_t count) const
|
||||
{
|
||||
if (count > remaining()) {
|
||||
return std::unexpected{truncatedError("peekBytes", count)};
|
||||
}
|
||||
return m_bytes.subspan(m_position, count);
|
||||
}
|
||||
[[nodiscard]] constexpr std::size_t position() const noexcept
|
||||
{
|
||||
return m_position;
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<T, bool>)
|
||||
[[nodiscard]] Void::Result::Result<T>
|
||||
read(std::endian byteOrder = std::endian::native)
|
||||
{
|
||||
auto bytes = readBytes(sizeof(T));
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
std::array<std::byte, sizeof(T)> storage{};
|
||||
std::ranges::copy(*bytes, storage.begin());
|
||||
T value = std::bit_cast<T>(storage);
|
||||
if constexpr (std::endian::native != std::endian::little &&
|
||||
std::endian::native != std::endian::big) {
|
||||
return Void::Result::fail(
|
||||
"Binary::Reader::read: mixed-endian targets are "
|
||||
"unsupported");
|
||||
} else if (byteOrder != std::endian::native) {
|
||||
value = std::byteswap(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
[[nodiscard]] constexpr std::size_t size() const noexcept
|
||||
{
|
||||
return m_bytes.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
readString(std::size_t count)
|
||||
{
|
||||
auto bytes = readBytes(count);
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
return std::string{reinterpret_cast<const char*>(bytes->data()),
|
||||
bytes->size()};
|
||||
}
|
||||
[[nodiscard]] constexpr std::size_t remaining() const noexcept
|
||||
{
|
||||
return m_bytes.size() - m_position;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Reader>
|
||||
subreader(std::size_t count)
|
||||
{
|
||||
auto bytes = readBytes(count);
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
return Reader{*bytes};
|
||||
}
|
||||
[[nodiscard]] constexpr bool empty() const noexcept
|
||||
{
|
||||
return remaining() == 0;
|
||||
}
|
||||
|
||||
private:
|
||||
[[nodiscard]] constexpr std::size_t checkpoint() const noexcept
|
||||
{
|
||||
return m_position;
|
||||
}
|
||||
|
||||
std::span<const std::byte> m_bytes;
|
||||
std::size_t m_position{0};
|
||||
[[nodiscard]] Void::Result::Result<void> rollback(std::size_t saved_position)
|
||||
{
|
||||
return seek(saved_position);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error
|
||||
truncatedError(std::string_view operation,
|
||||
std::size_t requested) const
|
||||
{
|
||||
return Void::Result::Error{
|
||||
std::format("Binary::Reader::{}: requested {} bytes at "
|
||||
"offset {}, only {} "
|
||||
"remain",
|
||||
operation, requested, m_position, remaining())};
|
||||
}
|
||||
[[nodiscard]] Void::Result::Result<void> seek(std::size_t position)
|
||||
{
|
||||
if (position > m_bytes.size()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
BinaryErrorCode::out_of_bounds,
|
||||
std::format("Binary::Reader::seek: offset {} exceeds size {}",
|
||||
position, m_bytes.size()))};
|
||||
}
|
||||
m_position = position;
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
truncated(std::string_view operation,
|
||||
std::size_t requested) const
|
||||
{
|
||||
return std::unexpected{truncatedError(operation, requested)};
|
||||
}
|
||||
};
|
||||
} // namespace Void::Binary
|
||||
[[nodiscard]] Void::Result::Result<void> skip(std::size_t count)
|
||||
{
|
||||
if (count > remaining()) {
|
||||
return truncated("skip", count);
|
||||
}
|
||||
m_position += count;
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
|
||||
readBytes(std::size_t count)
|
||||
{
|
||||
if (count > remaining()) {
|
||||
return std::unexpected{truncatedError("readBytes", count)};
|
||||
}
|
||||
const auto result = m_bytes.subspan(m_position, count);
|
||||
m_position += count;
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
|
||||
readBytesChecked(std::size_t count, DecodeBudget& budget)
|
||||
{
|
||||
if (count > budget.limits().max_field_bytes ||
|
||||
count > budget.remaining_bytes()) {
|
||||
auto over = budget.consume_field(count);
|
||||
return std::unexpected{std::move(over).error()};
|
||||
}
|
||||
auto bytes = readBytes(count);
|
||||
if (!bytes) {
|
||||
return bytes;
|
||||
}
|
||||
if (auto charged = budget.consume_field(count); !charged) {
|
||||
m_position -= count;
|
||||
return std::unexpected{std::move(charged).error()};
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
|
||||
peekBytes(std::size_t count) const
|
||||
{
|
||||
if (count > remaining()) {
|
||||
return std::unexpected{truncatedError("peekBytes", count)};
|
||||
}
|
||||
return m_bytes.subspan(m_position, count);
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<T>
|
||||
read(std::endian byteOrder = std::endian::native)
|
||||
{
|
||||
if (byteOrder != std::endian::little && byteOrder != std::endian::big) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
BinaryErrorCode::unsupported_endian,
|
||||
"Binary::Reader::read: unsupported byte order")};
|
||||
}
|
||||
if constexpr (std::endian::native != std::endian::little &&
|
||||
std::endian::native != std::endian::big) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::unsupported,
|
||||
BinaryErrorCode::unsupported_endian,
|
||||
"Binary::Reader::read: mixed-endian targets are unsupported")};
|
||||
} else {
|
||||
auto bytes = readBytes(sizeof(T));
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
std::array<std::byte, sizeof(T)> storage{};
|
||||
std::ranges::copy(*bytes, storage.begin());
|
||||
T value = std::bit_cast<T>(storage);
|
||||
if (byteOrder != std::endian::native) {
|
||||
value = std::byteswap(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<T> readLittle()
|
||||
{
|
||||
return read<T>(std::endian::little);
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<T> readBig()
|
||||
{
|
||||
return read<T>(std::endian::big);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<bool> readBool()
|
||||
{
|
||||
auto byte = peekBytes(1);
|
||||
if (!byte) {
|
||||
return std::unexpected{byte.error()};
|
||||
}
|
||||
const auto raw = std::to_integer<std::uint8_t>((*byte)[0]);
|
||||
if (raw > 1) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::corrupt,
|
||||
BinaryErrorCode::invalid_bool,
|
||||
std::format(
|
||||
"Binary::Reader::readBool: invalid byte 0x{:02x} at offset {}",
|
||||
raw, m_position))};
|
||||
}
|
||||
++m_position;
|
||||
return raw == 1;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<float> readF32(std::endian byteOrder)
|
||||
{
|
||||
static_assert(std::numeric_limits<float>::is_iec559 &&
|
||||
sizeof(float) == sizeof(std::uint32_t));
|
||||
auto bits = read<std::uint32_t>(byteOrder);
|
||||
if (!bits) {
|
||||
return std::unexpected{bits.error()};
|
||||
}
|
||||
return std::bit_cast<float>(*bits);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<double> readF64(std::endian byteOrder)
|
||||
{
|
||||
static_assert(std::numeric_limits<double>::is_iec559 &&
|
||||
sizeof(double) == sizeof(std::uint64_t));
|
||||
auto bits = read<std::uint64_t>(byteOrder);
|
||||
if (!bits) {
|
||||
return std::unexpected{bits.error()};
|
||||
}
|
||||
return std::bit_cast<double>(*bits);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string> readString(std::size_t count)
|
||||
{
|
||||
auto bytes = readBytes(count);
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
return std::string{
|
||||
reinterpret_cast<const char*>(bytes->data()), bytes->size()};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Reader> subreader(std::size_t count)
|
||||
{
|
||||
auto bytes = readBytes(count);
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
return Reader{*bytes};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Reader>
|
||||
subreaderChecked(std::size_t count, DecodeBudget& budget)
|
||||
{
|
||||
auto bytes = readBytesChecked(count, budget);
|
||||
if (!bytes) {
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
return Reader{*bytes};
|
||||
}
|
||||
|
||||
private:
|
||||
std::span<const std::byte> m_bytes;
|
||||
std::size_t m_position{0};
|
||||
|
||||
[[nodiscard]] Void::Result::Error
|
||||
truncatedError(std::string_view operation, std::size_t requested) const
|
||||
{
|
||||
return make_error(
|
||||
Void::Result::ErrorKind::corrupt,
|
||||
BinaryErrorCode::truncated,
|
||||
std::format(
|
||||
"Binary::Reader::{}: requested {} bytes at offset {}, only {} remain",
|
||||
operation, requested, m_position, remaining()));
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
truncated(std::string_view operation, std::size_t requested) const
|
||||
{
|
||||
return std::unexpected{truncatedError(operation, requested)};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::Binary
|
||||
@@ -0,0 +1,183 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Binary/Budget.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Binary
|
||||
{
|
||||
|
||||
/// Non-owning, bounds-checked writer into caller-owned mutable bytes.
|
||||
class Writer
|
||||
{
|
||||
public:
|
||||
explicit constexpr Writer(std::span<std::byte> output) noexcept
|
||||
: m_output(output)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::size_t position() const noexcept
|
||||
{
|
||||
return m_position;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::size_t size() const noexcept
|
||||
{
|
||||
return m_output.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::size_t remaining() const noexcept
|
||||
{
|
||||
return m_output.size() - m_position;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool empty() const noexcept
|
||||
{
|
||||
return remaining() == 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::span<const std::byte> written() const noexcept
|
||||
{
|
||||
return m_output.subspan(0, m_position);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> seek(std::size_t position)
|
||||
{
|
||||
if (position > m_output.size()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
BinaryErrorCode::out_of_bounds,
|
||||
std::format("Binary::Writer::seek: offset {} exceeds size {}",
|
||||
position, m_output.size()))};
|
||||
}
|
||||
m_position = position;
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::size_t checkpoint() const noexcept
|
||||
{
|
||||
return m_position;
|
||||
}
|
||||
|
||||
/// Rolls back the cursor position only; does not restore overwritten bytes.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
rollbackPosition(std::size_t saved_position)
|
||||
{
|
||||
return seek(saved_position);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
writeBytes(std::span<const std::byte> bytes)
|
||||
{
|
||||
if (bytes.size() > remaining()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::buffer_full,
|
||||
std::format(
|
||||
"Binary::Writer::writeBytes: requested {} bytes at offset {}, only {} remain",
|
||||
bytes.size(), m_position, remaining()))};
|
||||
}
|
||||
if (!bytes.empty()) {
|
||||
std::memmove(m_output.data() + m_position, bytes.data(), bytes.size());
|
||||
m_position += bytes.size();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
write(T value, std::endian byteOrder)
|
||||
{
|
||||
if (byteOrder != std::endian::little && byteOrder != std::endian::big) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
BinaryErrorCode::unsupported_endian,
|
||||
"Binary::Writer::write: unsupported byte order")};
|
||||
}
|
||||
if constexpr (std::endian::native != std::endian::little &&
|
||||
std::endian::native != std::endian::big) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::unsupported,
|
||||
BinaryErrorCode::unsupported_endian,
|
||||
"Binary::Writer::write: mixed-endian targets are unsupported")};
|
||||
} else {
|
||||
if (sizeof(T) > remaining()) {
|
||||
return std::unexpected{make_error(
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
BinaryErrorCode::buffer_full,
|
||||
std::format(
|
||||
"Binary::Writer::write: requested {} bytes at offset {}, only {} remain",
|
||||
sizeof(T), m_position, remaining()))};
|
||||
}
|
||||
if (byteOrder != std::endian::native) {
|
||||
value = std::byteswap(value);
|
||||
}
|
||||
const auto bytes =
|
||||
std::bit_cast<std::array<std::byte, sizeof(T)>>(value);
|
||||
std::ranges::copy(bytes, m_output.begin() +
|
||||
static_cast<std::ptrdiff_t>(m_position));
|
||||
m_position += sizeof(T);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<void> writeLittle(T value)
|
||||
{
|
||||
return write<T>(value, std::endian::little);
|
||||
}
|
||||
|
||||
template <std::integral T>
|
||||
requires(!std::same_as<std::remove_cv_t<T>, bool>)
|
||||
[[nodiscard]] Void::Result::Result<void> writeBig(T value)
|
||||
{
|
||||
return write<T>(value, std::endian::big);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> writeBool(bool value)
|
||||
{
|
||||
return write<std::uint8_t>(
|
||||
value ? std::uint8_t{1} : std::uint8_t{0}, std::endian::little);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
writeF32(float value, std::endian byteOrder)
|
||||
{
|
||||
static_assert(std::numeric_limits<float>::is_iec559 &&
|
||||
sizeof(float) == sizeof(std::uint32_t));
|
||||
return write<std::uint32_t>(std::bit_cast<std::uint32_t>(value), byteOrder);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
writeF64(double value, std::endian byteOrder)
|
||||
{
|
||||
static_assert(std::numeric_limits<double>::is_iec559 &&
|
||||
sizeof(double) == sizeof(std::uint64_t));
|
||||
return write<std::uint64_t>(std::bit_cast<std::uint64_t>(value), byteOrder);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> writeString(std::string_view value)
|
||||
{
|
||||
return writeBytes(std::as_bytes(std::span{value.data(), value.size()}));
|
||||
}
|
||||
|
||||
private:
|
||||
std::span<std::byte> m_output;
|
||||
std::size_t m_position{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Binary
|
||||
Reference in new issue
Block a user