diff --git a/include/Void/Binary/Budget.hpp b/include/Void/Binary/Budget.hpp new file mode 100644 index 0000000..5c1a10f --- /dev/null +++ b/include/Void/Binary/Budget.hpp @@ -0,0 +1,149 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +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(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 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 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 diff --git a/include/Void/Binary/ByteBuffer.hpp b/include/Void/Binary/ByteBuffer.hpp new file mode 100644 index 0000000..a0fe245 --- /dev/null +++ b/include/Void/Binary/ByteBuffer.hpp @@ -0,0 +1,257 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 storage) noexcept + : m_storage{std::move(storage)} + { + } + + [[nodiscard]] std::span 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 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 + requires(std::convertible_to && + !std::integral> && + !std::same_as, std::nullptr_t>) + explicit ByteBuffer(R resource, + std::size_t max_bytes = kDefaultMaxByteBufferBytes) noexcept + : ByteBuffer(max_bytes, static_cast(resource)) + { + } + + [[nodiscard]] Void::Result::Result 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 + append(std::span 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{}(bytes.data(), cur_begin) && + std::less{}(bytes.data(), cur_end); + const std::size_t alias_offset = + self_aliased ? static_cast(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 + requires(!std::same_as, bool>) + [[nodiscard]] Void::Result::Result + 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>(value); + return append(bytes); + } + } + + template + requires(!std::same_as, bool>) + [[nodiscard]] Void::Result::Result writeLittle(T value) + { + return write(value, std::endian::little); + } + + template + requires(!std::same_as, bool>) + [[nodiscard]] Void::Result::Result writeBig(T value) + { + return write(value, std::endian::big); + } + + [[nodiscard]] Void::Result::Result writeBool(bool value) + { + return write( + value ? std::uint8_t{1} : std::uint8_t{0}, std::endian::little); + } + + [[nodiscard]] Void::Result::Result + writeF32(float value, std::endian byteOrder) + { + static_assert(std::numeric_limits::is_iec559 && + sizeof(float) == sizeof(std::uint32_t)); + return write(std::bit_cast(value), byteOrder); + } + + [[nodiscard]] Void::Result::Result + writeF64(double value, std::endian byteOrder) + { + static_assert(std::numeric_limits::is_iec559 && + sizeof(double) == sizeof(std::uint64_t)); + return write(std::bit_cast(value), byteOrder); + } + + [[nodiscard]] Void::Result::Result writeString(std::string_view value) + { + return append(std::as_bytes(std::span{value.data(), value.size()})); + } + + [[nodiscard]] FrozenBytes freeze() noexcept + { + std::pmr::vector moved{m_data.get_allocator()}; + moved.swap(m_data); + return FrozenBytes{std::move(moved)}; + } + + void clear() noexcept { m_data.clear(); } + + [[nodiscard]] std::span 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 m_data; + std::size_t m_max_bytes{kDefaultMaxByteBufferBytes}; +}; + +} // namespace Void::Binary \ No newline at end of file diff --git a/include/Void/Binary/Reader.hpp b/include/Void/Binary/Reader.hpp index 0d749b0..2ed66e6 100644 --- a/include/Void/Binary/Reader.hpp +++ b/include/Void/Binary/Reader.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -11,146 +12,295 @@ #include #include #include +#include #include #include +#include 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 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 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 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> - 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 bytes) noexcept + : m_bytes(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); - } + [[nodiscard]] constexpr std::size_t position() const noexcept + { + return m_position; + } - template - requires(!std::same_as) - [[nodiscard]] Void::Result::Result - read(std::endian byteOrder = std::endian::native) - { - auto bytes = readBytes(sizeof(T)); - if (!bytes) { - return std::unexpected{bytes.error()}; - } - std::array storage{}; - std::ranges::copy(*bytes, storage.begin()); - T value = std::bit_cast(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 - 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]] constexpr std::size_t remaining() const noexcept + { + return m_bytes.size() - m_position; + } - [[nodiscard]] Void::Result::Result - 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 m_bytes; - std::size_t m_position{0}; + [[nodiscard]] Void::Result::Result 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 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 - truncated(std::string_view operation, - std::size_t requested) const - { - return std::unexpected{truncatedError(operation, requested)}; - } - }; -} // namespace Void::Binary + [[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::ranges::copy(*bytes, storage.begin()); + 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 \ No newline at end of file diff --git a/include/Void/Binary/Writer.hpp b/include/Void/Binary/Writer.hpp new file mode 100644 index 0000000..5084c6f --- /dev/null +++ b/include/Void/Binary/Writer.hpp @@ -0,0 +1,183 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Binary +{ + +/// Non-owning, bounds-checked writer into caller-owned mutable bytes. +class Writer +{ +public: + explicit constexpr Writer(std::span 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 written() const noexcept + { + return m_output.subspan(0, m_position); + } + + [[nodiscard]] Void::Result::Result 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 + rollbackPosition(std::size_t saved_position) + { + return seek(saved_position); + } + + [[nodiscard]] Void::Result::Result + writeBytes(std::span 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 + requires(!std::same_as, bool>) + [[nodiscard]] Void::Result::Result + 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>(value); + std::ranges::copy(bytes, m_output.begin() + + static_cast(m_position)); + m_position += sizeof(T); + return {}; + } + } + + template + requires(!std::same_as, bool>) + [[nodiscard]] Void::Result::Result writeLittle(T value) + { + return write(value, std::endian::little); + } + + template + requires(!std::same_as, bool>) + [[nodiscard]] Void::Result::Result writeBig(T value) + { + return write(value, std::endian::big); + } + + [[nodiscard]] Void::Result::Result writeBool(bool value) + { + return write( + value ? std::uint8_t{1} : std::uint8_t{0}, std::endian::little); + } + + [[nodiscard]] Void::Result::Result + writeF32(float value, std::endian byteOrder) + { + static_assert(std::numeric_limits::is_iec559 && + sizeof(float) == sizeof(std::uint32_t)); + return write(std::bit_cast(value), byteOrder); + } + + [[nodiscard]] Void::Result::Result + writeF64(double value, std::endian byteOrder) + { + static_assert(std::numeric_limits::is_iec559 && + sizeof(double) == sizeof(std::uint64_t)); + return write(std::bit_cast(value), byteOrder); + } + + [[nodiscard]] Void::Result::Result writeString(std::string_view value) + { + return writeBytes(std::as_bytes(std::span{value.data(), value.size()})); + } + +private: + std::span m_output; + std::size_t m_position{0}; +}; + +} // namespace Void::Binary diff --git a/src/Binary/module.cmake b/src/Binary/module.cmake index a7d9cca..f3c2bc7 100644 --- a/src/Binary/module.cmake +++ b/src/Binary/module.cmake @@ -1,3 +1,3 @@ void_add_module(Binary - INTERNAL_DEPS Functional + INTERNAL_DEPS Functional Memory ) diff --git a/tests/package/Binary/main.cpp b/tests/package/Binary/main.cpp index b862cba..86de4ab 100644 --- a/tests/package/Binary/main.cpp +++ b/tests/package/Binary/main.cpp @@ -1,4 +1,7 @@ +#include #include +#include +#include #include #include @@ -7,8 +10,31 @@ int main() { - const std::array bytes{std::byte{0x01}, std::byte{0x02}}; - Void::Binary::Reader reader{bytes}; - const auto value = reader.read(std::endian::big); - return value && *value == 0x0102 ? 0 : 1; -} + std::array scratch{}; + Void::Binary::Writer writer{scratch}; + if (!writer.writeBig(0x0102) || + !writer.writeBool(true) || + !writer.writeF64(3.5, std::endian::little)) { + return 1; + } + + Void::Binary::Reader reader{writer.written()}; + const auto u16 = reader.readBig(); + const auto b = reader.readBool(); + const auto d = reader.readF64(std::endian::little); + if (!u16 || *u16 != 0x0102 || !b || !*b || !d || *d != 3.5) { + return 1; + } + + Void::Memory::BudgetResource budget{1024}; + Void::Binary::ByteBuffer buf{&budget, 64}; + if (!buf.writeLittle(0x11223344u) || + !buf.writeString("ok")) { + return 1; + } + const auto frozen = buf.freeze(); + auto fr = frozen.reader(); + const auto v = fr.readLittle(); + const auto s = fr.readString(2); + return v && *v == 0x11223344u && s && *s == "ok" ? 0 : 1; +} \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 8672c31..a8bf104 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -91,13 +91,13 @@ if(_has_memory) run_consumer(MemoryOnly "${install_prefix}" "MemoryOnly" ${_no_external_deps}) endif() -has_modules(_has_binary Binary) +has_modules(_has_binary Binary Memory Functional Core) if(_has_binary) run_consumer(Binary "${install_prefix}" "Binary" ${_no_external_deps}) endif() # Foundation consumer with Core-formatting bridge and zero external packages. -has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Core) +has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) run_consumer(Foundation "${install_prefix}" "Foundation" ${_no_external_deps}) endif() diff --git a/tests/standalone/Binary/ByteBuffer.cpp b/tests/standalone/Binary/ByteBuffer.cpp new file mode 100644 index 0000000..22c74a4 --- /dev/null +++ b/tests/standalone/Binary/ByteBuffer.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +Void::Testing::Test binary_byte_buffer_limits_oom_preserve_and_zero_copy_freeze() +{ + using Void::Binary::BinaryErrorCode; + using Void::Binary::ByteBuffer; + + // Zero ceiling permits empty output only. + ByteBuffer zero_cap{std::size_t{0}}; + Void::Testing::expect(zero_cap.writeString("").has_value()); + const auto zero_fail = zero_cap.writeBool(true); + Void::Testing::expect(!zero_fail.has_value()); + Void::Testing::expect(zero_fail.error().code() == + Void::Binary::to_error_code(BinaryErrorCode::budget_exceeded)); + + // Upstream BudgetResource failure preserves previously committed bytes. + Void::Memory::BudgetResource budget{16}; + ByteBuffer buf{&budget, 1024}; + Void::Testing::require(buf.writeBig(0x01020304u).has_value()); + const auto before_oom_size = buf.size(); + const std::array big_chunk{}; + const auto oom = buf.append(big_chunk); + Void::Testing::expect(!oom.has_value()); + Void::Testing::expect(oom.error().code() == + Void::Binary::to_error_code(BinaryErrorCode::allocation_failed)); + Void::Testing::expect_eq(buf.size(), before_oom_size); + + // Self-aliasing append works safely even across buffer growth. + ByteBuffer growable{256}; + Void::Testing::require(growable.writeString("abc").has_value()); + for (int i = 0; i < 4; ++i) { + Void::Testing::require(growable.append(growable.view()).has_value()); + } + Void::Testing::expect_eq(growable.size(), std::size_t{48}); + const std::byte* const pre_freeze_ptr = growable.view().data(); + + const auto frozen = growable.freeze(); + Void::Testing::expect(growable.empty()); + Void::Testing::expect(frozen.data() == pre_freeze_ptr); + Void::Testing::expect_eq(frozen.size(), std::size_t{48}); + auto r = frozen.reader(); + const auto prefix = r.readString(6); + Void::Testing::require(prefix.has_value()); + Void::Testing::expect_eq(*prefix, std::string{"abcabc"}); +} \ No newline at end of file diff --git a/tests/standalone/Binary/Reader.cpp b/tests/standalone/Binary/Reader.cpp index c18d9fc..76c68eb 100644 --- a/tests/standalone/Binary/Reader.cpp +++ b/tests/standalone/Binary/Reader.cpp @@ -29,3 +29,100 @@ Void::Testing::Test binary_reader_subreader_is_bounded() Void::Testing::expect(!child->readBytes(1).has_value()); Void::Testing::expect_eq(reader.remaining(), static_cast(1)); } + +Void::Testing::Test binary_reader_explicit_endian_bool_floats_and_transactions() +{ + const std::array raw{ + std::byte{0x12}, std::byte{0x34}, std::byte{0x56}, std::byte{0x78}, + std::byte{0x78}, std::byte{0x56}, std::byte{0x34}, std::byte{0x12}, + std::byte{0x01}, std::byte{0x02}, + std::byte{0x3F}, std::byte{0x80}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0x08}, std::byte{0x40}}; + + Void::Binary::Reader reader{raw}; + const auto big32 = reader.readBig(); + const auto lit32 = reader.readLittle(); + Void::Testing::require(big32.has_value() && lit32.has_value()); + Void::Testing::expect_eq(*big32, std::uint32_t{0x12345678u}); + Void::Testing::expect_eq(*lit32, std::uint32_t{0x12345678u}); + + // Unsupported endian fails without moving cursor. + const auto saved_pos = reader.checkpoint(); + const auto invalid_endian = static_cast(99); + const auto bad_end = reader.read(invalid_endian); + Void::Testing::expect(!bad_end.has_value()); + Void::Testing::expect(bad_end.error().code() == + Void::Binary::to_error_code(Void::Binary::BinaryErrorCode::unsupported_endian)); + Void::Testing::expect_eq(reader.position(), saved_pos); + + // Valid bool advances, invalid bool (0x02) leaves cursor untouched. + const auto b_true = reader.readBool(); + Void::Testing::require(b_true.has_value()); + Void::Testing::expect(*b_true); + const std::size_t before_bad_bool = reader.position(); + const auto b_bad = reader.readBool(); + Void::Testing::expect(!b_bad.has_value()); + Void::Testing::expect(b_bad.error().code() == + Void::Binary::to_error_code(Void::Binary::BinaryErrorCode::invalid_bool)); + Void::Testing::expect_eq(reader.position(), before_bad_bool); + + // Skip the invalid bool byte and verify transaction rollback/commit & floats. + Void::Testing::require(reader.skip(1).has_value()); + { + Void::Binary::Reader::Transaction tx{reader}; + const auto f1 = reader.readF32(std::endian::big); + Void::Testing::require(f1.has_value()); + Void::Testing::expect_eq(*f1, 1.0F); + } // auto-rollback + Void::Testing::expect_eq(reader.position(), before_bad_bool + 1); + + { + Void::Binary::Reader::Transaction tx{reader}; + const auto f1 = reader.readF32(std::endian::big); + const auto d1 = reader.readF64(std::endian::little); + Void::Testing::require(f1.has_value() && d1.has_value()); + Void::Testing::expect_eq(*f1, 1.0F); + Void::Testing::expect_eq(*d1, 3.0); + tx.commit(); + } + Void::Testing::expect(reader.empty()); +} + +Void::Testing::Test binary_reader_cumulative_decode_budget_across_children() +{ + using Void::Binary::BinaryErrorCode; + const std::array bytes{ + std::byte{1}, std::byte{2}, std::byte{3}, + std::byte{4}, std::byte{5}, std::byte{6}, + std::byte{7}, std::byte{8}}; + Void::Binary::Reader root{bytes}; + Void::Binary::DecodeBudget budget{ + Void::Binary::DecodeLimits{.max_field_bytes = 5, .max_total_bytes = 6, .max_depth = 2}}; + + auto g1 = budget.enter_scope(); + auto g2 = budget.enter_scope(); + auto g3 = budget.enter_scope(); + Void::Testing::require(g1.has_value() && g2.has_value()); + Void::Testing::expect(!g3.has_value()); + Void::Testing::expect(g3.error().code() == + Void::Binary::to_error_code(BinaryErrorCode::depth_exceeded)); + + auto child = root.subreaderChecked(4, budget); + Void::Testing::require(child.has_value()); + Void::Testing::expect_eq(budget.consumed_bytes(), std::size_t{4}); + Void::Testing::expect_eq(budget.remaining_bytes(), std::size_t{2}); + + // Shared cumulative limit rejects child consuming past remaining total bytes. + const auto over_total = child->readBytesChecked(3, budget); + Void::Testing::expect(!over_total.has_value()); + Void::Testing::expect(over_total.error().code() == + Void::Binary::to_error_code(BinaryErrorCode::budget_exceeded)); + Void::Testing::expect_eq(budget.consumed_bytes(), std::size_t{4}); + + // Truncated read in child fails with truncated BEFORE charging budget. + auto ok_slice = child->readBytesChecked(2, budget); + Void::Testing::require(ok_slice.has_value()); + Void::Testing::expect_eq(budget.consumed_bytes(), std::size_t{6}); + Void::Testing::expect(!root.subreaderChecked(3, budget).has_value()); +} diff --git a/tests/standalone/Binary/Writer.cpp b/tests/standalone/Binary/Writer.cpp new file mode 100644 index 0000000..14d3779 --- /dev/null +++ b/tests/standalone/Binary/Writer.cpp @@ -0,0 +1,84 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +Void::Testing::Test binary_writer_roundtrip_and_golden_bytes() +{ + std::array buf{}; + Void::Binary::Writer writer{buf}; + + Void::Testing::require(writer.writeBig(0x1234).has_value()); + Void::Testing::require(writer.writeLittle(0x89ABCDEFu).has_value()); + Void::Testing::require(writer.writeBool(false).has_value()); + Void::Testing::require(writer.writeBool(true).has_value()); + Void::Testing::require(writer.writeF32(-2.5F, std::endian::big).has_value()); + Void::Testing::require(writer.writeF64(6.25, std::endian::little).has_value()); + Void::Testing::require(writer.writeString("hi").has_value()); + + const auto written = writer.written(); + Void::Testing::expect_eq(written.size(), std::size_t{2 + 4 + 1 + 1 + 4 + 8 + 2}); + Void::Testing::expect(written[0] == std::byte{0x12}); + Void::Testing::expect(written[1] == std::byte{0x34}); + Void::Testing::expect(written[2] == std::byte{0xEF}); + Void::Testing::expect(written[5] == std::byte{0x89}); + + Void::Binary::Reader reader{written}; + Void::Testing::expect_eq(*reader.readBig(), std::uint16_t{0x1234}); + Void::Testing::expect_eq(*reader.readLittle(), std::uint32_t{0x89ABCDEFu}); + Void::Testing::expect(!*reader.readBool()); + Void::Testing::expect(*reader.readBool()); + Void::Testing::expect_eq(*reader.readF32(std::endian::big), -2.5F); + Void::Testing::expect_eq(*reader.readF64(std::endian::little), 6.25); + Void::Testing::expect_eq(*reader.readString(2), std::string{"hi"}); + Void::Testing::expect(reader.empty()); +} + +Void::Testing::Test binary_writer_failure_atomicity_overlap_and_rollback() +{ + using Void::Binary::BinaryErrorCode; + + std::array buf{ + std::byte{0xAA}, std::byte{0xBB}, std::byte{0xCC}, + std::byte{0xDD}, std::byte{0xEE}, std::byte{0xFF}}; + Void::Binary::Writer writer{buf}; + + // Overlapping source slice copied forward inside same backing array. + Void::Testing::require( + writer.writeBytes(std::span{buf.data() + 1, 3}).has_value()); + Void::Testing::expect_eq(writer.position(), std::size_t{3}); + Void::Testing::expect(buf[0] == std::byte{0xBB}); + Void::Testing::expect(buf[1] == std::byte{0xCC}); + Void::Testing::expect(buf[2] == std::byte{0xDD}); + + // Insufficient remaining capacity leaves position and untouched tail unchanged. + const auto cp = writer.checkpoint(); + const auto full_err = writer.writeBig(0x11223344u); + Void::Testing::expect(!full_err.has_value()); + Void::Testing::expect(full_err.error().code() == + Void::Binary::to_error_code(BinaryErrorCode::buffer_full)); + Void::Testing::expect_eq(writer.position(), cp); + Void::Testing::expect(buf[3] == std::byte{0xDD}); + + // Unsupported endian fails without moving cursor or touching output. + const auto end_err = + writer.write(0x1122, static_cast(77)); + Void::Testing::expect(!end_err.has_value()); + Void::Testing::expect(end_err.error().code() == + Void::Binary::to_error_code(BinaryErrorCode::unsupported_endian)); + Void::Testing::expect_eq(writer.position(), cp); + + // Rollback position only; out-of-bounds seek returns out_of_bounds. + Void::Testing::require(writer.rollbackPosition(1).has_value()); + Void::Testing::expect_eq(writer.position(), std::size_t{1}); + const auto oob = writer.seek(99); + Void::Testing::expect(!oob.has_value()); + Void::Testing::expect(oob.error().code() == + Void::Binary::to_error_code(BinaryErrorCode::out_of_bounds)); +} \ No newline at end of file