binal
Declarative binary modeling for Python.
Describe a binary format once, as a Python class or as a .binal schema.
Encoding, decoding, validation, checksums, layout, and error messages all
come from that one description.
from dataclasses import field
from typing import Annotated
from binal import CRC32, BinaryModel, Checksum, LengthOf, Sized, UInt8, UInt16, UInt32
class Frame(BinaryModel, byte_order="big"):
version: UInt8
length: Annotated[UInt16, LengthOf("payload")] = field(init=False)
payload: Annotated[bytes, Sized("length")]
crc: Annotated[UInt32, Checksum(CRC32, fields=("version", "length", "payload"))] = (
field(init=False)
)
data = Frame(version=1, payload=b"Hello").encode() # length and CRC are computed
frame = Frame.decode(data) # and verified
frame.payload # b'Hello' Start with the quick start, or go straight to what your format needs.
Describe a format
| Your format has | Use |
|---|---|
| Integers of any width, varints | UInt8 to UInt128, Integer(12), ULEB128, ZigZag, VLQ |
| Floats, fixed point, decimals, BCD | Float16 to Float128, BFloat16, FixedPoint, Decimal64DPD, BCD |
| Text and bytes | Sized, Padded, Prefixed, NullTerminated, Terminated, Greedy |
| UUIDs, addresses, dates and times | UUID, GUID, IPv4, MAC, Timestamp, Duration |
| Flags and packed bits | BitModel, Bits, enums and flags, fixed storage widths |
| Lists and tuples | Fixed, counted, prefixed, terminated, greedy, and byte-bounded |
| Lengths, counts, and sizes that depend on other fields | LengthOf, CountOf, Sized("length"), or a Python callable |
| Optional parts and message types | When, TaggedUnion, untagged unions |
| Magic numbers, versions, padding, alignment | Const, Padding, Align |
| Checksums | CRC-8 to CRC-64, Adler-32, or any function |
| Pointers, shared objects, cycles | Ref, Offset |
| Compressed or scattered data | Space("zlib"), Space(gather=...) |
| Values that are not in the data | Context, Args |
| Something else | A codec of your own |
Use it
| To | Use |
|---|---|
Decode bytes, files, streams, or asyncio streams | I/O |
| Parse data that arrives in pieces | incremental_parser |
| Read one record of a large file | BinaryReader.read_at |
| Process many records in one call | decode_many, encode_many |
| Reject invalid data with a useful message | Validation |
| Bound memory and depth for untrusted input | Limits |
| Edit a file and keep every byte you did not touch | Documents |
| See where each field is, or why data does not decode | Inspection |
| Know sizes and offsets without any data | schema() and layout() |
| Write a format as text, without Python classes | The schema language |
| Use a model’s format from other languages | Portable schemas |
The repository’s
examples/ are
complete programs: Modbus RTU, TCP segments, a telemetry receiver, a map
tile archive, and editing a PNG’s metadata.