An enum: a name for a small number
A status that is one of three things could be stored as text, "notFound", at ten bytes a time. It could be stored as an ordinary number, and then every program has to remember that 1 means "not found". An enum is the schema taking over that memory: the cases have names in your code and small numbers in the bytes.
Enum("Status", ["ok", "notFound", "teapot"])
Every binary format with a schema has these. They differ in how much room a case takes.
- Protocol Buffers writes the case number as a varint, so one byte for the first 128 cases.
- FlatBuffers lets you pick the integer type, usually a byte.
- Cap'n Proto always takes two bytes.
- Dagr takes one byte in a record, and looks at how many cases there are before deciding what a list of them takes.
A list is where it matters. One status is one byte wherever you put it. A history of ten thousand is not.
- Two cases need one bit, so eight of them share a byte. Up to four cases need two bits, up to sixteen need four. Beyond that a case takes a byte, as elsewhere.
- The schema decides, the data does not. The width follows from the number of cases the enum has, so a reader knows it without looking.
- Nothing changes for the program. It sees a list of statuses. The generated code does the shifting.
Other formats can reach the same size if you give up the enum and pack the bits by hand. The point here is that you do not have to.
Room to grow
Three cases fit in two bits, and two bits have room for four. Dagr calls that room the enum's capacity, and uses the spare part of it.
- A case added later is not a break. A program built from the old schema that meets the new fourth case does not fail and does not guess. It gets a value that says "a case I do not know, number 3", and can pass it on unchanged.
- A value beyond the capacity is an error. It cannot be a newer case, so the data is damaged or belongs to another schema.
- You can ask for more room than you need, with
capacity=16for an enum that has three cases today. The price is known in advance: four bits in a list where two would have done. - The capacity itself cannot change later. It decides the width, and old data was written with the old width.
Cases that carry a constant
Often the cases of an enum stand for something from outside: an HTTP status is 200, 404 or 418, and those are the numbers people know. Storing 404 takes two bytes. Dagr lets a case carry a constant that is written in the schema and nowhere else.
Enum("Status", ["ok", "notFound", "teapot"], values=[200, 404, 418])
The bytes still hold 0, 1 or 2, in two bits. The generated code holds a small table, and asking a case for its value looks it up. In the panel above, choose Status: the line under the bars shows what the program reads back.
- The constant costs nothing in the data, however large it is. It can be a number, a text, or a whole record with several fields: a planet with its radius and its mass.
- All cases carry the same kind of value. That is the only rule.
- It is fixed when the code is generated. If the values must differ from one piece of data to the next, they are data and this is the wrong tool. That is what a union is for.
Several at once: flags
Sometimes the choice is not one of the cases but any number of them. A contact can be family and a colleague. For that an enum can be declared as a set of flags, and each case becomes one bit.
Enum("Label", ["family", "friend", "colleague", "vip"], as_bitset=True)
This is the oldest trick in binary data. What the schema adds is the names, and code in each language that uses that language's own idea of a set of options.
A union: one of several, each with its own value
An enum answers "which one?". Often the next question is "and what goes with it?". A length is in centimetres or in inches, and either way there is a number. A cell of a spreadsheet holds a whole number, a number with a fraction, a text or a yes/no.
UnionType("Cell", types=[
("whole", t.i64),
("real", t.f64),
("text", t.utf8),
("flag", t.bool),
])
A value of this type is exactly one of the four, and the bytes must say which. In a packed node Dagr writes a union as two things:
- a header: the number of the variant, and with it a small code that says how the value is written: as LEB128, in one, two, four or eight plain bytes, as a float in a short form, or with a length in front;
- the value, written as that kind of value would be written anywhere else.
The code looks like a detail and is the reason unions can change over time. A reader that meets a variant it has never heard of still knows how many bytes to step over. It reports "something I do not know" and carries on with the rest. Like an enum, a union declares a capacity, the number of variants it has room for, and can grow up to it.
A variant can be nearly anything the schema language has: a number, a text, an enum, a record, a list, another union.
The same idea elsewhere
- JSON has no unions, and so everyone makes their own: an object with a
"type"field, and a reader that looks at it first. - Protocol Buffers has
oneof: a group of fields in a message of which at most one is set. - FlatBuffers has unions of tables, stored as a type byte and a pointer.
- Cap'n Proto has unions inside a struct, with a 16-bit mark that says which member is in use.
In Protocol Buffers and Cap'n Proto a union lives inside a record. In Dagr it is a type of its own, which can be a field, an element of a list, or a variant of another union, whatever its variants hold. The next chapter depends on that.
A union that contains itself
A variant may be the union it belongs to. That sounds like a trick and is the ordinary way to describe anything that nests. Take arithmetic: an expression is a number, or a name, or the negative of an expression, or a sum of expressions.
UnionType("Expr", types=[
("num", t.i32),
("name", t.utf8),
("neg", t.ref("Expr")),
("sum", t.ref("Expr").array),
])
Four lines describe every expression of this kind, of any size. Type one.
What it is
- Choose a line on the left and its bytes stay lit. A part of the expression is a run of bytes, and its parts are runs inside that run.
- Everything that nests says how long it is. So a reader that only wants the last term of a sum steps over the others without understanding them.
- A sum lists what its terms are before the terms themselves: first all the headers, then all the values. The next chapter is about that arrangement.
- The format has no rule about depth, and readers do. Data can nest a million levels deep in very few bytes, and a reader that follows it blindly runs out of memory. Dagr's readers that walk into data stop at 128 levels and report an error.
A recursive union is still a tree, written in place. If two parts of an expression should be the same object, or something should point back at what contains it, the variants hold records, and those are shared and linked as chapter 4 described.
What this costs
- A union is the slowest thing to read in a schema. A field of a known type is read by code that was generated for that type. A union needs a look at the header and a decision, every time.
- Each value pays for its header, a byte in most cases. A million numbers in a list of unions cost a million bytes more than a million numbers in a list of numbers.
- A schema made mostly of unions says little. The more of the shape you leave open, the more of the work moves from the schema to the reader. Chapter 10 takes that to its end.
What these panels are.
- The bytes are Dagr's. Each panel shows a field of a packed node, without the tag in front of it. The same encoder is checked against Dagr's reference writer.
- The first panel compares with a count. "A byte each" and the JSON line are sizes the page works out, to give the bits something to stand next to.
- The expression panel accepts little: whole numbers, names, plus, minus and brackets. It is a picture of nesting and no calculator.
Try it
- With the two-case enum, add cases one at a time. After how many does the list grow by a byte?
- With Status, make a list of eight. How many bytes hold the cases? How many bytes would the numbers 200, 404 and 418 have needed as LEB128?
- Tick all four flags. Which bits of the byte are still free, and what would a fifth flag cost?
- Type
---5. How many bytes does each minus sign cost, and why two rather than one? - Type
a + band then(a + b) + canda + b + c. The last two mean the same. Which is smaller, and what did the brackets cost?
What comes next
Enums took a few bits each once they stood in a list, and a sum wrote its headers apart from its values. Both are cases of one idea: a list is more than its elements one after another. Chapter 9 is about lists, including lists with gaps in them and lists whose elements are not all of one kind.
