Changelog
1.1.0
codec.decodeExact(bytes, offset?)decodes a value that must end the bytes, failing at the first byte after it.Decoder<O>is the type of codecs that may only decode (Codec<O, never>), for choices and tables of parsers.reader.offsetcan be set, to decode values in any order.parser.fieldslists the names of the fields a parser decodes.fail(error)fails with an error of your own, as if a function threw it.- Arrays with a count read from the input, of items that vary in size, reserve no more places than the input has bytes: a few bytes no longer make decoding allocate hundreds of megabytes before it fails.
- A failure deep in a recursive value no longer writes out its whole path again at each level it passes. The
pathof errors is frozen.
1.0.0
binopsy is rewritten in TypeScript. Formats are still described field by field, but everything else is new: a parser is a codec that both decodes and encodes, its values are typed from its fields, and it compiles to JavaScript specialized to its format.
None of the API of 0.0.0, the last published version, remains; it followed binary-parser’s. The table below maps it to the new API, and the README documents all of it. Formats rewritten this way keep their bytes, except where noted, but not the quirks of 0.0.0, such as returning partial values for truncated input.
Migrating from 0.0.0
| 0.0.0 | Now |
|---|---|
const Bin = require("binopsy"), new Bin(), Bin.start() |
import { bin } from "binopsy", bin() (ES module only) |
| Field methods change the parser | Field methods return a new parser |
.uint8("a"), .int16le("a"), .floatbe("a"), .doublele("a") |
.u8("a"), .i16le("a"), .f32be("a"), .f64le("a") |
.endianess("little").uint16("a") |
.u16le("a") (no default byte order) |
.bit3("a").bit5("b") |
.field("a", bits(3)).field("b", bits(5)); numbers after bit fields start at the next byte, as before |
.endianess("little").bit3("a").bit2("b") |
.field("b", bits(2)).field("a", bits(3)): the fields of each run in reverse order (the padding stays last) |
| Bit fields of nested parsers sharing bytes with the parent’s | One run of bit fields, and map to the nested object (nested parsers start at a byte) |
.string("s", { length: 4 }) |
.field("s", string(4)); encoding needs text of 4 bytes, unless it has a terminator or padding |
.string("s", { length: 4, stripNull: true }) |
string(4, { padRight: 0 }) (trailing zeros are removed) |
.string("s", { zeroTerminated: true }) |
string({ terminator: 0 }); a missing terminator fails |
.string("s", { zeroTerminated: true, length: 8 }) (or a field or function) |
string({ terminator: 0, max: 8 }) (string(8, { terminator: 0 }) takes all 8 bytes) |
.string("s", { length: "n" }), { encoding: "latin1" } |
string("n"), string(n, { encoding: "latin1" }); zero terminators of utf16le strings are 16-bit units |
{ encoding: "hex" }, "base64" |
map(bytes(length), …) (text encodings: utf8, latin1, ascii, utf16le) |
.buffer("b", { length: "n" }), { readUntil: "eof" } |
bytes("n"), bytes(Infinity) (Uint8Arrays, viewing the input) |
.buffer("b", { length: 4, clone: true }) |
map(bytes(4), { decode: (b) => new Uint8Array(b), encode: (b) => b }) |
.array("a", { type, length: "n" }) |
array(type, "n"), or array(type, u8) (the count is not a field, and is written from the array) |
.array("a", { type, readUntil: "eof" }), { readUntil: (item) => … } |
array(type, Infinity), array(type, { until: (item) => … }) (the last item is included) |
.array("a", { type, length, readUntil }) |
A custom codec (an array up to an item, or of a length, whichever comes first) |
.array("a", { type, length, key: "id" }) |
map(array(type, length), …) to an object |
.nest("a", { type: Parser }), { flatten: true } |
.field("a", Parser), .merge(Parser) |
.fixedSizeNest("a", { type, length }) |
.field("a", sized(length, type)) |
.choice("a", { tag: "t", choices, defaultChoice }) |
.field("a", match("t").case(1, A).case(2, B).otherwise(D)): the objects become a union discriminated by t |
.choice("a", { tag: (o) => …, choices }) |
.field("a", match((o: …) => …).case(…)) |
.choice("a", { …, flatten: true }) |
.merge(match("t").case(1, A)…), of parsers |
{ formatter, deformatter } |
map(codec, { decode, encode }), or only decode; functions of the whole object map the parser |
{ assert: 1 }, { assert: (v) => … } |
literal(codec, 1) (which may be omitted when encoding), refine(codec, (v) => …) (also checked when encoding) |
.create(Class) |
map(parser, { decode: (o) => Object.assign(new Class(), o), encode: … }) |
parser.parse(buffer) |
parser.decode(bytes); truncated input throws a DecodeError |
parser.serialize(value), parser.serialize(value, buffer) |
parser.encode(value), parser.encodeInto(value, bytes) (which returns the offset after the value) |
parser.sizeOf(), parser.sizeOf(value) |
parser.size (fixed size, otherwise NaN), parser.sizeOf(value) |
parser.stream() (a Transform) |
decodeStream(parser, source) (an async iterator); Readable.from it for a Node.js stream |
Type objects with readFunc, writeFunc, sizeFunc |
custom({ decode, encode, size }) |
compile(), getCode() |
Not needed: codecs compile themselves |
Functions of the parent object (function () { return this.n }) |
Functions of the earlier fields: (o) => o.n |
Also watch for:
- The bit layout of
.endianess("little")is not thelsborder: reverse the fields of each run of bit fields, and keep the padding last. - Terminators of
utf16lestrings are 16-bit units (0.0.0 looked for a zero byte). - Arrays mapped to objects by a key must decide what duplicate keys and the order of keys become.
- Assertions on other fields of the object (
thisin 0.0.0) become arefineof the whole parser. - State set by the constructor of
.create(Class)needs amapor acustomcodec.
New
- Types: the decoded and encoded values are inferred (
Output<typeof parser>,Input<typeof parser>); lengths, tags and functions are checked against the fields before them, and editors complete the names of fields. enumOf(codec, table, policy?)decodes numbers as names, TypeScript enum members or values of const objects. Unknown numbers are rejected (enumOf.reject), kept (enumOf.keep), or decoded as a fallback name or member given as the third argument; the policy may be left out when the table names every value of abits(1)tobits(5)field.matchcases may be numeric enum members.parser.pick(...fields)decodes some fields and steps over the others;Readerdecodes consecutive values.codec.sizeOf(value)computes the size of a value without encoding it (customcodecs are encoded, unless they have asize).trace(codec, bytes)returns where each field of a value is, with its value..skip(n)steps over reserved bytes (0.0.0 did not support.skip), and.align(n)over those up to a multiple ofnbytes from the start of the parser.- Computed fields (
.computed) and literals may be omitted when encoding; counts read before a value are written from it (also the size of a region, after it). - Parsers can read fields of the parser they are added to:
bin<{ length: number }>(). optional(flag, codec)andwhen(condition, codec)for values that may be absent;lazyfor recursive formats;customfor formats of your own;failfor unsupported parts.- Strings: padding, terminators of any byte, and lengths of any kind.
- 24-bit integers, 64-bit integers as
bigint, and bit fields of up to 53 bits (#12). - Errors give the path of the field (e.g.
items[3].name) and the offset. - Streams decode values spanning chunks without starting over at each chunk, work with any async iterable, such as Node.js and web streams, and close their source when stopped.
- binopsy works in browsers: it uses
Uint8Arrays andDataViews instead ofBuffers. Bundlers leave out the code of matches and bit fields when a format does not use them.
Behaviour to know
- Bit fields (
bits(width), andenumOf,map,literalorrefineof one) are fields of parsers, and consecutive ones share bytes. They cannot be array items or standalone codecs: the types reject this, and it throws when compiled. codec.sizeisNaNwhen values vary in size, or (forlazy) when it is not known yet.- Functions given to codecs must have no side effects: a value may be decoded more than once (a stream decodes again a value that did not fit in its chunk, and calls
customdecoders again with more bytes). - Streamed values must take at least one byte; errors of the source are passed on as they are.
- Definitions reject unknown options, invalid lengths, duplicate field names and
__proto__. - Absent values (
optional,when) arenull, neverundefined. - Literals keep their default through
sizedandlazy; inputs ofmapandcustomcodecs are required, even if they acceptundefined.