Files
Library/docs/roadmap/modules/Binary.md
T

9.3 KiB
Raw Blame History

Binary readers, writers and codec boundaries

Status: planning only; all feature tasks are PLANNED. Baseline: f1f9ba375b22abf1adcc7c550ec21ac20895c0a4, inspected 2026-11-24.

Existing baseline

Binary currently depends on Functional and has one public header, Reader. Void::Binary::Reader borrows span<const byte>, tracks its position and provides seek/skip, read/peek bytes, integral endian decoding, copied strings and bounded subreaders. Results use Void::Result::Result<T>. Returned byte spans/subreaders do not extend input lifetime. Integral reads use copied storage/bit_cast, so no aligned-load or aliasing requirement is imposed on input. The default byte order is native; it must not silently define a portable file or protocol format.

Reader tests check big-endian reading, truncation leaving position unchanged, and bounded children. No writer, varint, structured codec, stream backend or format registry exists in this source inventory. Scoped graph coverage reported no recorded gaps and the full reader/test were read directly.

Ownership and backend decision

Per C-01/C-02/C-07, Binary owns representation mechanics; Data owns values/schema/reflection, Archive owns archive layouts, Storage owns its persisted records and Net owns protocol frames. IO owns actual transfers. Binary never imports these higher modules or starts workers. Choose native span cursors plus standard byte/ bit/PMR tools. Do not add a generic serialization dependency or put JSON schema logic inside a byte reader. Checksums for storage integrity remain distinct from authentication; no homegrown cryptographic primitive is introduced.

NEW cursor and buffer APIs

Illustrative NEW shape in NEW include/Void/Binary/Writer.hpp and NEW include/Void/Binary/Varint.hpp (signatures are not existing compiling examples):

namespace Void::Binary {
class Writer {
public:
  explicit Writer(std::span<std::byte> output) noexcept;
  std::size_t position() const noexcept;
  std::size_t remaining() const noexcept;
  Void::Result::Result<void> writeBytes(std::span<const std::byte>);
  template<std::integral T> requires (!std::same_as<T,bool>)
  Void::Result::Result<void> write(T, std::endian order); // no wire default
  Void::Result::Result<void> writeUvarint(std::uint64_t);
};
struct DecodeLimits {
  std::size_t max_field_bytes = 16 * 1024 * 1024;
  std::size_t max_total_bytes = 64 * 1024 * 1024;
  unsigned max_depth = 64;
};
Void::Result::Result<std::uint64_t> readUvarint(Reader&);
}

Writer borrows mutable output and owns only its cursor; caller owns the buffer through all access. Every primitive validates capacity before modifying bytes or position. writeBytes supports overlapping source/output via memmove-equivalent behavior; integral encoding uses local fixed storage. Composite encoders validate their exact measured size before publication or stage into bounded scratch. A cursor checkpoint rolls back position only; it must not claim to restore overwritten caller bytes. An explicit transactional encoder stages data when strong all-or-nothing bytes are required.

NEW ByteBuffer is an owning pmr::vector<byte> wrapper with an explicit Memory resource and a default 16 MiB capacity ceiling; growth checks current size + requested bytes and resource admission before reserve. It does not expose stable pointers across growth. freeze() transfers owned storage without copying and makes published bytes immutable. A borrowed span never becomes owning merely because it came from freeze().view(); the frozen owner must remain alive. Empty output is valid; a zero ceiling permits only empty output, never unlimited allocation.

Reader adds named readLittle<T>/readBig<T>, cursor transactions for compound parsing, and structured domain code/offset/requested/remaining diagnostics mapped through Functional. Preserve current primitive truncation behavior. Unsupported endian/type checks happen before consuming bytes. Floats use explicitly named IEEE binary32/binary64 codecs and capability checks (is_iec559 and width); no long-double object serialization. Booleans accept only 0/1. Signed integers have an explicit two's-complement wire contract; padding/native object representations are never copied as a schema.

Varints, strings and incremental decoding

