DagrA guide to binary formats, and to Dagrdraft

2 Chapter two

Numbers and text

Every binary format is built from two small decisions made over and over: how to write a number, and how to write a piece of text. This chapter shows the usual answers, bit by bit, and two less usual ones: the number Dagr uses for its pointers, and what it does with numbers that have a fraction.

A number of a fixed width

The simplest way to write a number is to decide in advance how many bytes it gets. A u8 is one byte and holds 0 to 255. A u16 is two, a u32 four, a u64 eight. The reader needs no instructions: it knows the width, takes that many bytes, and has the number.

There is one choice left, the order of the bytes. Nearly every processor in use today keeps the lowest byte first, which is called little-endian, and so do Dagr and most recent formats. Network protocols traditionally send the highest byte first.

A number as long as it needs to be

The other way is to let the number say how long it is. The best-known scheme is LEB128, the "varint" of Protocol Buffers, WebAssembly and DWARF. It cuts the number into groups of seven bits, lowest group first, and puts each group in a byte. The eighth bit of each byte is not part of the number. It is a signal to the reader: 1 means another byte follows, 0 means this is the last.

Numbers up to 127 take one byte, up to 16,383 two, and so on. The price is paid by the reader, which cannot know where the number ends without looking at every byte of it:

def read_leb(buf, at):
    value, shift = 0, 0
    while True:
        byte = buf[at]
        value |= (byte & 0x7F) << shift
        at, shift = at + 1, shift + 7
        if byte < 0x80:              # top bit clear: the last byte
            return value, at

That loop is short, but it has a branch per byte that depends on the data, and processors are slow at exactly that when the lengths vary.

Negative numbers: ZigZag

Put -1 in the panel. A negative number in a computer has all its high bits set, so the scheme that drops leading zeros finds none to drop, and the smallest negative number becomes the longest thing you can write: ten bytes.

ZigZag is the usual repair. Before writing, fold the number line so that small numbers of either sign come first: 0, -1, 1, -2, 2 become 0, 1, 2, 3, 4. Tick the box and -1 is one byte again. The reader unfolds after reading.

V62: say the length first

LEB128 spreads the length over every byte of the number. Dagr's pointers use a different scheme, which it calls V62, that says the length once, at the start.

A V62 is 1, 2, 4 or 8 bytes. The two lowest bits of the first byte are a code for which, and all the remaining bits are the number.

codebytesbits for the numberlargest number
001663
0121416,383
104301,073,741,823
11862about 4.6 billion billion

The name is the last row: 62 bits is all a V62 can carry. To write one, shift the number left by two, put the code in the gap, and store the result as an ordinary little-endian integer of that width. Reading is the same in reverse, and there is no loop:

def read_v62(buf, at):
    width = 1 << (buf[at] & 3)       # 1, 2, 4 or 8, from two bits
    word = int.from_bytes(buf[at:at + width], "little")
    return word >> 2, at + width

Here are the three schemes side by side. Below the bytes, the chart shows how many bytes LEB128 and V62 each need as the number grows; the dotted line is the number you typed.

fixed u64always 8 bytes
LEB128a bit in every byte
V62two bits in the first

The bits are drawn highest first inside each byte, so the V62 code sits at the right-hand end of the first byte. What the panel shows:

Why bother, then?

If V62 is often a little larger, what does it buy? Three things, and all three matter for a pointer more than for an ordinary value.

If you have met the variable-length integers of QUIC, this is the same family: two bits, four widths, 62 bits. QUIC keeps the two bits at the top of the first byte because it is big-endian; Dagr keeps them at the bottom because it is little-endian.

A pointer that can go backwards as well as forwards is a V62 holding a ZigZag number, the same fold as above.

Which one, where

None of the three is the right answer everywhere, so Dagr uses all of them, each where its strength counts.

schemegood atDagr uses it for
fixed widthbeing read in place, being indexednumbers in the layouts built for fast access, and lists of numbers
LEB128being smalllengths, counts, labels, and numbers in the layouts built for size
V62being followed and being filled in laterpointers from one part of a buffer to another

"The layouts built for fast access" and "the layouts built for size" are the subject of chapter 5, where you can watch the same number change its encoding as the layout changes.

Numbers with a fraction

Everything above was about whole numbers. A temperature of 21.5 or a price of 0.1 needs another kind of number, and nearly every processor and language agrees on one: the floating-point number of the IEEE 754 standard. It comes in two usual sizes, 32 bits and 64 bits, which Dagr calls f32 and f64.

