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.
| Schema | Describes | Left as bytes | Rejected or ignored |
|---|---|---|---|
elf | File, program, and section headers; section names | All section contents: symbols, relocations, dynamic entries, notes | Extended section numbering |
zip | End record, central directory, local files | Compressed data, extra fields | ZIP64, encryption, data descriptors, methods other than stored and deflate |
pcapng | Section header, interface and enhanced packet blocks | Other blocks, option values, packets | Further sections |
tiff | Directories and their entries | Entry values | Image data, sub-directories, BigTIFF |
mp4 | The box tree, mvhd, mdhd, hdlr, stsz, elst | Every other box, including the other sample tables and fragments | |
sqlite | Header, table and index b-trees, records, overflow chains | Freelist, pointer maps, WAL, UTF-16 | |
png | Chunks with their CRCs, IHDR, tEXt | Every other chunk, including image data | |
gif | Screen, image, and extension framing | Color tables, image data, extension contents | |
wav | Chunks, fmt | Samples, the extensible fields, other chunks | RF64, RIFX |
tar | ustar headers | Contents, pax records | GNU extensions, the header checksum |
gzip | One member, its CRC and size | Compressed data | Further 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
decodecannot 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.