Unsigned varints use seven payload bits per byte, low group first, maximum ten bytes for uint64. Byte ten may contain only payload bit 0; continuation there is malformed. Reject nonminimal encodings by default, distinguishing truncated input from overflow and noncanonical data. Signed varints use explicit ZigZag operations in unsigned arithmetic, including INT64_MIN, without signed shifts/overflow. A compatibility permissive decoder must be named; it cannot be selected implicitly by a signed or storage format.

Length-prefixed byte fields decode length, check configured field and remaining-total limits, check size_t conversion, then borrow/copy as requested. Strings are bytes unless an explicitly named UTF codec is selected by the caller. Embedded NUL is not terminator. Nested limits are shared cumulative budget state, so children cannot each claim a fresh 64 MiB allowance. Decompression belongs to Archive; advertised decompressed sizes are not permission for Binary to allocate arbitrary memory.

NEW incremental decoding returns complete(value), need_more(minimum_bytes) or a terminal error plus consumed-byte count. need_more owns any retained partial bytes (at most ten for a varint); it never retains a temporary input span. Field assemblers reserve within the same aggregate budget and report cancellation between input chunks through a caller-driven adapter. Cancellation does not reinterpret already emitted streaming output as undone. Binary owns no async operation options; IO/Async adapters use their shared types under C-03.

Codec boundary with Data and Storage

The selected NEW general value codec is VoidValueBinary V1, owned and versioned by Data with an adapter using Binary. Binary supplies primitives only. Data assigns value tags, duplicate policy and schema envelope; Storage independently assigns WAL/checkpoint framing, checksums and recovery rules. Neither codec may serialize raw Value object memory. Do not add CBOR/MessagePack/Protocol Buffers compatibility claims to this native format. Later standards adapters need named capability tasks and conformance fixtures.

Ordered tasks

Task Phase; dependencies Scope and acceptance Recommended role
M-BINARY-01 P0; current reader Freeze cursor, lifetime, byte-order and failure fixtures; enumerate every current consumer before deprecating native-endian defaults. sol_implementer
M-BINARY-02 P1; M-BINARY-01; Functional error gate Implement Writer, explicit endian primitives and structured diagnostics; truncation/unsupported operations change neither cursor nor bytes. sol_implementer
M-BINARY-03 P1; M-BINARY-02; Memory bounded-resource gate Add owning ByteBuffer, immutable transfer and cumulative budgets; allocation failure and capacity exhaustion preserve published storage. sol_implementer
M-BINARY-04 P2; M-BINARY-02 Add canonical varints/ZigZag, length fields and explicit floating codecs; golden bytes, invalid encodings and all uint64 boundaries pass. sol_implementer
M-BINARY-05 P2; M-BINARY-03–04 Add incremental parsing and Data adapter primitives; all chunk boundaries produce identical values and retained bytes remain within limits. sol_implementer
M-BINARY-06 P3; M-BINARY-05; Data V1 codec gate Publish portable format examples, fuzz targets and installed minimal consumers; differential round trips and independent golden fixtures pass. sol_implementer

Validation, migration and resource evidence

CURRENT checks are the existing Reader suite and parent baseline; no build was rerun. PROPOSED tests include unaligned spans, empty/exact/one-byte-short output, overlapping writeBytes, endian fixtures independent of host, noncanonical varints, all truncated prefixes, INT64_MIN, NaN payload handling and nested cumulative-budget exhaustion. Fuzz decode plus writer replay; include malicious length values near SIZE_MAX before any allocation. Cross-endian emulation/targets are proposed prerequisites, not current compiler/platform evidence. Shared schema owners review the V1 tag and framing fixtures.

Measure scalar and batched cursor operations, copied versus borrowed fields, incremental chunk sizes and allocation counts with PERFORMANCE: p50/p95/p99, throughput, peak RSS/CPU and build cost. Track scratch capacity, retained partial fields and owning-buffer capacity separately. No benchmark was executed for this plan.

Migration preserves Reader's current names through adapters and adds explicit endian overloads before removing ambiguous defaults in a major release. File/ wire bytes are versioned by their owner; changing helper APIs cannot rewrite them. Rollback keeps old readers until new-format writes are disabled or compatibility readers are deployed. See Data, Memory, Storage, IO, VALIDATION, DEPENDENCIES, DELIVERY and requirements.