Skip to Content
Binal
API Reference

Codecs

Custom codecs and the built-in codec primitives

A codec separates a field’s Python representation from its binary storage. Subclass Codec[PyT, StorageT], set storage to the binary type used on the wire, and implement encode (Python value to storage value) and decode (storage value to Python value). Codec errors are wrapped in EncodeError / DecodeError with the original exception as __cause__.

from datetime import datetime, timezone
from typing import Annotated

from binal import BinaryModel, Codec, UInt32, UInt64


class TimestampCodec(Codec[datetime, int]):
    storage = UInt64

    def encode(self, value: datetime) -> int:
        return int(value.timestamp())

    def decode(self, value: int) -> datetime:
        return datetime.fromtimestamp(value, tz=timezone.utc)


Timestamp = Annotated[datetime, TimestampCodec()]


class Event(BinaryModel, byte_order="big"):
    id: UInt32
    timestamp: Timestamp

A codec’s storage width and length come from the storage annotation’s own markers when it has them, and otherwise are inherited from the field — so Annotated[str, UpperCodec(), Prefixed(UInt8)] (bytes storage) and Annotated[int, RaisingCodec(), UInt8] (int storage, width from the field) both work. An int-storage codec requires an integer type on the field or on the storage annotation. A codec’s storage must be self-delimiting: bytes or str storage needs Fixed, Prefixed, NullTerminated, or Sized.

Codec primitives

The built-in types are Annotated aliases pairing a Python type with a codec object. The codec classes are public, so a custom width or encoding can be spelled directly:

  • IntegerCodec(bits, signed=False, byte_order=None) — the binary representation of an integer. Integer(bits, signed=False), Signed(bits), and Unsigned(bits) are helpers that return Annotated[int, IntegerCodec(...)]. A ByteOrder marker on the field overrides the model’s byte order; the older IntegerCodec(byte_order=...) spelling means the same thing.
  • FloatCodec(bits) — a floating-point value: 16, 32, or 64 bits.
  • BoolCodec() — a boolean as one byte, 0 or 1.
  • VarIntCodec(kind="uleb128", zigzag=False, bits=None) — a variable-length integer. kind is "uleb128" or "sleb128"; zigzag=True zigzag-encodes the value first. bits bounds zigzag values: bits=32 accepts only the int32 range and encodes to at most 5 bytes, bits=64 the int64 range and at most 10 bytes. Plain ULEB128/SLEB128 (bits=None) are arbitrary precision, bounded only by the configured varint byte limit.
from typing import Annotated

from binal import (
    BinaryModel,
    BoolCodec,
    FloatCodec,
    IntegerCodec,
    VarIntCodec,
)


class CustomWidth(BinaryModel, byte_order="big"):
    a: Annotated[int, IntegerCodec(bits=24, signed=False)]
    b: Annotated[float, FloatCodec(bits=32)]
    c: Annotated[bool, BoolCodec()]
    d: Annotated[int, VarIntCodec(kind="uleb128", zigzag=True, bits=32)]

ZigZag32 and ZigZag64 are VarIntCodec(kind="uleb128", zigzag=True, bits=32) and bits=64 respectively — genuinely distinct widths, not aliases. See Integers for the varint rules, including the acceptance of non-canonical encodings on decode.

On this page