Collections
Fixed-count, dynamic, terminated, and greedy arrays
from typing import Annotated
from binal import Array, BinaryModel, Float32, UInt16
class Vertex(BinaryModel, byte_order="little"):
position: Annotated[list[Float32], Array(count=3)]
normal: Annotated[list[Float32], Array(count=3)]
class Mesh(BinaryModel, byte_order="little"):
vertices: Annotated[list[Vertex], Array(count_prefix=UInt16)]
indices: Annotated[list[UInt16], Array(count_prefix=UInt16)]
triangle = Mesh(
vertices=[
Vertex([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
Vertex([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
Vertex([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
],
indices=[0, 1, 2],
)
assert Mesh.decode(triangle.encode()) == triangle Array(count=3) is a fixed-length collection, Array(count_prefix=UInt16) prefixes the element count, and Array(count="n") reads the count from an earlier field named n (paired with CountOf on that field).
Computed counts
The count may also be a plain Python callable over the evaluation scope — the values decoded (or constructed) so far, plus context. The callable may only read fields declared before the collection, and the computed count is validated against the collection size limit before any element is read or written.
from typing import Annotated
from binal import Array, BinaryModel, UInt8, UInt16
class ChannelSamples(BinaryModel, byte_order="big"):
channels: UInt8 # one bit per channel that is enabled
samples: Annotated[list[UInt16], Array(count=lambda v: v["channels"].bit_count())]
ChannelSamples(channels=0b101, samples=[10, 20]).encode()
# b'\x05\x00\x0a\x00\x14' The same callable spelling works for sizes (Sized), offsets (Offset), alignments (Align), lengths (Sized / Padded), and bit widths (Bits). A callable may declare what it reads via a depends_on attribute, so the compiler can check the reference at class definition; without it, reading a missing key raises a structured error naming the field, never a bare KeyError.
Terminated collections
Terminated(0xFFFF) reads elements until one equals the sentinel value. The terminator is consumed but not included in the result, unless include=True. If the input ends without the terminator, decoding fails with DecodeError. On encode, a list without include=True must not contain the sentinel (the encoder appends it); with include=True it must end with the sentinel and contain it nowhere else, so the bytes always decode back to the same list. A callable sentinel is a predicate: reading stops at the first element for which it returns True; the encoder cannot invent such an element, so a predicate requires include=True.
from typing import Annotated
from binal import BinaryModel, Terminated, UInt16
class GlyphRanges(BinaryModel, byte_order="big"):
starts: Annotated[list[UInt16], Terminated(0xFFFF)]
GlyphRanges(starts=[0x20, 0x4E00]).encode() # b'\x00\x20\x4e\x00\xff\xff' Greedy collections
Greedy() reads elements until the end of the input. The field must be the last field, since nothing can follow a field that consumes the rest of the input. On encode the elements are written with no count or terminator.
from typing import Annotated
from binal import BinaryModel, Greedy, UInt8
class Palette(BinaryModel):
version: UInt8
colors: Annotated[list[tuple[UInt8, UInt8, UInt8]], Greedy()]
Palette.decode(bytes.fromhex("01 ff0000 00ff00")).colors
# [(255, 0, 0), (0, 255, 0)] Length-bounded collections
Sized(n) or Prefixed(UInt16) on a list bounds it by a byte length rather than an element count: decode reads elements until the frame is used up, and the frame must end on an element boundary. LengthOf on such a list gives its encoded byte length. A byte-bounded list takes no Array or Terminated.
from dataclasses import field
from typing import Annotated
from binal import BinaryModel, LengthOf, Prefixed, Sized, UInt8, UInt16
class Extension(BinaryModel, byte_order="big"):
type: UInt16
data: Annotated[bytes, Prefixed(UInt16)]
class Extensions(BinaryModel, byte_order="big"):
"""The extensions of a TLS hello: their size in bytes, not their count."""
size: Annotated[UInt16, LengthOf("items")] = field(init=False)
items: Annotated[list[Extension], Sized("size")]
Extensions([Extension(0x002B, b"\x03\x04")]).encode()
# b'\x00\x06\x00\x2b\x00\x02\x03\x04' Tuples
tuple[A, B, ...] is a fixed sequence of differently typed items, written in order with no count, exactly like the same fields written out. Each item is any type a field can have; the tuple takes the model’s byte and bit order.
from binal import BinaryModel, Float32, UInt16
class TouchEvent(BinaryModel, byte_order="little"):
contact: tuple[UInt16, UInt16, Float32] # x, y, pressure
TouchEvent(contact=(320, 200, 0.5)).encode()