I/O
Bytes, files, streams, and async streams
from io import BytesIO
from typing import Annotated
from binal import BinaryModel, Prefixed, UInt8, UInt16
class Packet(BinaryModel, byte_order="big"):
version: UInt8
payload: Annotated[bytes, Prefixed(UInt16)]
packet = Packet(version=1, payload=b"Hello")
data = packet.encode()
packet = Packet.decode(data)
packet = Packet.decode(memoryview(data))
packet.write_file("packet.bin")
packet = Packet.read_file("packet.bin") Streams
Streams are read incrementally, one record at a time. read() decodes a
single record and leaves the stream positioned exactly after it, so
consecutive records can be read from the same stream; iter_read()
yields records until end of stream. Only the current record is
buffered, so a large stream is never slurped into memory.
stream = BytesIO(
Packet(version=1, payload=b"Hello").encode()
+ Packet(version=2, payload=b"World").encode()
)
packet = Packet.read(stream) # Packet(version=1, payload=b'Hello')
packets = list(Packet.iter_read(stream))
# [Packet(version=2, payload=b'World')] A record that makes no progress (a zero-size record with more data
after it) raises DecodeError instead of looping forever.
Incremental parsing
Packet.incremental_parser() returns a parser typed for the model: IncrementalParser[Packet], so feed() returns list[Packet]. feed(data) appends to a buffer and returns the records completed by that chunk; bytes after a record’s end are retained for the next record. close() signals end of input and returns the final record, or None if the buffer is empty. feed after close raises.
parser = Packet.incremental_parser() # IncrementalParser[Packet]
records = parser.feed(b"\x01\x00\x05Hel") # [] — record incomplete
records += parser.feed(b"lo") # [Packet(version=1, payload=b'Hello')]
final = parser.close() # None — buffer empty An incomplete record is kept for the next chunk; a malformed record raises immediately. Streaming code distinguishes the two by branching on DecodeError.is_incomplete (plus claimed, the byte count the failing read needed), never on the reason string — a malformed input that happens to raise “Unexpected end of input” is not buffered until end of input.
Random access
BinaryReader.open(path) opens a file for random-access reading without loading it: reads go through os.pread. read_at(model, offset, size=None, context=None) decodes one record at an absolute offset — reading exactly size bytes, or, for size=None, a self-delimiting record bounded by Limits.max_model_size and end of file. Bounds are validated before reading, as a structured DecodeError, and the reader’s position is restored afterwards, on success and on failure. BinaryWriter.open(path, "wb" / "r+b") and write_at(instance | bytes, offset) are the symmetric write side.
from binal import BinaryReader, BinaryWriter
with BinaryReader.open("dataset.bin") as reader:
record = reader.read_at(Record, offset=entry.offset, size=entry.size)
# or, with context from the index entry:
record = reader.read_at(
Record, offset=entry.offset, size=entry.size, context={"flags": entry.flags}
)
with BinaryWriter.open("dataset.bin", "r+b") as writer:
writer.write_at(record, offset=entry.offset) No indexed-file framework is needed: read an index model, then read_at per entry. A record in a sized window must consume exactly size bytes — trailing bytes are an error, and needing more is a truncation error.
Async streams
The async API works with any async reader/writer pair, e.g.
asyncio.StreamReader / asyncio.StreamWriter. read_async() reads
one record and requests no byte past its end, so the stream can be
handed on afterwards; iter_read_async() reads records until end of
stream, reading ahead in chunks, so it owns the stream until it is
exhausted. write_async() writes the encoded record and awaits
drain().
import asyncio
async def main() -> None:
reader = asyncio.StreamReader()
reader.feed_data(packet.encode())
reader.feed_eof()
one = await Packet.read_async(reader)
# Packet(version=1, payload=b'Hello')
reader = asyncio.StreamReader()
reader.feed_data(
Packet(version=1, payload=b"Hello").encode()
+ Packet(version=2, payload=b"World").encode()
)
reader.feed_eof()
packets = [p async for p in Packet.iter_read_async(reader)]
# [Packet(version=1, ...), Packet(version=2, ...)]
asyncio.run(main()) write_async documents that cancellation may leave a partial record on the wire (no atomicity guarantee); after a CancelledError the reader stays usable and the next read resumes from the buffered bytes.
Resource limits
max_model_size bounds a single model in both directions — decode, decode_partial, read, iter_read, the async variants, IncrementalParser.feed / close, and encode() on the output. Every bound is validated before any allocation it guards.