Skip to Content
Binal

Schema Language

The .binal text syntax

A .binal schema describes a format as text. It runs from Python through Format, from the command line through binal, and any model can be exported as one.

from binal import Format

messages = Format("""
enum Kind: u8 { text = 1, move = 2 }

struct Message {
    byte_order big,
    magic: bytes size 3 = b"MSG",
    urgent: flag,                       // one bit
    priority: u7,
    kind: Kind,
    length: u16 = sizeof(body),         // computed and verified
    body: Body(kind) size length,
    crc: u32 = crc32(bytesof(urgent, priority, kind, length, body)),
}

type Body(kind: int) = match kind {
    Kind.text => str,
    Kind.move => Move,
    _ => bytes,
}

struct Move { x: u16 where x < 640, y: u16 where y < 480 }
""")

data = messages.encode(
    "Message",
    {"urgent": True, "priority": 5, "kind": "move", "body": {"x": 320, "y": 200}},
)
messages.decode("Message", data)["body"]  # {'x': 320, 'y': 200}

Definitions

DefinitionMeaning
struct Name { ... }Members in order, separated by commas
enum Name: u8 { a = 1, b = 2 }Named values; any other value is an error
open enum Name: u8 { ... }Named values; any other value stays a number
type Name = ...A name for any type
struct Name(n: int, text: bytes)Parameters, given where the type is used: Name(count, tag). A parameter is int, bool, bytes, str, space, or any. Types take them too.

Comments start with //.

Members

MemberMeaning
name: typeA field
byte_order bigThe byte order from here on: big, little, or an expression that gives one
bit_order msbWhich end of a byte bits are taken from: msb or lsb
let name = exprA name for a value, which is not stored
seek exprContinue at this position

A field can have clauses after its type:

ClauseMeaning
if exprPresent only if the condition holds
= exprComputed when encoding, verified when decoding; the value may be left out
where exprA rule the value must satisfy; may be repeated
at exprStored at this position instead of the current one
align exprStarts at a multiple of this

Types

TypeMeaning
u1 to u128, i1 to i128Integers; u16le and u16be state a byte order. A width that is not whole bytes is packed.
bits(n), sbits(n)An integer whose width is an expression
f16, bf16, f32, f64Floats, with the same suffixes
flag, boolA bit; a byte that is 0 or 1
uleb128, sleb128, vlq, zigzag, zigzag32, zigzag64, sqlite_varintVarints
bytesThe rest of the region it is in
str, str(latin1)Text: utf8 (the default), ascii, latin1, utf16le, utf16be, utf32le, utf32be
[T; n]An array of n elements
[T; prefix u16]An array after its count
[T; rest]Elements up to the end of the region
[T; until cond]Elements up to and including the first that satisfies the condition, where it is it
[T; terminated 0]Elements up to a terminator, which is not one of them
match expr { a => T, _ => U }A type chosen by a value
either(T, U)The first type that decodes
ref(u32) TThe address of a T
space(zlib) TA T in its own address space, with an optional codec: deflate, zlib, reverse

A frame after a type bounds the region it is read from:

FrameMeaning
size nExactly n bytes
prefix u16As many bytes as the prefix says
terminated 0Up to a terminator: a byte, "text", or b"bytes"
padded n, padded n with 32n bytes, filled at the end with a pad byte (0 if not given)

References

ref(storage, options) Type stores an address as an unsigned integer. The target is a named type.

OptionMeaning
base expr, unit exprThe object is at base + address × unit
null nThe address that means no object
in nameThe address space it is in
align nObjects are allocated at multiples of it
internEqual objects are stored once

References and Spaces explains identity, sharing, and spaces gathered from several pieces (space T gather (first, follow(chain, content, next, 512))).

Expressions

Integers (10, 0xff, 0b101, 1_000), floats, "text", b"\x89PNG", true, false, names of earlier fields and parameters, members (a.b), elements (a[0]), and enum values (Kind.text). The operators, loosest first:

? :, ||, &&, comparisons, |, ^, &, shifts, + -, * / %, and unary - ! ~.

As in Rust, comparisons bind looser than bitwise operators: flags & 1 == 0 means (flags & 1) == 0.

FunctionGives
len(x)Elements of an array, or bytes
sizeof(f)A field’s encoded size
offsetof(f)A field’s position
bytesof(f, g)The encoded bytes of fields, joined
start(), here()Where this struct starts, and where the next member is
index()An array element’s index, in its arguments
input_size()The size of the address space
rfind(bytes)The last position of some bytes, when decoding
min(a, b), max(a, b)The smaller and the larger
crc8, crc16, crc16_modbus, crc32, crc32c, crc64, adler32Checksums of bytes
inflate(bytes)Raw DEFLATE data, decompressed
zeros(n)n zero bytes
octal(bytes)A number in ASCII octal, as tar stores sizes

A computed field may use anything in the struct, before or after it: encoding finds an order, and reports a cycle if there is none.

The format schemas use most of the language.