"""Field-id → destination table: decode straight into caller-owned storage.
CORELIB_PLAN §5.3 recommends the visitor pattern "because the primary consumer
of this library is *generated code* … those objects already exist at decode
time; the visitor pattern lets the decoder write each field straight into the
waiting member without an intermediate representation". A :class:`Binding` is
that idea written down once instead of by hand: rather than a handler with a
branch per field id, the table says where every field belongs, and
:func:`handler` compiles it into the :class:`sofab.Visitor` the decoder drives.
It is **not** a second decode surface, and CORELIB_PLAN §5.3.1 does not allow
one: "no convenience wrapper that decodes by another route", because "every
additional surface is a second implementation of every rule in this document".
So a table is a way of *saying where a field goes*, never a way of getting it
there — the same `feed`, the same header walk, the same hooks and the same
verdicts as any other handler.
What it still buys over a hand-written visitor is the *elements*: an array of any
length lands in the caller's slots through
:meth:`sofab.Visitor.on_array_begin` / :meth:`~sofab.Visitor.on_float_array_begin`
without a list and without a Python object per element.
Two pieces of storage, both **supplied and sized by the caller** — the decoder
allocates neither and never sizes anything from the wire (documentation#54 §6.6,
CORELIB_PLAN §6.2.1):
``words``
One writable, C-contiguous byte buffer whose length is a multiple of 8 — a
``bytearray`` is the obvious choice. Every numeric field lands in it as one
64-bit slot: unsigned as ``uint64``, signed as ``int64``, ``fp32``/``fp64``
both widened to a native ``double``, arrays as ``cap`` consecutive slots.
Read the slots back through as many typed views over the *same* buffer as
you need — ``memoryview(buf).cast("q")``, ``.cast("Q")``, ``.cast("d")`` —
which costs no copy and no second buffer.
``objects``
A pre-sized ``list``, for the two field kinds that have no fixed-width
machine representation: ``string`` and ``blob``. Each lands at its own index.
A slot takes either of two shapes, and the row says which. :meth:`string`
and :meth:`bytes` name a slot to *put a value in*, and the decoder builds
that ``str``/``bytes`` — from the only size it has, the wire's, which is the
materialized aggregate CORELIB_PLAN §6.6.3 names. :meth:`string_into` and
:meth:`blob_into` name a slot that already **holds** a writable byte buffer
the caller put there, and the payload is copied into it: nothing is sized
from the wire, a destination too short is refused rather than grown, and
``count_at`` receives the byte length. That is §6.6.3's third shape — "into a
destination the caller declared before the decode began" — and it is what
lets a whole message decode without one allocation the sender chose.
A field the table does not name is not an error: it is dispatched to the
:class:`sofab.Visitor` the decoder was given, or skipped. So a binding covers
the schema's hot fields and everything else keeps working. A table built with
``closed=True`` skips such a field even when there is a visitor — which is what
a *child* table wants, because the visitor was never told the walk descended
into it (see :class:`Binding`).
Example::
b = Binding()
b.unsigned(1, at=0).signed(2, at=1).string(3, at=0, count_at=2)
b.unsigned_array(4, at=8, cap=16, count_at=3)
b.blob_into(5, at=1, count_at=4) # into a buffer you put there
words = bytearray(b.words_required * 8)
objs = [None] * b.objects_required
objs[1] = bytearray(4096) # field 5's destination
dec = Decoder(binding=b, words=words, objects=objs)
st = dec.feed(chunk)
u = memoryview(words).cast("Q")
u[0] # field 1
objs[0] # field 3, or untouched if it never arrived
u[2] # 1 if field 3 arrived, else untouched
u[8:8 + u[3]] # field 4's elements, u[3] of them
objs[1][:u[4]] # field 5's payload, u[4] bytes of it
"""
from __future__ import annotations
import struct
from collections.abc import Sequence
from typing import Any
from .types import (
ARRAY_MAX,
FIXLEN_MAX,
ID_MAX,
SIGNED_MAX,
SIGNED_MIN,
UNSIGNED_MAX,
FixlenSubtype,
SofaArgumentError,
WireType,
)
#: ``bytes`` under a name the class body does not shadow -- :meth:`Binding.bytes`
#: is a binder method, so a ``bytes`` annotation inside the class means that.
_Bytes = bytes
# --- entry kinds -------------------------------------------------------------
#
# Plain module-level ints rather than an IntEnum: both engines compare them on
# the decode hot path, and the native one lowers them to C ``int`` switches.
# The array kinds are one contiguous block, and ``K_SEQUENCE`` closes the list:
# the native engine tells an array row from a scalar one with a range test over
# these numbers rather than a membership test, so a kind added outside that
# block would be misread as an array. Keep new kinds inside their group.
K_UNSIGNED = 0
K_SIGNED = 1
K_BOOLEAN = 2
K_FLOAT32 = 3
K_FLOAT64 = 4
K_STRING = 5
K_BYTES = 6
K_ARRAY_UNSIGNED = 7
K_ARRAY_SIGNED = 8
K_ARRAY_BOOLEAN = 9
K_ARRAY_FLOAT32 = 10
K_ARRAY_FLOAT64 = 11
K_SEQUENCE = 12
#: For each kind, the wire tag it accepts: ``(wire type, fixlen subtype or None)``.
#: A field whose wire tag contradicts its binding is **not** an error — it is
#: skipped exactly like an unknown id and the decode stays COMPLETE
#: (MESSAGE_SPEC §7.3, CORELIB_PLAN §6.3).
#: A boolean's tag is the unsigned one: §4.4 gives booleans no wire type of
#: their own, so nothing distinguishes them here — the difference is what the
#: decoder stores, not what it accepts.
KIND_TAG: tuple[tuple[WireType, FixlenSubtype | None], ...] = (
(WireType.UNSIGNED, None),
(WireType.SIGNED, None),
(WireType.UNSIGNED, None),
(WireType.FIXLEN, FixlenSubtype.FP32),
(WireType.FIXLEN, FixlenSubtype.FP64),
(WireType.FIXLEN, FixlenSubtype.STRING),
(WireType.FIXLEN, FixlenSubtype.BLOB),
(WireType.ARRAY_UNSIGNED, None),
(WireType.ARRAY_SIGNED, None),
(WireType.ARRAY_UNSIGNED, None),
(WireType.ARRAY_FIXLEN, FixlenSubtype.FP32),
(WireType.ARRAY_FIXLEN, FixlenSubtype.FP64),
(WireType.SEQUENCE_START, None),
)
#: Kinds that are one ``words`` slot holding one value -- the kinds that can
#: carry a declared ``default`` for MESSAGE_SPEC §7.4.1's reset.
_SCALAR_KINDS = frozenset(
(K_UNSIGNED, K_SIGNED, K_BOOLEAN, K_FLOAT32, K_FLOAT64)
)
#: Kinds whose ``at`` indexes ``objects`` rather than ``words``.
_OBJECT_KINDS = frozenset((K_STRING, K_BYTES))
#: Kinds that consume ``cap`` consecutive slots instead of one.
_ARRAY_KINDS = frozenset(
(
K_ARRAY_UNSIGNED,
K_ARRAY_SIGNED,
K_ARRAY_BOOLEAN,
K_ARRAY_FLOAT32,
K_ARRAY_FLOAT64,
)
)
[docs]
class Entry:
"""One row of a :class:`Binding`. Built by the binder methods, read by the
engines; not something callers construct."""
__slots__ = (
"kind", "field_id", "at", "cap", "count_at", "child", "wt", "st",
"elem_lo", "elem_hi", "elem_bounded", "declared", "into", "which_at",
"own_words", "own_objects", "own_into", "reset_words", "reset_objects",
"reset_into",
)
def __init__(
self,
kind: int,
field_id: int,
at: int,
cap: int,
count_at: int,
child: Binding | None,
elem_lo: int = 0,
elem_hi: int = 0,
elem_bounded: bool = False,
into: bool = False,
default_bits: int = 0,
default_value: Any = None,
) -> None:
self.kind = kind
self.field_id = field_id
self.at = at
self.cap = cap
self.count_at = count_at
self.child = child
# The ``words`` slot this row's *field id* is written to when the value
# arrives, or -1. Set by :meth:`Binding.freeze` from the owning table's
# ``which_at``, so the hot path reads it off the row it has already
# loaded rather than carrying a per-scope register (MESSAGE_SPEC §7.4.1).
self.which_at = -1
# What this row starts from when its option is re-selected (§7.4.1). The
# slots are the row's own; ``reset_*`` is the same over the row's whole
# subtree and is what the decoder walks, filled by :meth:`Binding.freeze`
# for the rows of a one-of table and left empty for every other row.
own_words: list[tuple[int, int]] = []
own_objects: list[tuple[int, Any]] = []
own_into: list[tuple[int, bytes]] = []
if kind in _SCALAR_KINDS:
# One 64-bit pattern, whatever the kind: a signed default in two's
# complement and a float's as its ``double`` bits, so the reset is
# one loop over ``words`` rather than a branch per row.
own_words.append((at, default_bits))
elif kind in _OBJECT_KINDS and not into:
# The declared ``default`` if the row has one, else the empty value.
# §4.2 refuses a non-empty default for a string/blob *option*, but a
# *member* of a struct option is an ordinary field and may declare
# one; the value object is immutable and prepared here, so the reset
# stores a reference and allocates nothing (CORELIB_PLAN §6.6). An
# ``into`` row keeps the buffer the caller put there -- its length is
# ``count_at``, below.
if default_value is None:
own_objects.append((at, "" if kind == K_STRING else b""))
else:
own_objects.append((at, default_value))
elif kind in _OBJECT_KINDS and default_value is not None:
# An ``into`` row: the slot holds the caller's buffer, not the value,
# so the default cannot be stored -- it has to be *copied in*, and the
# length slot says how much of the buffer is live. Prepared as bytes
# here (a string default UTF-8-encoded once), so the reset is a slice
# assignment with nothing to build.
own_into.append((at, default_value))
elif kind in _ARRAY_KINDS and default_value is not None:
# An array's declared default, element by element, in the same
# ``words`` encoding the decode path stores: the elements are slots
# like any other, so the reset stays one loop with no branch per row.
for offset, word in enumerate(default_value):
own_words.append((at + offset, word))
# Without a declared default an array starts empty and a string/blob
# ``into`` starts zero-length, which is what a count slot of 0 says; with
# one, the count is the default's own length. An array's untouched
# elements past that length are not written, because ``count_at`` is what
# says how many of them are the value (§4.2, §5.1).
if count_at >= 0:
n_arrived = 0
if default_value is not None and (
kind in _ARRAY_KINDS or (kind in _OBJECT_KINDS and into)
):
# An array's element count, or an ``into`` default's byte length.
n_arrived = len(default_value)
own_words.append((count_at, n_arrived))
self.own_words = tuple(own_words)
self.own_objects = tuple(own_objects)
self.own_into = tuple(own_into)
self.reset_words: tuple[tuple[int, int], ...] = ()
self.reset_objects: tuple[tuple[int, Any], ...] = ()
self.reset_into: tuple[tuple[int, bytes], ...] = ()
# A string/blob row whose ``objects`` slot already holds the destination
# (:meth:`Binding.string_into` / :meth:`Binding.blob_into`): the payload
# is copied into it and no ``str``/``bytes`` is built (§6.6.3).
self.into = into
# The width the schema declares (§1, §7.1): an integer scalar's, or each
# element's for an integer array. Checked at the value, before it is
# stored. Absent means "as wide as the wire type allows".
self.elem_lo = elem_lo
self.elem_hi = elem_hi
self.elem_bounded = elem_bounded
# Precomputed so the §7.3 tag test on the hot path is two int compares.
self.wt, self.st = KIND_TAG[kind]
# What this row declares to Visitor.on_schema_bound: an array's ``cap``
# is always the schema's element count, a string/blob's ``maxlen`` only
# when one was given, and a scalar or a sequence declares nothing.
if kind in _ARRAY_KINDS:
self.declared = cap
elif kind in _OBJECT_KINDS and cap:
self.declared = cap
else:
self.declared = -1
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
f"Entry(kind={self.kind}, field_id={self.field_id}, at={self.at}, "
f"cap={self.cap}, count_at={self.count_at})"
)
[docs]
class Binding:
"""Where each field id's value belongs. Build once, decode many times.
Every binder method returns ``self``, so a table reads as one statement.
``at`` is a slot index — into ``words`` for the numeric kinds, into
``objects`` for :meth:`string`, :meth:`bytes`, :meth:`string_into` and
:meth:`blob_into`. ``count_at`` is an optional ``words`` slot the decoder
writes the field's *arrival* into: ``1`` for a scalar that turned up, the
element count for an array, the byte length for a :meth:`string_into` /
:meth:`blob_into` payload, the number of occurrences for a sequence. Slots
the decoder never writes are left exactly as the caller prepared them, which
is how a decode reports absence without inventing a sentinel.
An array's ``count_at`` is written when the array's **count header** is read,
not when its last element lands — that is where the destination is settled
(§6.6.3). On a decode that completes the value is the same either way; a
decode that ends INCOMPLETE or INVALID inside an array may already have
written it.
``closed`` decides what happens to an id this table does **not** name. Open
(the default), it goes to the decoder's visitor, as it would without a
table. Closed, it is skipped exactly as a decoder with no visitor skips it —
no hook, nothing materialized, no cap spent, decode stays COMPLETE — and a
nested sequence the table does not name is skipped whole.
``which_at`` makes the table a **one-of**: its rows are alternatives, not
siblings, which is what a union is (MESSAGE_SPEC §4.2). The decoder writes the
arriving option's **field id** into that ``words`` slot on every correctly
typed arrival — after the §7.3 tag test, so a mistyped option and an id the
table does not name neither switch nor discard the held option — and the last
arrival wins (§7.4.1). Prepare the slot with the schema's ``default_id``: a
union that never arrives leaves it untouched, which is the same value an empty
union frame decodes to (§4.2), so absence needs no sentinel.
Every option kind here is **replaced whole** by its own arrival — a scalar and
a string/blob by their value, an array by its count and elements (§7.4) — so
nothing of a discarded option can reach a reader that consults ``which_at``
first. A ``struct``/``union`` option is the exception, because a later arrival
rewrites only the children it carries; :meth:`sequence` therefore refuses a
one-of table until the reset §7.4.1 asks for is implemented.
A one-of table should also be ``closed``: an option id a newer sender added is
an unknown id inside the union's scope, and an open table would hand it to the
visitor under the *parent's* identity (below).
That is what a **child** table wants. The decoder descends into a bound
sequence without telling the visitor, so the visitor still believes the walk
is in the parent's scope, and an id the child does not name would reach it
under the parent's identity: an unknown field a newer sender added inside a
struct would land in whichever parent field shares its id. A closed child
cannot hand one over. The flag belongs to the table, so a child bound from
two places behaves the same in both.
"""
__slots__ = (
"_entries", "_by_id", "_words_required", "_objects_required",
"_tree", "_compiled", "_frozen", "_closed", "_which_at", "_default_id",
)
def __init__(
self,
closed: bool = False,
which_at: Any = None,
default_id: Any = 0,
) -> None:
self._closed = bool(closed)
if which_at is None:
self._which_at = -1
else:
slot = _index(which_at, "which slot")
if slot < 0:
raise SofaArgumentError(f"which slot {slot} out of range")
self._which_at = slot
# The option this union holds when none has arrived (§4.2). The caller
# prepares the top-level ``which_at`` slot with it, so the decoder needs
# it only for the reset of a *nested* union inside a re-selected option.
self._default_id = _index(default_id, "default id")
if self._default_id < 0 or self._default_id > ID_MAX:
raise SofaArgumentError(f"default id {self._default_id} out of range")
self._entries: list[Entry] = []
self._by_id: dict[int, Entry] = {}
self._words_required = 0
self._objects_required = 0
# Derived once and reused: a Decoder is built per message in the
# one-shot path, and walking the tree per decode would cost more than
# the decode.
self._tree: tuple[int, int] | None = None
if self._which_at >= 0:
self._words_required = self._which_at + 1
# The native engine's compiled destination map, built on first use and
# cached here: a Binding is build-once, so every Decoder over it reuses
# the same map instead of recompiling per message.
self._compiled: Any = None
self._frozen = False
# --- introspection ------------------------------------------------------
@property
def entries(self) -> tuple[Entry, ...]:
"""The rows, in the order they were bound. The engines compile this."""
return tuple(self._entries)
@property
def which_at(self) -> int:
"""The ``words`` slot the arriving option's field id is written to, or
``-1``. See :class:`Binding`."""
return self._which_at
@property
def default_id(self) -> int:
"""The option a one-of table holds when none has arrived (§4.2)."""
return self._default_id
@property
def closed(self) -> bool:
"""Whether an id this table does not name is skipped rather than handed
to the visitor; see :class:`Binding`."""
return self._closed
@property
def words_required(self) -> int:
"""Slots the ``words`` buffer must hold — i.e. it must be at least
``words_required * 8`` bytes. Counts this table only; a child
:meth:`sequence` binding shares the same buffer, so take the maximum
over the whole tree (or give every table disjoint slots, which is what
generated code does)."""
return self._words_required
@property
def objects_required(self) -> int:
"""Entries the ``objects`` list must hold."""
return self._objects_required
@property
def tree_words_required(self) -> int:
""":attr:`words_required` over this table *and* every table reachable
through :meth:`sequence`. A child shares the parent's storage, so this
is the size the one buffer has to have."""
return self._tree_sizes()[0]
@property
def tree_objects_required(self) -> int:
""":attr:`objects_required` over the whole tree; see
:attr:`tree_words_required`."""
return self._tree_sizes()[1]
def _tree_sizes(self) -> tuple[int, int]:
tree = self._tree
if tree is None:
reachable = self.freeze()
tree = (
max(b.words_required for b in reachable),
max(b.objects_required for b in reachable),
)
self._tree = tree
return tree
[docs]
def freeze(self) -> list[Binding]:
"""Close the table — this one and every child — and return the whole
reachable set.
A binding is a build-once artifact: a :class:`sofab.Decoder` derives its
storage requirements and one handler per table from it and holds them,
so a table that changed afterwards would decode against a stale copy.
Freezing at first use makes that a clear error instead. Called for you —
building the decoder is what freezes the table — and idempotent, so
calling it yourself is harmless.
It is deliberately the *whole tree*: a child bound into a parent is
reachable only downwards, so freezing the root is the only moment at
which every table in it can be reached at once.
"""
reachable = self._reachable()
for b in reachable:
b._frozen = True
if b._which_at >= 0:
# Pushed onto the rows here rather than read off the table in
# the walk: at the store the row is already in hand, while the
# table is one indirection away and would have to live in a
# register across the whole field loop (corelib-py#164).
for e in b._entries:
e.which_at = b._which_at
(e.reset_words, e.reset_objects,
e.reset_into) = _option_reset(e)
return reachable
def _reachable(self) -> list[Binding]:
"""This table and every child, breadth-first, each visited once — a
schema may legitimately be recursive."""
seen = {id(self): self}
out = [self]
i = 0
while i < len(out):
for e in out[i]._entries:
child = e.child
if child is not None and id(child) not in seen:
seen[id(child)] = child
out.append(child)
i += 1
return out
def __len__(self) -> int:
return len(self._entries)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
f"<Binding {len(self._entries)} fields"
f"{', closed' if self._closed else ''}, "
f"{self._words_required} words, {self._objects_required} objects>"
)
# --- binder methods -----------------------------------------------------
[docs]
def unsigned(
self,
field_id: int,
at: int,
count_at: int | None = None,
max_value: int | None = None,
default: int | None = None,
) -> Binding:
"""Bind an unsigned-integer field to ``words`` slot ``at`` (``uint64``).
``max_value`` is the schema's declared width (``0xFF`` for a ``u8``, or
for a ``bitfield`` whose highest ``pos`` is 7). The slot is 64 bits wide
whatever the field declares, so nothing about the storage enforces a
narrower width, and MESSAGE_SPEC §1 then requires an explicit check:
given, a value above it is INVALID at the value, before it is stored —
so a message truncated behind it is INVALID, not INCOMPLETE (§5.2).
``default`` is the schema's declared default for this field, and it
matters for one thing only: a **union option** that is re-selected
starts from it (MESSAGE_SPEC §7.4.1). Outside a one-of table it is
ignored — an absent field leaves the slot exactly as the caller prepared
it, which is how a decode reports absence, and inventing a value there
would take that away."""
return self._add(
K_UNSIGNED, field_id, at, 0, count_at, None, None, max_value,
default=default,
)
[docs]
def signed(
self,
field_id: int,
at: int,
count_at: int | None = None,
min_value: int | None = None,
max_value: int | None = None,
default: int | None = None,
) -> Binding:
"""Bind a signed-integer field to ``words`` slot ``at`` (``int64``).
``min_value``/``max_value`` are the schema's declared width (``-128`` /
``127`` for an ``i8``, or for an ``enum`` whose constants all fit one);
see :meth:`unsigned`. Either side may be given on its own.
``default`` is the schema's declared default for this field, and it
matters for one thing only: a **union option** that is re-selected
starts from it (MESSAGE_SPEC §7.4.1). Outside a one-of table it is
ignored — an absent field leaves the slot exactly as the caller prepared
it, which is how a decode reports absence, and inventing a value there
would take that away."""
return self._add(
K_SIGNED, field_id, at, 0, count_at, None, min_value, max_value,
default=default,
)
[docs]
def boolean(
self,
field_id: int,
at: int,
count_at: int | None = None,
default: int | None = None,
) -> Binding:
"""Bind a boolean field to ``words`` slot ``at`` as ``0`` or ``1``.
A boolean has no wire type of its own (§4.4) — it arrives as an unsigned
integer and is accepted under that tag — but it is **not** the unsigned
binding, because §4.4 splits the two rules that meet here:
* **canonical on encode**: :meth:`sofab.Encoder.write_bool` writes
``true`` as ``1``;
* **tolerant on decode**: *every* value other than ``0`` reads as true.
Such a value is not INVALID — there is nothing to reject, only
something to normalize — so the slot gets ``1``, never the ``42`` the
sender happened to write, and a re-encode emits ``1``.
Doing that here is what keeps the rule off every caller: a slot a
**completed** decode filled can be tested for truth *or* compared to
``1``, and both agree. (Only a completed one — like every other bound
kind, a decode that ends INCOMPLETE or INVALID says nothing about what
it has written so far; :meth:`boolean_array` spells out what that means
for an array caught mid-payload.) Note there is deliberately no
declared-width argument, the way
:meth:`unsigned` has ``max_value``: §4.4 gives a boolean no width bound
at all, unlike an ``enum`` or a ``bitfield``, so binding one with a
ceiling of ``1`` — which would make ``42`` INVALID — is exactly the
reading the clause rules out.
``default`` is the schema's declared default for this field, and it
matters for one thing only: a **union option** that is re-selected
starts from it (MESSAGE_SPEC §7.4.1). Outside a one-of table it is
ignored — an absent field leaves the slot exactly as the caller prepared
it, which is how a decode reports absence, and inventing a value there
would take that away.
A ``default`` follows the same tolerance: anything other than ``0`` is
stored as ``1``.
"""
return self._add(K_BOOLEAN, field_id, at, 0, count_at, None,
default=default)
[docs]
def float32(
self,
field_id: int,
at: int,
count_at: int | None = None,
default: float | None = None,
) -> Binding:
"""Bind an ``fp32`` field to ``words`` slot ``at``, widened to a native
``double`` (read it back through a ``.cast("d")`` view).
``default`` is the schema's declared default for this field, and it
matters for one thing only: a **union option** that is re-selected
starts from it (MESSAGE_SPEC §7.4.1). Outside a one-of table it is
ignored — an absent field leaves the slot exactly as the caller prepared
it, which is how a decode reports absence, and inventing a value there
would take that away.
An ``fp32`` ``default`` is rounded through single precision, because
that is the value the field can hold.
"""
return self._add(K_FLOAT32, field_id, at, 0, count_at, None,
default=default)
[docs]
def float64(
self,
field_id: int,
at: int,
count_at: int | None = None,
default: float | None = None,
) -> Binding:
"""Bind an ``fp64`` field to ``words`` slot ``at`` as a ``double``.
``default`` is the schema's declared default for this field, and it
matters for one thing only: a **union option** that is re-selected
starts from it (MESSAGE_SPEC §7.4.1). Outside a one-of table it is
ignored — an absent field leaves the slot exactly as the caller prepared
it, which is how a decode reports absence, and inventing a value there
would take that away."""
return self._add(K_FLOAT64, field_id, at, 0, count_at, None,
default=default)
[docs]
def string(
self,
field_id: int,
at: int,
maxlen: int = 0,
count_at: int | None = None,
default: str | None = None,
) -> Binding:
"""Bind a UTF-8 ``string`` field to ``objects[at]``.
``maxlen`` is the schema's declared byte length, or ``0`` for a field the
schema leaves unbounded. Declaring it makes the field **schema-bounded**:
a longer payload is INVALID (MESSAGE_SPEC §7.1) and the receiver-side
``max_dyn_string_len`` cap no longer applies to it (§6.2.1). Left at ``0``
the cap applies as usual."""
return self._add(K_STRING, field_id, at, maxlen, count_at, None,
default=default)
[docs]
def bytes(
self,
field_id: int,
at: int,
maxlen: int = 0,
count_at: int | None = None,
default: _Bytes | None = None,
) -> Binding:
"""Bind a ``blob`` field to ``objects[at]``; see :meth:`string` for
``maxlen``."""
return self._add(K_BYTES, field_id, at, maxlen, count_at, None,
default=default)
[docs]
def string_into(
self,
field_id: int,
at: int,
maxlen: int = 0,
count_at: int | None = None,
default: str | None = None,
) -> Binding:
"""Bind a UTF-8 ``string`` field **into the buffer already in**
``objects[at]`` — no ``str`` is built.
This is §6.6.3's third shape: "into a destination the caller declared
before the decode began — a field-id → slot table — which is the bullet
above with the choice made once instead of per field". :meth:`string`
names a slot to *put a value in*, and the value is one the decoder has to
build from the only size it has, the wire's. This names a slot that
already *holds the storage*: put a writable, contiguous, single-byte
buffer (a ``bytearray``, a ``memoryview`` over one, an ``array("B")``) at
``objects[at]`` before decoding, and the decoder validates the payload as
UTF-8 and copies the wire bytes into it.
Nothing here is sized from the wire. A destination shorter than the
announced length is refused with :class:`sofab.SofaArgumentError` — §6.3's
``InvalidArgument``, because "the message is well-formed and within every
bound it declares — what does not fit is the storage this caller offered"
— and it is **never** grown.
``count_at`` receives the payload's **byte length**, which is how the
caller knows how much of its buffer is live; an absent field leaves the
slot exactly as it was prepared, as everywhere else. (The arrival flag
:meth:`string` writes would not be enough here: a caller holding the
bytes needs to know how many of them are the message's.)
``maxlen`` is the schema's declared byte length, exactly as on
:meth:`string`: declaring it makes a longer payload INVALID
(MESSAGE_SPEC §7.1) and takes the receiver-side ``max_dyn_string_len``
cap off the field (§6.2.1). Left at ``0`` the field is schema-unbounded —
and the cap does **not** apply to it either, on the same reasoning
:meth:`sofab.Visitor.on_string_begin` carries: the cap exists to stop the
sender dictating the receiver's allocation, and a caller that put the
buffer there sized it itself. What bounds this field is the buffer, and a
payload past it is refused at the length word before a byte is copied.
"""
return self._add(K_STRING, field_id, at, maxlen, count_at, None,
into=True, default=default)
[docs]
def blob_into(
self,
field_id: int,
at: int,
maxlen: int = 0,
count_at: int | None = None,
default: _Bytes | None = None,
) -> Binding:
"""Bind a ``blob`` field into the buffer already in ``objects[at]``; see
:meth:`string_into`. The only difference is the one :meth:`bytes` has
from :meth:`string` — the payload is copied verbatim and not validated as
UTF-8."""
return self._add(K_BYTES, field_id, at, maxlen, count_at, None,
into=True, default=default)
[docs]
def unsigned_array(
self,
field_id: int,
at: int,
cap: int,
count_at: int | None = None,
elem_max: int | None = None,
default: Sequence[int] | None = None,
) -> Binding:
"""Bind an unsigned-integer array to ``words[at:at + cap]``.
``cap`` is the **schema's** maximum element count. A message declaring
more is malformed against that schema, so it is rejected as INVALID
(MESSAGE_SPEC §7.1) — the decoder never sizes storage from the wire.
``elem_max`` is the schema's declared element width (``0xFF`` for a
``u8`` array, and so on). Given, it is checked **at** each element,
before the element is stored, so a too-wide value is INVALID at the
element that carries it rather than after the array completes."""
return self._add(
K_ARRAY_UNSIGNED, field_id, at, cap, count_at, None, 0, elem_max,
default=default
)
[docs]
def signed_array(
self,
field_id: int,
at: int,
cap: int,
count_at: int | None = None,
elem_min: int | None = None,
elem_max: int | None = None,
default: Sequence[int] | None = None,
) -> Binding:
"""Bind a signed-integer array to ``words[at:at + cap]`` (``int64``).
The two halves of the declared width are independent: either may be
given on its own and bounds its own side (see :meth:`unsigned_array`)."""
return self._add(
K_ARRAY_SIGNED, field_id, at, cap, count_at, None, elem_min, elem_max,
default=default
)
[docs]
def boolean_array(
self,
field_id: int,
at: int,
cap: int,
count_at: int | None = None,
default: Sequence[bool] | None = None,
) -> Binding:
"""Bind an array of booleans to ``words[at:at + cap]`` as ``0``/``1``.
The element half of :meth:`boolean`: an array of boolean travels as an
array of unsigned (§4.4 gives booleans no wire type), and §4.4's decode
rule applies per element, so each slot is normalized as it is stored.
``cap`` is the schema's maximum element count and behaves exactly as it
does for :meth:`unsigned_array`. There is no ``elem_max``, for the reason
:meth:`boolean` takes no width: a boolean element outside ``0..1`` is
normalized, never rejected.
**The elements are normalized when the array completes**, not one at a
time — the pass runs once over the slots the payload filled, so the
element loop every other array kind shares carries no test of its own. A
decode that ends INCOMPLETE or INVALID *inside* this array may therefore
leave raw wire values in the slots it already wrote, exactly as it may
already have written ``count_at`` (see :class:`Binding`). The next
:meth:`sofab.Decoder.feed` refills the array from element zero, so what
a **completed** decode leaves is always ``0``/``1``."""
return self._add(K_ARRAY_BOOLEAN, field_id, at, cap, count_at, None,
default=default)
[docs]
def float32_array(
self,
field_id: int,
at: int,
cap: int,
count_at: int | None = None,
default: Sequence[float] | None = None,
) -> Binding:
"""Bind an ``fp32`` array to ``words[at:at + cap]``, widened to
``double`` per element."""
return self._add(K_ARRAY_FLOAT32, field_id, at, cap, count_at, None,
default=default)
[docs]
def float64_array(
self,
field_id: int,
at: int,
cap: int,
count_at: int | None = None,
default: Sequence[float] | None = None,
) -> Binding:
"""Bind an ``fp64`` array to ``words[at:at + cap]``."""
return self._add(K_ARRAY_FLOAT64, field_id, at, cap, count_at, None,
default=default)
[docs]
def sequence(
self, field_id: int, child: Binding, count_at: int | None = None
) -> Binding:
"""Descend into a nested sequence with ``child`` as its table (§4.9).
The child writes into the *same* ``words`` / ``objects`` storage, so a
whole message tree decodes into one flat pair of buffers. ``count_at``
counts how many times the sequence occurred, which is what tells a
caller whether an optional sub-message was present.
A sequence with no binding is skipped whole, sub-tree and all — the
auto-skip §5.2 requires — and costs nothing but the walk."""
if not isinstance(child, Binding):
raise SofaArgumentError("sequence child must be a Binding")
if child._frozen and not self._frozen:
# The child is already closed, so binding it here would extend a
# frozen tree by the back door.
raise SofaArgumentError("sequence child is already in use by a decoder")
return self._add(K_SEQUENCE, field_id, 0, 0, count_at, child)
# --- internals ----------------------------------------------------------
def _add(
self,
kind: int,
field_id: Any,
at: Any,
cap: Any,
count_at: Any,
child: Binding | None,
elem_lo: Any = None,
elem_hi: Any = None,
into: bool = False,
default: Any = None,
) -> Binding:
if self._frozen:
raise SofaArgumentError(
"this binding is already in use by a decoder; build the table "
"before the decoder, not after"
)
fid = _index(field_id, "field id")
if fid < 0 or fid > ID_MAX:
raise SofaArgumentError(f"field id {fid} out of range")
if fid in self._by_id:
raise SofaArgumentError(f"field id {fid} is already bound")
slot = _index(at, "slot index")
if slot < 0:
raise SofaArgumentError(f"slot index {slot} out of range")
n = _index(cap, "capacity")
if n < 0 or n > (FIXLEN_MAX if kind in _OBJECT_KINDS else ARRAY_MAX):
raise SofaArgumentError(f"capacity {n} out of range")
if count_at is None:
cnt = -1
else:
cnt = _index(count_at, "count slot")
if cnt < 0:
raise SofaArgumentError(f"count slot {cnt} out of range")
self._words_required = max(self._words_required, cnt + 1)
if kind in _OBJECT_KINDS:
self._objects_required = max(self._objects_required, slot + 1)
elif kind in _ARRAY_KINDS:
self._words_required = max(self._words_required, slot + n)
elif kind != K_SEQUENCE:
self._words_required = max(self._words_required, slot + 1)
lo = SIGNED_MIN if elem_lo is None else _index(elem_lo, "elem_min")
signed = kind in (K_SIGNED, K_ARRAY_SIGNED)
hi = (SIGNED_MAX if signed else UNSIGNED_MAX) \
if elem_hi is None else _index(elem_hi, "elem_max")
if not (SIGNED_MIN <= lo <= SIGNED_MAX) or not (
0 <= hi <= (SIGNED_MAX if signed else UNSIGNED_MAX)
):
raise SofaArgumentError("declared element width out of range")
bits = 0
dval: Any = None
if default is not None:
if kind in _SCALAR_KINDS:
bits = _default_bits(kind, default, lo, hi)
else:
dval = self._default_payload(kind, default, n, lo, hi, into)
entry = Entry(kind, fid, slot, n, cnt, child, lo, hi,
elem_lo is not None or elem_hi is not None, into, bits,
dval)
self._entries.append(entry)
self._by_id[fid] = entry
return self
def _default_payload(
self, kind: int, default: Any, cap: int, lo: int, hi: int, into: bool
) -> Any:
"""A ``string``/``blob``/``array`` default, prepared for the reset.
§4.2 refuses a non-empty ``default`` on a union *option* of these kinds,
and that rule is checked here rather than by kind: whether a row is an
option is whether *this table* is a one-of, which is known at bind time.
A member of a struct option is a row of an ordinary child table and
carries no such restriction — which is the whole of corelib-py#169.
Whether the row is *inside* a one-of subtree is not known until
:meth:`freeze` walks the tree, so a default outside one is accepted and
then ignored, exactly as a scalar ``default=`` is.
"""
if kind == K_SEQUENCE:
raise SofaArgumentError(
"a struct/union row takes no default: it starts from the rows of "
"its child table (§4.2)"
)
if self._which_at >= 0:
raise SofaArgumentError(
"a string/blob/array option must not declare a non-empty "
"default; it starts empty (§4.2). A member of a struct option "
"may declare one"
)
if kind in _OBJECT_KINDS:
value = _default_object(kind, default, cap)
if into:
# The reset copies into the caller's buffer, so the value it
# copies is bytes whatever the kind: a string default is encoded
# once here rather than per reset.
return value.encode("utf-8") if kind == K_STRING else value
return value
return _default_elements(kind, default, cap, lo, hi)
def _default_object(kind: int, default: Any, cap: int) -> Any:
"""A ``string``/``blob`` default: the immutable value the reset stores.
The length is checked the way the schema checks it (SCHEMA_SPEC: a ``string``
default's length ≤ ``maxlen``, a ``blob``'s decoded length ≤ ``maxlen``) —
against the declared bound, in **bytes**, because that is what ``maxlen``
counts and what the wire would have carried.
"""
if kind == K_STRING:
if not isinstance(default, str):
raise SofaArgumentError(
f"a string default must be str, got {type(default).__name__}"
)
value: Any = default
length = len(default.encode("utf-8"))
else:
if isinstance(default, str):
raise SofaArgumentError("a blob default must be bytes, not str")
try:
value = bytes(default)
except TypeError as exc:
raise SofaArgumentError(
f"a blob default must be bytes-like, got {type(default).__name__}"
) from exc
length = len(value)
if cap and length > cap:
raise SofaArgumentError(
f"default of {length} bytes is longer than the declared maxlen {cap}"
)
return value
def _default_elements(
kind: int, default: Any, cap: int, lo: int, hi: int
) -> tuple[int, ...]:
"""An array default, as one ``words`` value per element.
Each element goes through the same normalisation its own arrival would get:
a signed element in two's complement, a boolean through §4.4's "anything
other than 0 is true", a float as its ``double`` bits (an ``fp32`` rounded
through single precision first, like a scalar ``fp32`` default). The count is
checked against ``cap``, which is the schema's element count (SCHEMA_SPEC: an
array default's length ≤ ``items.count``).
"""
try:
values = tuple(default)
except TypeError as exc:
raise SofaArgumentError(
f"an array default must be iterable, got {type(default).__name__}"
) from exc
if len(values) > cap:
raise SofaArgumentError(
f"default of {len(values)} elements is longer than the declared "
f"capacity {cap}"
)
scalar_of = {
K_ARRAY_UNSIGNED: K_UNSIGNED,
K_ARRAY_SIGNED: K_SIGNED,
K_ARRAY_BOOLEAN: K_BOOLEAN,
K_ARRAY_FLOAT32: K_FLOAT32,
K_ARRAY_FLOAT64: K_FLOAT64,
}[kind]
return tuple(_default_bits(scalar_of, v, lo, hi) for v in values)
def _default_bits(kind: int, default: Any, lo: int, hi: int) -> int:
"""One 64-bit pattern for a declared ``default`` (§7.4.1, §2).
Stored the way the decode path stores the value it replaces — a signed
default in two's complement, a float's as its ``double`` bits — so the reset
writes ``words`` without knowing the kind. An ``fp32`` default is rounded
through single precision first, because that is the value an ``fp32`` field
can actually hold and therefore what its own arrival would leave.
"""
if kind not in _SCALAR_KINDS:
raise SofaArgumentError(
"a default belongs to a scalar row or an array element; a "
"string/blob row goes through _default_object and a struct/union "
"row starts from its children (§4.2)"
)
if kind == K_FLOAT64 or kind == K_FLOAT32:
try:
# ``__float__`` rather than ``float()``, for the same reason
# :func:`_index` asks for ``__index__``: a string that happens to
# parse is a mistake, not a default.
value = default.__float__()
except AttributeError as exc:
raise SofaArgumentError(
f"default must be a real number, got {type(default).__name__}"
) from exc
if kind == K_FLOAT32:
value = struct.unpack("<f", struct.pack("<f", value))[0]
packed: int = struct.unpack("<Q", struct.pack("<d", value))[0]
return packed
number = _index(default, "default")
if kind == K_BOOLEAN:
# §4.4: a boolean has two values and no declared width, so anything
# other than 0 is true -- the same normalisation the decode half does.
return 1 if number else 0
if not (lo <= number <= hi):
raise SofaArgumentError(
f"default {number} is outside the declared width {lo}..{hi}"
)
return number & 0xFFFF_FFFF_FFFF_FFFF
def _option_reset(
e: Entry,
) -> tuple[
tuple[tuple[int, int], ...],
tuple[tuple[int, Any], ...],
tuple[tuple[int, bytes], ...],
]:
"""Every slot an option owns, and the value it starts from (§7.4.1).
Walked only when a *different* option arrives, which a conformant producer
never causes (§4.2 emits one child, §7.4 calls a repeated id not
well-formed), so this is built once here and the decode path just replays
it. Flat rather than recursive: a ``struct``/``union`` option's children —
and their children — are slots like any other, and a nested union's
``which_at`` starts at its own ``default_id``.
"""
words = list(e.own_words)
objects = list(e.own_objects)
into = list(e.own_into)
child = e.child
if child is not None:
# A schema may be recursive, so each table is visited once: its rows
# write the same slots however often the cycle is walked.
seen = {id(child)}
stack = [child]
while stack:
table = stack.pop()
rows: tuple[Entry, ...] | list[Entry] = table._entries
if table._which_at >= 0:
words.append((table._which_at, table._default_id))
# §4.2: "A new union holds ``default_id`` at that option's own
# default", so a nested union contributes its which slot and the
# storage of *that one* option -- not of all of them. It matters
# whenever two options share a slot, which a union invites: only
# one of them is ever held, so overlapping them is legitimate,
# and writing every option's default would then leave whichever
# row came last.
held = table._by_id.get(table._default_id)
rows = () if held is None else (held,)
for row in rows:
words.extend(row.own_words)
objects.extend(row.own_objects)
into.extend(row.own_into)
grandchild = row.child
if grandchild is not None and id(grandchild) not in seen:
seen.add(id(grandchild))
stack.append(grandchild)
return tuple(words), tuple(objects), tuple(into)
def _index(value: Any, what: str) -> int:
"""``__index__`` or a §6.3 InvalidArgument — never a silent truncation."""
try:
index: int = value.__index__()
except AttributeError as exc:
raise SofaArgumentError(
f"{what} must be an integer, got {type(value).__name__}"
) from exc
return index
# A Binding is reached through the handler that declares it -- see
# :meth:`sofab.Visitor.destinations`. There is no adapter here and no second
# decode path anywhere: the decoder consults the table at the point a value is
# stored, and every rule that decides *whether* and *how* the value is decoded
# runs in the one place both engines already had. §5.3.1 asks for one surface,
# and one surface is what a destination map leaves.