Metadata-Version: 2.4
Name: binal
Version: 0.7.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Telecommunications Industry
Classifier: Natural Language :: English
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Communications
Classifier: Topic :: Software Development
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Archiving
Classifier: Topic :: Utilities
Requires-Dist: fastcrc>=0.5
Requires-Dist: tibs>=2.0.2
License-File: LICENSE
Summary: Declarative binary modeling for Python. Define a format once. Get encoding, decoding, validation, and layout from the same declaration.
Keywords: binary,binary-format,bit-level,bitfield,checksum,codec,crc,data-format,decode,decoding,deserialization,encode,encoding,endian,file-format,marshalling,packet,parser,protocol,schema,serialization,sleb128,struct,uleb128,unmarshalling,validation,varint
Author-email: Nolan <300344883+nolantw@users.noreply.github.com>
License-Expression: MIT
Requires-Python: >=3.13
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/nolantw/binal/blob/main/CHANGELOG.md
Project-URL: Documentation, https://nolantw.github.io/binal/
Project-URL: Homepage, https://nolantw.github.io/binal/
Project-URL: Issues, https://github.com/nolantw/binal/issues
Project-URL: Repository, https://github.com/nolantw/binal

<div align="center">

<h1>binal</h1>

<p><strong>Declarative binary modeling for Python</strong></p>

<p>
Define a binary format once, as a Python class, and get encoding,<br>
decoding, validation, and layout from the same declaration.
</p>

<p>
<a href="https://pypi.org/project/binal/"><img alt="PyPI version" src="https://img.shields.io/pypi/v/binal"></a>
<a href="pyproject.toml"><img alt="Python 3.13+" src="https://img.shields.io/badge/python-3.13%2B-blue"></a>
<a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-blue"></a>
</p>

<p>
<a href="https://nolantw.github.io/binal/"><b>Documentation</b></a>
·
<a href="#capabilities"><b>Capabilities</b></a>
·
<a href="#installation"><b>Installation</b></a>
·
<a href="#usage"><b>Usage</b></a>
·
<a href="https://nolantw.github.io/binal/docs/contributing"><b>Contributing</b></a>
</p>

</div>

<br>

## Capabilities

