moonvar integers as octets

Five encodings · five packages · no dependencies

A number, written
down as octets.

  • quic45 39
  • prefix1f 9a 0a
  • leb128b9 0a
  • lenencfc 39 05
  • fixed05 39

moonvar turns integers into bytes and reads them back the way five protocols do: the fixed widths in either byte order, and the variable-length integers of QUIC, HPACK, protobuf and MySQL. Each encoding is a package of its own, so you link the one whose wire you are speaking.

moon add moonbitstack/moonvar

One number, every encoding

Every octet below was written by this library, compiled to JavaScript and running in this tab.

quic · prefix · leb128 · lenenc · fixed reading…
5encodings, each a package
42public functions over them
0packages imported by another
10octets, the most LEB128 spends on a u64

The five

Same number, five rules

1337 below, in each encoding, from the live panel above. The difference is not style: each rule is what some wire already expects.

quic

Two bits name the width — one, two, four or eight octets — and the rest carry the value, big-endian.

1337 → 45 39

prefix

A value in the low N bits of the first octet, spilling into continuation octets when it does not fit.

1337 → 1f 9a 0a

leb128

Seven bits an octet, least significant group first, one bit in each saying whether another follows.

1337 → b9 0a

lenenc

One octet below 251; above it a marker octet and two, three or eight little-endian octets.

1337 → fc 39 05

fixed

The widths a machine has, plus the 24-bit length protocols use, in either byte order.

1337 → 05 39

While reading

Readers that answer

A parser is judged by what it does with a packet it did not expect.

Nothing read past the end

Every fixed reader checks the width it needs before indexing, and answers None when the view is short. The variable-length readers raise a Refused that names the fault: truncated, or past the ceiling.

A width without writing it

Each package has size(): how many octets a value takes, without producing them. A length field has to be measured before the payload it describes is written.

One package, one wire

No package imports another. Wanting protobuf's varint does not pull in QUIC's, and a reader that needs one encoding does not carry four.

Where to go

Take the next step