I/O Reference
Partial decoding, incremental parsing, streams, and low-level I/O
decode_partial
Model.decode_partial(data, offset=0) decodes one record starting at offset and returns (instance, consumed). Bytes after the record are left for the caller — unlike decode(), which rejects trailing data. Error offsets are relative to the start of data, not to offset, and offset itself must satisfy 0 <= offset <= len(data).
from binal import BinaryModel, UInt8
class Packet(BinaryModel, byte_order="big"):
version: UInt8
instance, consumed = Packet.decode_partial(b"\x07\x08\x09", offset=1)
# instance.version == 8, consumed == 1 decode_many and encode_many
Model.decode_many(data) decodes records stored back to back that together span all of data, in one call, and returns them as a list. Model.encode_many(records) encodes a sequence of instances one after another and returns the bytes. Each record is decoded, encoded, and validated as decode() and encode() handle one; the runtime handles the whole sequence in one call instead of one call per record. A failure’s path names the record, and a decode failure’s offset counts from the start of data.
from binal import BinaryModel, Int16
class Point(BinaryModel, byte_order="big"):
x: Int16
y: Int16
data = Point.encode_many([Point(1, 2), Point(3, 4)])
Point.decode_many(data) # [Point(x=1, y=2), Point(x=3, y=4)]
Point.decode_many(data + b"\x00") # DecodeError at Point[2].x, offset 8 Format.decode_many(type_name, data) and Format.encode_many(type_name, values) do the same for a schema’s types; their error paths start with the record’s index ([2].x).
IncrementalParser
Model.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. A decode failure whose error has is_incomplete set means the record is incomplete, so the bytes are kept; any other decode error means the input is invalid and is raised immediately. close() signals end of input and returns the final record, or None if the buffer is empty; it raises DecodeError on a truncated leftover or trailing data. feed after close raises. A model with a greedy bytes field only ends at EOF, so its record is produced by close().
from binal import BinaryModel, UInt8
class Packet(BinaryModel, byte_order="big"):
version: UInt8
parser = Packet.incremental_parser()
records = parser.feed(b"\x01\x02") # records completed by this chunk
records += parser.feed(b"\x03")
final = parser.close() # the last record, or None iter_read / iter_read_async
Packet.iter_read(stream) yields records from a binary stream until end of stream, buffering only the current record. Packet.iter_read_async(reader) is the async equivalent, for any async reader such as asyncio.StreamReader; it reads ahead in chunks, so it owns the reader until it is exhausted. read() and read_async() read one record and never request a byte past its end. A record that makes no progress raises DecodeError instead of looping forever.
write / write_async
packet.write(stream) encodes the record and writes it, calling stream.write again after a short write. A write that returns None (a non-blocking raw stream with no room) raises BlockingIOError whose characters_written counts the bytes already written; a write that returns 0 raises OSError. The stream is not flushed. await packet.write_async(writer) calls writer.write() once and awaits writer.drain().
BinaryReader / BinaryWriter
The low-level primitives BinaryModel is built on, for code that needs to read or write a binary format without declaring a model: custom codecs, ad-hoc parsers, and formats whose shape is only known at runtime. For declarative modeling, use BinaryModel instead.
BinaryReader(data) reads from bytes, bytearray, or memoryview. read_int(bits, signed, byte_order), read_float(format, byte_order) (a Float format name such as "binary32" or "bfloat16"), read_varint(kind, zigzag, bits=None) (kind "uleb128", "sleb128", or "vlq"), read_bits(width), read_bytes(n), and read_byte() consume input and raise DecodeError on truncation or an overlong varint. seek(pos) moves to an absolute byte position; remaining(), at_eof(), bytes_consumed(), and bits_consumed() report position. Limits (max_field_length, max_varint_bytes, …) come from Limits and are checked before allocation.
read_model(Model, context=None) decodes one record at the next byte boundary and moves past it, with the model’s own bit order and limits; BinaryWriter.write_model(instance) is its counterpart and returns the record’s size. Together they mix declared records with hand-written fields in one buffer.
BinaryWriter() accumulates output. write_int(value, bits, signed, byte_order), write_float(value, format, byte_order), write_varint(value, kind, zigzag, bits=None), write_bits(value, width), and write_bytes(value) append; bytes() returns the accumulated bytes. tell() is the current byte position (a pending partial byte counts); tell_bits() is the bit position. flush_bits() pads the current partial byte.
from binal import BinaryReader, BinaryWriter
writer = BinaryWriter()
writer.write_int(0x1234, 16, False, "big")
writer.write_bits(0b101, 3)
data = writer.bytes()
reader = BinaryReader(data)
reader.read_int(16, False, "big") # 0x1234
reader.read_bits(3) # 0b101 StreamReader and AsyncRecordReader are the internal stream readers behind read() / iter_read() / read_async() / iter_read_async(); they are not part of the public API.
Random access
BinaryReader.open(path) opens a file for random-access reading without loading it: reads go through os.pread, and the reader owns the file (closed by the context manager or close()). 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. A record in a sized window must consume exactly size bytes: trailing bytes inside the window are an error, and needing more is a truncation error.
BinaryWriter.open(path, "wb" / "r+b") and write_at(instance | bytes, offset) are the symmetric write side: pending sequential bytes are flushed before an out-of-order write lands, and the logical position is restored afterwards.
from binal import BinaryReader, BinaryWriter
with BinaryReader.open("dataset.bin") as reader:
record = reader.read_at(Record, offset=entry.offset, size=entry.size)
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)