Skip to Content
Binal
API Reference

Limits

Configurable resource limits for decoding untrusted input

Decoding must never allocate in proportion to a value read from the wire without first checking it against a bound. Limits carries those bounds; a model can override them per class with the limits= class keyword. Every bound is validated before any allocation it guards, and every bound must be a positive integer.

from binal import BinaryModel, Limits, Prefixed, UInt16
from typing import Annotated


class Packet(BinaryModel, byte_order="big", limits=Limits(max_field_length=1_000_000)):
    payload: Annotated[bytes, Prefixed(UInt16)]

The defaults:

BoundDefaultMeaning
max_field_length16 MiBLargest single field (bytes/str payload), in bytes. A wire length above this is rejected before any bytes are read for the field.
max_collection_size1,000,000Largest number of elements in one collection. A wire count above this is rejected before the first element is decoded.
max_model_size64 MiBLargest input accepted by decode() for a single model, in bytes.
max_nesting_depth512Deepest nesting of models inside models. Deeper input is rejected instead of exhausting the Python stack.
max_varint_bytes1024Longest variable-length integer encoding, in bytes. Width-bound varints (ZigZag32 / ZigZag64) have their own tighter caps derived from their width.
max_buffered_input64 MiBMost bytes a streaming reader may buffer while waiting for a complete record.

A violation raises DecodeError (or, for a nested model that is too deep, a DecodeError converted from a RecursionError). The limits apply to decode(), decode_partial(), streams, and the incremental parser alike.