Skip to Content
Binal

Strings and Bytes

Sized, padded, prefixed, terminated, and greedy fields

from typing import Annotated

from binal import BinaryModel, NullTerminated, Padded, Prefixed, UInt16


class Record(BinaryModel, byte_order="big"):
    name: Annotated[str, Padded(32, encoding="utf-8")]
    description: Annotated[str, Prefixed(UInt16, encoding="utf-8")]
    identifier: Annotated[str, NullTerminated(encoding="ascii")]

Bytes fields use the same markers: Sized(n) / Padded(n), Prefixed(UInt16), NullTerminated(), and Sized("length") for length-dependent fields.

Sized versus padded

Sized(n) and Padded(n) are different jobs, and the same marker means the same thing for bytes and str.

Sized(n) is for values that are always exactly n bytes: decode returns all n bytes as-is, with no stripping and no NUL splitting, and encode requires the value to be exactly n bytes — a short value is never silently padded. Trailing zero bytes are data, so they survive a round-trip:

from typing import Annotated

from binal import BinaryModel, Sized


class Tag(BinaryModel, byte_order="big"):
    payload: Annotated[bytes, Sized(4)]


data = b"\x01\x02\x00\x00"
assert Tag.decode(data).payload == data
assert Tag.decode(data).encode() == data

Padded(n, pad=b"\x00", strip=True) is for explicitly padded data: encode pads a short value with pad (repeated to fill the field) and decode strips trailing pad bytes when strip is True, preserving them when it is False. For strings with the default NUL pad, decode splits at the first NUL and raises if non-zero bytes follow it.

from typing import Annotated

from binal import BinaryModel, Padded


class Name(BinaryModel, byte_order="big"):
    name: Annotated[str, Padded(16, encoding="utf-8")]


Name(name="abc").encode()  # b'abc\x00...' (16 bytes)
Name.decode(b"abc\x00" + b"\x00" * 12).name  # 'abc'


class Raw(BinaryModel, byte_order="big"):
    data: Annotated[bytes, Padded(4, pad=b"\xff", strip=False)]


Raw(data=b"\x01").encode()  # b'\x01\xff\xff\xff'
Raw.decode(b"\x01\xff\xff\xff").data  # b'\x01\xff\xff\xff'

Terminated and greedy

NullTerminated() ends a str or bytes field with a NUL: one zero byte for bytes, single-byte encodings, and UTF-8, and one NUL code unit (2 or 4 zero bytes) for UTF-16 and UTF-32. Terminated(delimiter) ends one with any delimiter: a non-empty bytes for a bytes field, a str (encoded with encoding, default UTF-8) or bytes for a str field. The value may not contain the terminator — encode raises ValidationError instead of writing bytes that would decode to something shorter — and decode raises DecodeError if the input ends first. In a multi-byte encoding the terminator is matched only at code-unit boundaries, so bytes inside a character never end the value.

Greedy() reads a str or bytes field to the end of the input; it must be the last field, and Greedy(encoding="latin-1") sets a string’s encoding.

from typing import Annotated

from binal import BinaryModel, Greedy, NullTerminated, Terminated


class Request(BinaryModel, byte_order="big"):
    line: Annotated[str, Terminated("\r\n", encoding="ascii")]
    key: Annotated[bytes, NullTerminated()]
    body: Annotated[bytes, Greedy()]


Request(line="GET /", key=b"k", body=b"...").encode()  # b'GET /\r\nk\x00...'