Skip to Content
Binal
API Reference

Field Markers

The Annotated markers that shape a field's binary form

Field markers are used inside Annotated metadata. They say how a field is framed, whether it is present, and what value it carries. Each marker is listed with the field kind it applies to.

Lengths and sizes

LengthOf / CountOf / Sized

LengthOf("payload") on an integer field makes it derived: its value is the length of the named field, computed at construction and written on encode. CountOf("items") is the same for the element count of a list. Sized("length") on a bytes or str field reads its size from an earlier integer field.

from typing import Annotated

from binal import Array, BinaryModel, CountOf, LengthOf, Sized, UInt8, UInt16


class Packet(BinaryModel, byte_order="big"):
    length: Annotated[UInt16, LengthOf("payload")]
    payload: Annotated[bytes, Sized("length")]


class Batch(BinaryModel, byte_order="big"):
    n: Annotated[UInt8, CountOf("items")]
    items: Annotated[list[UInt16], Array(count="n")]


packet = Packet(payload=b"Hello")
packet.length  # 5
packet.encode()  # b'\x00\x05Hello'

Derived fields take no constructor argument. A derived value is computed when the instance is built, so a length that does not fit its integer type is stored as-is and only fails at encode, with ValidationError.

Sized (or an Array(count="n")) whose length field was skipped by a When condition reads to the end of the input instead, when it is the last field.

Framing

Prefixed

Prefixed(UInt16) writes a length prefix using the given integer type (any integer type, or a varint type), followed by the field data. For strings, encoding selects the text encoding. The prefix uses its own byte order, not a ByteOrder marker on the field.

from typing import Annotated

from binal import BinaryModel, Prefixed, UInt16


class Message(BinaryModel, byte_order="big"):
    text: Annotated[str, Prefixed(UInt16, encoding="utf-8")]

Fixed

Fixed(n) is a fixed-length field padded with zero bytes. On decode, a fixed bytes field strips trailing zero padding, and a fixed string validates that there are no non-zero bytes after the first NUL (UTF-16/32 strings strip trailing NUL characters instead). Values with meaningful trailing zeros need Prefixed or Sized.

from typing import Annotated

from binal import BinaryModel, Fixed


class Record(BinaryModel, byte_order="big"):
    tag: Annotated[bytes, Fixed(4)]


Record(tag=b"AB").encode()  # b'AB\x00\x00'
Record.decode(b"AB\x00\x00").tag  # b'AB'

NullTerminated

NullTerminated(encoding="utf-8") is a string field terminated by a single NUL byte (a NUL code unit for UTF-16/32). The terminator is consumed on decode and written on encode.

Array

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.

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)]

Terminated

Terminated(0xFFFF) on a list field 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. For a value sentinel the encoder appends it when the list does not already end with it; for a predicate sentinel the encoder cannot synthesize one, so the list must already end with a matching element.

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

Greedy() on a list field 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. A fixed-size element stops cleanly at padding bits that cannot form another element. On encode the elements are written with no count or terminator. A bytes field with no length mechanism is greedy in the same way.

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]

Constants and layout

Const

Const(value) is a constant field for any type — int, float, bool, bytes, str, or enum. The field is derived (no constructor argument); the encoder writes the constant regardless of the stored value, and the decoder raises DecodeError on mismatch. An int constant needs an integer type, e.g. Annotated[UInt8, Const(1)]. For bytes/str without a length mechanism, the length is inferred from the constant.

from typing import Annotated

from binal import BinaryModel, Const, Prefixed, UInt8, UInt16


class File(BinaryModel, byte_order="big"):
    magic: Annotated[bytes, Const(b"BINA")]
    version: Annotated[UInt8, Const(1)]
    body: Annotated[bytes, Prefixed(UInt16)]


File(body=b"data").encode()  # b'BINA\x01\x00\x04data'

Padding

Padding(3) is reserved padding of three zero bytes. The bytes are written on encode and validated as zeros on decode.

Align

Align(4) aligns the next field to a multiple of 4 bytes. The alignment is relative to the start of the model, and the pad bytes are validated as zeros on decode.

from typing import Annotated

from binal import Align, BinaryModel, Padding, UInt8, UInt32


class Aligned(BinaryModel, byte_order="big"):
    a: UInt8
    pad: Annotated[bytes, Padding(3)]
    b: Annotated[UInt32, Align(4)]


Aligned(a=1, b=2).encode()  # b'\x01\x00\x00\x00\x00\x00\x00\x02'

ByteOrder

ByteOrder("little") overrides the model’s byte order for one field. It applies to int, float, enum, and nested-model fields. It is the unified spelling; the older IntegerCodec(byte_order=...) override still works and means the same thing. It does not apply to length prefixes — the prefix codec’s own byte order governs those.

from typing import Annotated

from binal import BinaryModel, ByteOrder, UInt16, UInt32


