DagrA guide to binary formats, and to Dagrdraft

8 Chapter eight

Enums and unions: one of several

Much of real data is a choice. An order is open, paid or cancelled. A message is a text, a picture or a call. This chapter is about the two ways a schema says "one of these": the enum, where the choice is all there is, and the union, where each choice brings a value of its own.

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.

A list is where it matters. One status is one byte wherever you put it. A history of ten thousand is not.

the enum:
add:

how long, how manythe cases, a few bits eachdim: bits not used

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.

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.

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:

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

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

    which variant, and how writtena length or a counta numbertextfaded: not part of what you chose

    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

    What these panels are.

    Try it

    1. With the two-case enum, add cases one at a time. After how many does the list grow by a byte?
    2. 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?
    3. Tick all four flags. Which bits of the byte are still free, and what would a fifth flag cost?
    4. Type ---5. How many bytes does each minus sign cost, and why two rather than one?
    5. Type a + b and then (a + b) + c and a + 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.