Skip to Content
Binal

Formats and Documents

Run .binal schemas from Python, and edit files losslessly

A Format is a compiled schema, written in .binal text or portable JSON; Schema Language describes the text. It works with plain values: structs are dicts, enum values their variant names, arrays lists.

from binal import Format

fmt = Format("""
struct List { head: ref(u8, null 0) Node }
struct Node { value: u8, next: ref(u8, null 0) Node }
""")

fmt.encode("List", {"head": {"value": 5, "next": None}})   # b"\x01\x05\x00"
fmt.decode("List", b"\x01\x05\x00")                      # {"head": {"value": 5, "next": None}}

decode replaces every reference by its object. Format.load(path) reads a schema file, and export_schema(Model).format() gives the format of a model.

Records stored back to back decode and encode in one call:

log = Format("struct Sample { sensor: u8, value: u16le }")
data = log.encode_many("Sample", [{"sensor": 1, "value": 2}, {"sensor": 3, "value": 4}])
log.decode_many("Sample", data)   # [{"sensor": 1, "value": 2}, {"sensor": 3, "value": 4}]

A failure’s path starts with the record’s index ([1].value), and its offset counts from the start of the input.

Format schemas

The repository’s formats/ directory holds skeleton schemas of real formats. They show the language at work and test it; they are not parsers for those formats. Most are under 100 lines, describe the headers and pointers, and leave the harder tables as bytes. They are tested on small fixtures, so expect files from elsewhere to use features they lack. They are in the repository, not in the installed package.

SchemaDescribesLeft as bytesRejected or ignored
elfFile, program, and section headers; section namesAll section contents: symbols, relocations, dynamic entries, notesExtended section numbering
zipEnd record, central directory, local filesCompressed data, extra fieldsZIP64, encryption, data descriptors, methods other than stored and deflate
pcapngSection header, interface and enhanced packet blocksOther blocks, option values, packetsFurther sections
tiffDirectories and their entriesEntry valuesImage data, sub-directories, BigTIFF
mp4The box tree, mvhd, mdhd, hdlr, stsz, elstEvery other box, including the other sample tables and fragments
sqliteHeader, table and index b-trees, records, overflow chainsFreelist, pointer maps, WAL, UTF-16
pngChunks with their CRCs, IHDR, tEXtEvery other chunk, including image data
gifScreen, image, and extension framingColor tables, image data, extension contents
wavChunks, fmtSamples, the extensible fields, other chunksRF64, RIFX
tarustar headersContents, pax recordsGNU extensions, the header checksum
gzipOne member, its CRC and sizeCompressed dataFurther members, the header CRC

Many of them store sizes, counts, and checksums as plain fields, so an edit can leave a file that other programs reject. Bytes a schema does not describe survive only when you edit a document or encode over the original.

from pathlib import Path

from binal import Format

png = Format.load("formats/png.binal")
image = png.decode("Png", Path("image.png").read_bytes())

Documents

open keeps references as references:

doc = fmt.open("List", bytes([1, 10, 3, 20, 1]))   # a cycle
head = doc.root["head"]          # a Reference
doc[head]                        # {"value": 10, "next": <Reference>}, read now
second = doc[head]["next"]
doc[second]["next"] == head      # True: the same object
  • Lazy. An object is read the first time it is asked for; resolve_all() reads everything reachable.
  • Identity is not equality. Two references are equal when they name the same object. Two objects with equal values at different addresses are different objects; doc.same(a, b) asks directly. A reference belongs to its document and is refused by any other.
  • Cycles and sharing are kept, which a plain decode cannot do: it reports a cycle as an error.
  • doc.location(ref) gives the object’s type, address space, address, and size.

Editing

doc[head] = {"value": 99, "next": second}   # every reference to it sees this
doc.root = {"head": {"value": 1, "next": None}}   # a plain value: a new object
data = doc.encode()

encode is lossless: it writes over the original input, so bytes the schema does not describe are kept. Objects and positioned data stay where they were read while they still fit; an object that grew, or a new one, is appended, and every reference, size, and count that depends on it is recomputed.

An object that overlaps another keeps its own value: if an edit makes them disagree on a shared byte, one of them is appended and its references follow. Editing "foobar" in a string table that stores "bar" as its end leaves "bar" as it was. To change both, set both.