| Area | What it covers |
|:--|:--|
| [Binary types](docs/content/docs/binary-types/index.mdx) | Integers of any width up to 128 bits, varints (LEB128, zigzag, VLQ), binary floats from 8-bit to binary128, decimal floats (BID and DPD), fixed point, BCD, bytes, and strings (sized, prefixed, terminated, greedy) |
| [Semantic types](docs/content/docs/binary-types/semantic.mdx) | UUIDs, IP and MAC addresses, timestamps, dates, times, durations, complex and rational numbers |
| [Modeling](docs/content/docs/modeling/collections.mdx) | Nested and recursive models, bit fields, lists, tuples, enums and flags, tagged and untagged unions, conditional and dependent fields, derived lengths and counts |
| [References](docs/content/docs/modeling/references.mdx) | Offsets and pointers into address spaces, shared and cyclic objects |
| [Checksums](docs/content/docs/api/checksums.mdx) | CRC-8, CRC-16, CRC-32, CRC-32C, CRC-64, and Adler-32, verified on decode |
| [I/O](docs/content/docs/io.mdx) | File, buffer, stream, and asynchronous I/O, incremental parsing and partial decoding, sequences of records in one call |
| [Validation](docs/content/docs/validation.mdx) | Field constraints, cross-field validation, and structured errors with field paths and byte offsets |
| [Introspection](docs/content/docs/advanced/schema.mdx) | Static schema and runtime layout with field offsets and sizes |
| [Formats and documents](docs/content/docs/advanced/documents.mdx) | [`.binal` schemas](docs/content/docs/advanced/schema-language.mdx) run from Python, lossless editing that keeps unknown bytes, and [skeleton schemas](docs/content/docs/advanced/documents.mdx#format-schemas) of common file formats |
| [Inspection](docs/content/docs/advanced/inspection.mdx) | Where every field and object of a file is, and why one does not decode, from Python or the `binal` command |
| [Portable schemas](docs/content/docs/advanced/portable-schemas.mdx) | A model's format exported as JSON for other languages and tools |
| [Low-level I/O](docs/content/docs/api/io.mdx) | `BinaryReader` and `BinaryWriter` for ad-hoc formats and custom codecs |

## Installation

binal supports Python 3.13 and newer. It depends on fastcrc (CRC checksums) and tibs (bfloat16 and 8-bit floats), both with prebuilt wheels.

Add it to a uv project:

```sh
uv add binal
```

To install it in an active Python environment:

```sh
pip install binal
```

To build from source, which needs Rust 1.88 or newer:

```sh
git clone https://github.com/nolantw/binal
cd binal
uv sync --locked
```

## Usage

### Describe a format once

Lengths, checksums, bit fields, constants, and unions are declared, not
coded. Derived fields take no argument: encoding computes them and
decoding verifies them.

```python
from dataclasses import field
from enum import IntEnum
from typing import Annotated

from binal import (
    CRC32,
    BinaryModel,
    BitModel,
    Bits,
    Checksum,
    Const,
    LengthOf,
    Prefixed,
    Range,
    Sized,
    TaggedUnion,
    UInt8,
    UInt16,
    UInt32,
)


class Kind(IntEnum):
    TEXT = 1
    MOVE = 2


class Flags(BitModel):
    urgent: Annotated[bool, Bits(1)]
    priority: Annotated[int, Bits(7)]


class Text(BinaryModel, byte_order="big"):
    body: Annotated[str, Prefixed(UInt16)]


class Move(BinaryModel, byte_order="big"):
    x: Annotated[UInt16, Range(0, 639)]
    y: Annotated[UInt16, Range(0, 479)]


class Message(BinaryModel, byte_order="big"):
    magic: Annotated[bytes, Const(b"MSG")] = field(init=False)
    flags: Flags
    kind: Annotated[Kind, UInt8]
    body: Annotated[
        Text | Move, TaggedUnion("kind", {Kind.TEXT: Text, Kind.MOVE: Move})
    ]
    crc: Annotated[UInt32, Checksum(CRC32, fields=("flags", "kind", "body"))] = field(
        init=False
    )


message = Message(Flags(urgent=True, priority=5), Kind.TEXT, Text("Hello"))
data = message.encode()
data.hex(" ")  # '4d 53 47 85 01 00 05 48 65 6c 6c 6f 67 5f be 1c'
assert Message.decode(data) == message
```

### See exactly what went wrong

Errors name the field, the byte, and the rule.

```python
from binal import DecodeError, ValidationError

try:
    Message.decode(data[:9])
except DecodeError as error:
    print(error.path, error.offset, error.is_incomplete)
    # Message.body.body 7 True

try:
    Move(640, 0)
except ValidationError as error:
    print(error.path, error.expected, error.received)
    # Move.x value between 0 and 639 640
```

### Follow pointers, even in cycles

A `Ref` field stores an address; its value is the object there.
Encoding places the objects and fills in the addresses.

```python
from binal import Ref


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


Node(1, Node(2, None)).encode()  # b"\x01\x02\x02\x00"

# A document keeps references, so a cycle can be read and edited.
document = Node.open(b"\x01\x02\x02\x00")
second = document.root.next
document[second] = Node(7, None)
document.encode()  # b"\x01\x02\x07\x00"
```

### Edit a file

A `.binal` schema describes a format as text. Here a PNG's title
changes, and its length and CRC follow.

```python
from pathlib import Path

from binal import Format

png = Format.load("formats/png.binal")
image = png.decode("Png", Path("formats/fixtures/image.png").read_bytes())
for chunk in image["chunks"]:
    if chunk["type"] == b"tEXt" and chunk["data"]["keyword"] == "Title":
        chunk["data"]["text"] = "Edited with binal"
        del chunk["length"], chunk["crc"]
edited = png.encode("Png", image)
```

The schemas in `formats/` are skeletons, not parsers for their formats:
most describe headers and pointers, checked on small fixtures, and leave
the harder tables as bytes. See
[what each one leaves out](docs/content/docs/advanced/documents.mdx#format-schemas).

### Read it any way it arrives

```python
from io import BytesIO

stream = BytesIO(data * 3)
assert list(Message.iter_read(stream)) == [message] * 3  # one at a time
assert Message.decode_many(data * 3) == [message] * 3  # in one call
record, consumed = Message.decode_partial(data + b"more")  # a prefix
```

### Take the format to other languages

```python
from binal import export_schema

export_schema(Move).to_source()
# struct Move {
#     byte_order big,
#     bit_order msb,
#     x: u16 where x >= 0 && x <= 639,
#     y: u16 where y >= 0 && y <= 479,
# }
```

## Project status

binal is pre-1.0: the API may change between minor releases.

## License

MIT. See [LICENSE](LICENSE).

