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.
- Reading is as cheap as it gets. One load from memory, no decisions.
- A position can be computed. If every element of a list is four bytes, element 1000 is at byte 4000. That is what makes a list you can index.
- Small numbers waste space. Most numbers in real data are small: counts, ages, lengths, ids that started at 1. In a
u64, the number 5 is one useful byte and seven zeros. Try it above.
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.
| code | bytes | bits for the number | largest number |
|---|---|---|---|
00 | 1 | 6 | 63 |
01 | 2 | 14 | 16,383 |
10 | 4 | 30 | 1,073,741,823 |
11 | 8 | 62 | about 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.
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:
- For small numbers the two are nearly the same. V62 has one bit less in its first byte, so 64 to 127 cost it a second byte.
- V62 has no sizes of 3, 5, 6 or 7 bytes. A number that needs 15 bits takes four bytes where LEB128 takes three. In the middle of the range V62 is the larger one, sometimes by a lot: try
2^30. - At the top V62 wins again. LEB128 spends a bit in every byte, so a large number costs it nine or ten bytes. V62 stops at eight.
- V62 cannot write everything. A number of 262 or more does not fit. For a distance inside a buffer that is no limit in practice. For arbitrary 64-bit values it would be, and Dagr does not use V62 for those.
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.
- One look, one load. Two bits give the whole length. The widths are the widths a processor reads natively, so the rest is a single load and a shift. Following a chain of pointers through a buffer does this constantly.
- It can be skipped without being read. A reader that wants the field after this one needs only the first byte to step over it.
- It can be written wider than it needs to be. A V62 holding 5 is normally one byte, but it is just as valid as four bytes with code
10. So a writer can leave a slot of a known width, carry on, and fill the number in later. That is how Dagr writes a graph with a cycle in it, where a node must point at something that has not been placed yet. Chapter 4 comes back to this.
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.
| scheme | good at | Dagr uses it for |
|---|---|---|
| fixed width | being read in place, being indexed | numbers in the layouts built for fast access, and lists of numbers |
| LEB128 | being small | lengths, counts, labels, and numbers in the layouts built for size |
| V62 | being followed and being filled in later | pointers 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:
- a sign, one bit;
- an exponent, which says how large the number is, as a power of two;
- a fraction, the digits of the number, in binary.
Type a number below. The first row is the number as a processor holds it.
- Most decimal fractions are not exact. Type
0.1. One tenth has no finite form in base two, just as one third has none in base ten, so the nearest number that does fit is stored. The panel shows which one. With 64 bits the nearest number is much nearer. - The bits have no leading zeros to drop. A small whole number such as 5 is mostly zero bytes. The number 5.0 is not: its exponent and fraction fill the high bits. LEB128 would gain nothing here.
- There are special values: two zeros (try
-0), two infinities (inf,-inf) and "not a number" (nan), which is what dividing zero by zero gives.
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 is | it is written as | try |
|---|---|---|
| zero, an infinity, or not a number | one byte | 0, inf |
| a whole number that is not too large | that whole number: ZigZag, then LEB128 | 21, -300 |
| exactly a 16-bit float | those two bytes | 21.5, 0.25 |
an f64 that is exactly a 32-bit float | those four bytes | 100000.5 as f64 |
| anything else | its own bytes, unchanged | 0.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.
| type | exponent | fraction | what that means |
|---|---|---|---|
f16 | 5 bits | 10 bits | about three decimal digits, and nothing beyond 65504 |
bf16 | 8 bits | 7 bits | about two decimal digits, and the whole range of an f32 |
f16is the half-precision float of IEEE 754. It spends its bits on precision and has little range: 100000 does not fit and becomes infinity.bf16is the upper half of anf32: the same sign and exponent, and the fraction rounded to its first seven bits. It keeps the range and gives up precision. Turning one back into anf32is appending two zero bytes, which is why hardware built for machine learning likes it.- Unlike the short forms above, these lose something. That is why they are types you choose in the schema, and never something Dagr does on its own.
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.
- Each element in its shortest form. This is the default. Every element is written like a single float, with one difference: there is no field label to carry the "plain bytes" mark, so an element that has no short form costs its own bytes and one more. Zeros and tidy numbers make the list small. Untidy ones make it one byte per element larger than it had to be.
- Plain bytes. Mark the field
rawin the schema and every element is its four or eight bytes. Nothing is saved on a zero and nothing is added to a measurement. The elements all have the same size, so the hundredth is found by multiplying, and the whole list can be copied in one go. - The list says which it is. The mode is written next to the count, so a reader needs no schema to tell them apart, and a schema may change its mind later without breaking old data.
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.
- Plain English text is one byte a character, and is byte for byte the same as ASCII.
- You can start reading anywhere. A byte beginning with
10is the middle of a character, so a reader dropped at a random position can find the next start. LEB128 has no such property. - The number of bytes is not the number of characters. The panel counts both. A format has to pick one to store, and storing the byte count is the useful one: it tells the reader how far to jump.
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
- 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? - Find the smallest number that LEB128 writes in three bytes, and the smallest that V62 writes in four. Which comes first?
- Find a number where V62 is exactly twice the size of LEB128. Then find one where it is smaller.
- 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. - In the list panel, find the shortest list for which plain bytes are smaller. Then make a list of twenty zeros and compare.
- Type
0.1asf32,f16andbf16. Which is nearest, and which is furthest? - Type
16777217as anf32. What is stored, and why can a float not hold every whole number its size suggests? - 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.
