Skip to Content
Binal
Modeling

Collections

Fixed, dynamic, terminated, and greedy arrays

from typing import Annotated

from binal import Array, BinaryModel, Float32, UInt16


class SensorData(BinaryModel, byte_order="big"):
    samples: Annotated[list[Float32], Array(count_prefix=UInt16)]


class Matrix(BinaryModel, byte_order="big"):
    values: Annotated[list[Float32], Array(count=16)]

Array(count=16) 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).

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. A callable sentinel is a predicate: reading stops at the first element for which it returns True.

from typing import Annotated

from binal import BinaryModel, Terminated, UInt16


class Words(BinaryModel, byte_order="big"):
    words: Annotated[list[UInt16], Terminated(0xFFFF)]


Words(words=[1, 2]).encode()  # b'\x00\x01\x00\x02\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 Tail(BinaryModel, byte_order="big"):
    head: UInt8
    rest: Annotated[list[UInt8], Greedy()]


Tail.decode(b"\x09\x01\x02\x03").rest  # [1, 2, 3]

The full reference is in Field Markers; the size limits that bound collections are in Limits.