#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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 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 rollback(std::size_t saved_position) { return seek(saved_position); } [[nodiscard]] Void::Result::Result 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 skip(std::size_t count) { if (count > remaining()) { return truncated("skip", count); } m_position += count; return {}; } [[nodiscard]] Void::Result::Result> 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> 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> peekBytes(std::size_t count) const { if (count > remaining()) { return std::unexpected{truncatedError("peekBytes", count)}; } return m_bytes.subspan(m_position, count); } template requires(!std::same_as, bool>) [[nodiscard]] Void::Result::Result 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 storage{}; std::memcpy(storage.data(), bytes->data(), sizeof(T)); T value = std::bit_cast(storage); if (byteOrder != std::endian::native) { value = std::byteswap(value); } return value; } } template requires(!std::same_as, bool>) [[nodiscard]] Void::Result::Result readLittle() { return read(std::endian::little); } template requires(!std::same_as, bool>) [[nodiscard]] Void::Result::Result readBig() { return read(std::endian::big); } [[nodiscard]] Void::Result::Result readBool() { auto byte = peekBytes(1); if (!byte) { return std::unexpected{byte.error()}; } const auto raw = std::to_integer((*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 readF32(std::endian byteOrder) { static_assert(std::numeric_limits::is_iec559 && sizeof(float) == sizeof(std::uint32_t)); auto bits = read(byteOrder); if (!bits) { return std::unexpected{bits.error()}; } return std::bit_cast(*bits); } [[nodiscard]] Void::Result::Result readF64(std::endian byteOrder) { static_assert(std::numeric_limits::is_iec559 && sizeof(double) == sizeof(std::uint64_t)); auto bits = read(byteOrder); if (!bits) { return std::unexpected{bits.error()}; } return std::bit_cast(*bits); } [[nodiscard]] Void::Result::Result readString(std::size_t count) { auto bytes = readBytes(count); if (!bytes) { return std::unexpected{bytes.error()}; } return std::string{ reinterpret_cast(bytes->data()), bytes->size()}; } [[nodiscard]] Void::Result::Result subreader(std::size_t count) { auto bytes = readBytes(count); if (!bytes) { return std::unexpected{bytes.error()}; } return Reader{*bytes}; } [[nodiscard]] Void::Result::Result 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 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 truncated(std::string_view operation, std::size_t requested) const { return std::unexpected{truncatedError(operation, requested)}; } }; } // namespace Void::Binary