Files
Library/include/Void/Binary/Reader.hpp
T

306 lines
9.1 KiB
C++

#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>
#include <utility>
namespace Void::Binary
{
/// 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()}
{
}
Transaction(const Transaction&) = delete;
Transaction& operator=(const Transaction&) = delete;
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)}
{
}
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;
}
~Transaction() { rollback_if_uncommitted(); }
void commit() noexcept { m_committed = true; }
private:
void rollback_if_uncommitted() noexcept
{
if (m_reader && !m_committed) {
(void)m_reader->seek(m_saved);
}
}
Reader* m_reader{nullptr};
std::size_t m_saved{0};
bool m_committed{false};
};
explicit constexpr Reader(std::span<const std::byte> bytes) noexcept
: m_bytes(bytes)
{
}
[[nodiscard]] constexpr std::size_t position() const noexcept
{
return m_position;
}
[[nodiscard]] constexpr std::size_t size() const noexcept
{
return m_bytes.size();
}
[[nodiscard]] constexpr std::size_t remaining() const noexcept
{
return m_bytes.size() - m_position;
}
[[nodiscard]] constexpr bool empty() const noexcept
{
return remaining() == 0;
}
[[nodiscard]] constexpr std::size_t checkpoint() const noexcept
{
return m_position;
}
[[nodiscard]] Void::Result::Result<void> rollback(std::size_t saved_position)
{
return seek(saved_position);
}
[[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> 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