A floating-point number is scientific notation in base two. Its bits are three fields:

Type a number below. The first row is the number as a processor holds it.

signexponentfraction, or the valuea byte that says which short form

How Dagr writes one

Where a layout is built for fast access, a float is simply its four or eight bytes, lowest first, as in the first row. A processor can use them as they are, and a list of them is one plain block.

Where a layout is built for size, Dagr looks for something shorter. The second row of the panel shows the result. The rule is strict: a shorter form is used only if it gives back exactly the same number, bit for bit. Nothing is ever rounded.

if the number isit is written astry
zero, an infinity, or not a numberone byte0, inf
a whole number that is not too largethat whole number: ZigZag, then LEB12821, -300
exactly a 16-bit floatthose two bytes21.5, 0.25
an f64 that is exactly a 32-bit floatthose four bytes100000.5 as f64
anything elseits own bytes, unchanged0.1, 21.37

The short forms cost one extra byte to say which of them was used. The last row costs nothing extra: there the field's tag already says "plain bytes follow", a mechanism chapter 6 explains. So a float in a packed node, Dagr's layout built for size (chapter 5), is never longer than its plain form, and often shorter.

How often depends on the data. Measurements are usually untidy and take the last row. Numbers that people chose tend to be tidy: a price of 5, a volume of 0.5, a setting left at 0.

Two smaller floats

Some data does not need the precision of 32 bits, and there is a great deal of it: the weights of a machine-learning model are the usual example. Dagr has two 16-bit floats as types of their own. Choose them in the panel above and type 21.37 or 100000.

typeexponentfractionwhat that means
f165 bits10 bitsabout three decimal digits, and nothing beyond 65504
bf168 bits7 bitsabout two decimal digits, and the whole range of an f32

In a packed node a 16-bit float is its two bytes. Only zero, the infinities and "not a number" get the one-byte form.

Lists of floats

Floats rarely come alone. A track, a signal, a row of prices: the usual case is a list. In the layouts built for fast access a list of floats is one plain block, element after element, and chapter 14 shows what can be done with such a block.

In a packed node there are two ways to write the list, and the schema chooses.

how long, how many, which waywhich form this element hasthe element

The first suits lists that are mostly empty or mostly round. The second suits coordinates, samples and embeddings, which is to say most lists of floats that are long enough to matter.

Text

Text is a list of characters, and each character is a number: its Unicode code point. A is 65, é is 233, ᛞ (the rune Dagr is named after) is 5854, and 🙂 is 128,578. So writing text is the same problem again, a list of numbers that are mostly small and occasionally large, and the answer almost everyone has settled on is UTF-8.

UTF-8 is a variable-length scheme of one to four bytes, and it says the length first, as V62 does. The top bits of the first byte tell how many bytes the character has. Every following byte starts with 10, which no first byte ever does.

Dagr writes a piece of text as its length in bytes, as a LEB128, and then the UTF-8 bytes. There is no terminating zero, so text may contain any character, and a reader can step over text it does not care about without looking inside.

What these panels are. They compute the bytes in your browser, with a little JavaScript that follows the same rules as Dagr's writers. The whole-number and text panels are small enough to check by eye. The float panels, including the 16-bit floats and the lists, are checked against Dagr's reference writer: the bytes are identical.

Try it

  1. In the first panel, write 1843 as a u8. What should a format do when a number does not fit the width its schema promised?
  2. Find the smallest number that LEB128 writes in three bytes, and the smallest that V62 writes in four. Which comes first?
  3. Find a number where V62 is exactly twice the size of LEB128. Then find one where it is smaller.
  4. In the float panel, find a number between 1 and 2 that takes three bytes in a packed node as an f32, and one that takes four.
  5. In the list panel, find the shortest list for which plain bytes are smaller. Then make a list of twenty zeros and compare.
  6. Type 0.1 as f32, f16 and bf16. Which is nearest, and which is furthest?
  7. Type 16777217 as an f32. What is stored, and why can a float not hold every whole number its size suggests?
  8. Type a family emoji such as 👨‍👩‍👧 into the text panel. How many characters does the panel count, and how many did you type?

What comes next

A number and a piece of text are values. A record is several values that belong together, and the question becomes how the reader tells them apart: by a label in front of each, or by a table that says where each one is. That is chapter 3.