Skip to Content
Binal

References and Spaces

Objects stored elsewhere, and data with its own addresses

References

A Ref field stores an address; its value is the object stored there.

from __future__ import annotations

from typing import Annotated

from binal import BinaryModel, Ref, UInt8


class Node(BinaryModel):
    value: UInt8
    next: Annotated[Node | None, Ref(UInt8, null=0)]


class List(BinaryModel):
    head: Annotated[Node | None, Ref(UInt8, null=0)]


data = List(head=Node(value=5, next=Node(value=6, next=None))).encode()
# b"\x01\x05\x03\x06\x00": each node is allocated after the record,
# and its address is filled in.
List.decode(data)
ArgumentMeaning
storageThe integer that holds the address, e.g. UInt32.
base, unitThe object is at base + address × unit: a literal, an earlier field’s name, or a callable. unit is a page or block size.
nullThe address that means “no object”; the field is then Model | None.
alignObjects are allocated at multiples of it.
internEqual objects are stored once.

A Ref field may also be guarded by When, for an object that is only there sometimes.

The object may also be a value: bytes, a string, or a list. The field’s other markers then describe the value, and its sizes may name earlier fields:

from binal import Prefixed, Sized, UInt16, UInt32


class Entry(BinaryModel, byte_order="little"):
    count: UInt32
    data: Annotated[bytes, Ref(UInt32), Sized("count")]
    name: Annotated[str | None, Ref(UInt16, null=0), Prefixed(UInt8)]

A size inside a referenced value is a field name or a literal, so it stays portable schema; a callable is a SchemaError.

Identity, sharing, and cycles

Identity is not equality. Two equal values are two objects, written twice, unless the reference says intern=True. decode gives plain values: shared objects are copied, and a cycle is an error. Model.open keeps the references:

doc = List.open(bytes([1, 10, 3, 20, 1]))   # 1 -> 3 -> 1: a cycle
head = doc.root.head                         # a Reference
node = doc[head]                             # a Node, read when first asked for
doc[doc[node.next].next] is not None         # the cycle is kept
doc[node.next].next == head                  # True: the same object
doc.encode()                                 # lossless

See Formats and Documents for editing. A Python object graph that contains itself has no plain encoding: encoding one is an EncodeError that says so.

Address spaces

Space reads a nested model from its own address space: the field’s bytes, decompressed when a codec is given. Addresses and references in the model are relative to the space.

from dataclasses import field

from binal import Array, CountOf, LengthOf, Prefixed, Sized, Space, UInt16


class Item(BinaryModel, byte_order="big"):
    name: Annotated[str, Prefixed(UInt8)]


class Inner(BinaryModel, byte_order="big"):
    count: Annotated[UInt8, CountOf("items")] = field(init=False)
    items: Annotated[list[Annotated[Item, Ref(UInt8)]], Array("count")]


class Archive(BinaryModel, byte_order="big"):
    size: Annotated[UInt16, LengthOf("body")] = field(init=False)
    body: Annotated[Inner, Space("zlib"), Sized("size")]

LengthOf a space is its stored (compressed) length. In a document, an unchanged compressed space keeps its original bytes.

Gathered spaces

Some formats store one record in scattered pieces: a SQLite cell keeps the start of its payload in the page and the rest in a chain of overflow pages; a FAT file is a chain of clusters. Space(gather=...) reads the model from those pieces, concatenated, and occupies no bytes where it is declared. A piece is an earlier bytes field, named by a string, or a chain of objects: Follow("chain", "content", "next", chunk) starts at the Ref field chain, takes each object’s content bytes, and moves on through its next reference until it is None.

from __future__ import annotations

from binal import Follow, When


class Link(BinaryModel, byte_order="big"):
    next: Annotated[Link | None, Ref(UInt8, null=0)]
    content: Annotated[bytes, Prefixed(UInt8)]


class Payload(BinaryModel, byte_order="big"):
    count: Annotated[UInt8, CountOf("items")] = field(init=False)
    items: Annotated[list[UInt16], Array("count")]


class Chained(BinaryModel, byte_order="big"):
    total: Annotated[UInt8, LengthOf("payload")] = field(init=False)
    head: Annotated[bytes, Sized(lambda s: min(s["total"], 3))] = field(init=False)
    chain: Annotated[Link | None, Ref(UInt8), When(lambda s: s["total"] > 3)] = (
        field(init=False)
    )
    payload: Annotated[
        Payload, Space(gather=("head", Follow("chain", "content", "next", 2)))
    ]


Chained(payload=Payload(items=[1, 2, 3])).encode()
# b'\x07\x03\x00\x01\x05\t\x02\x00\x02\x00\x02\x00\x03'

The pieces are derived fields, declared = field(init=False): you construct the model with the gathered value only, and encoding fills the pieces, splitting what does not fit in the earlier pieces into objects of chunk bytes. Reading a piece on an instance gives what encoding writes. In a document, an unchanged chain keeps its objects.