class Mixed(BinaryModel, byte_order="big"):
    a: UInt16
    b: Annotated[UInt32, ByteOrder("little")]


Mixed(a=1, b=2).encode()  # b'\x00\x01\x02\x00\x00\x00'

Pointers

Offset

Offset("payload") on an integer field makes it a pointer: its value is the byte position of the named target field. base="start" (default) measures from the start of the model; base="self" measures from the offset field’s own position. The field is derived (computed on encode, no constructor argument) and must be declared before its target. The target must not be a bit field and must not be conditional; the offset field itself must not be conditional. The offset value points at the target field’s start — for a Prefixed target, that includes its length prefix.

On decode, the target is read from the recorded offset and the reader position is restored, so data that lives elsewhere in the input (a gap, an out-of-order section) still decodes.

from typing import Annotated

from binal import BinaryModel, Offset, Prefixed, UInt16


class Packet(BinaryModel, byte_order="big"):
    off: Annotated[UInt16, Offset("payload")]
    payload: Annotated[bytes, Prefixed(UInt16)]


Packet(payload=b"AB").encode()  # b'\x00\x02\x00\x02AB'
# The payload lives at offset 8, after a 6-byte gap:
Packet.decode(b"\x00\x08\x00\x00\x00\x00\x00\x00\x00\x02AB").payload  # b'AB'

Conditions and unions

When

When("has_extra", equals=1) includes the field only when the named field equals the given value. When(predicate) takes a callable receiving the already-decoded values (a dict of field name to value) and returning whether the field is present — this is how multi-field, compound, and custom conditions are written, in plain Python, with no separate expression language. A predicate may only read fields declared before the conditional field. A field whose condition is false is absent on the wire; its value is stored but not validated.

from typing import Annotated

from binal import BinaryModel, UInt8, UInt16, When


class Maybe(BinaryModel, byte_order="big"):
    has_extra: UInt8
    extra: Annotated[UInt16, When("has_extra", equals=1)]
    total: UInt8


class Compound(BinaryModel, byte_order="big"):
    a: UInt8
    b: UInt8
    c: Annotated[UInt16, When(lambda v: v["a"] == 1 and v["b"] == 2)]


Maybe(has_extra=1, extra=7, total=3).encode()  # b'\x01\x00\x07\x03'
Maybe(has_extra=0, total=3).encode()  # b'\x00\x03'
Compound(a=1, b=2, c=9).encode()  # b'\x01\x02\x00\x09'

TaggedUnion

TaggedUnion(discriminator="kind", variants={1: Circle, 2: Square}) selects the variant model from the value of the discriminator field. The discriminator must be a field of the containing model, read from already-decoded values — not a field of the variants. Variant names may be strings, so a recursive union can name a class still being defined; the name is resolved against the model’s module at first use.

from typing import Annotated

from binal import BinaryModel, TaggedUnion, UInt8, UInt16


class Circle(BinaryModel, byte_order="big"):
    radius: UInt16


class Square(BinaryModel, byte_order="big"):
    side: UInt16


class Shape(BinaryModel, byte_order="big"):
    kind: UInt8
    shape: Annotated[
        Circle | Square,
        TaggedUnion(discriminator="kind", variants={1: Circle, 2: Square}),
    ]


Shape(kind=2, shape=Square(side=5)).encode()  # b'\x02\x00\x05'

EnumField

EnumField(UInt8, on_unknown="raise") is an enumeration field backed by an integer type. on_unknown controls decoding of values not in the enum: "raise" (default) raises a decode error, "keep" keeps the raw integer value. On encode, members of the declared enum and raw integers in range are accepted.

from enum import IntEnum
from typing import Annotated

from binal import BinaryModel, EnumField, UInt8


class Color(IntEnum):
    RED = 1
    GREEN = 2


class Pixel(BinaryModel, byte_order="big"):
    color: Annotated[Color, EnumField(UInt8, on_unknown="keep")]


Pixel(color=Color.RED).encode()  # b'\x01'
Pixel.decode(b"\x07").color  # 7

Bit fields

Bits

Bits(3) is a bit field of 3 bits, for use in BitModel. int bit fields are unsigned by default (range 0 .. 2**width-1); pass signed=True for a two’s-complement field (range -2**(width-1) .. 2**(width-1)-1), which sign-extends on decode. Bit arrays — list[Annotated[int, Bits(3)]] — pack elements across byte boundaries.

from typing import Annotated

from binal import Array, BitModel, Bits


class Flags(BitModel, bit_order="msb"):
    version: Annotated[int, Bits(3)]
    delta: Annotated[int, Bits(3, signed=True)]
    flag: Annotated[bool, Bits(1)]


class Samples(BitModel, bit_order="msb"):
    values: Annotated[list[Annotated[int, Bits(3)]], Array(4)]