Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 9 min read
Open in the interactive handbook

76ж. A prefix tree for command parsing: AT commands and a console on a tree in flash

A modem answers AT commands, a debug console answers operator commands, and in both cases the firmware solves the same problem: which of the known commands has arrived. Scanning a table with strcmp works, but compares the same beginnings ("AT+C…") again and again and first requires collecting the whole string in a buffer. A prefix tree parses the name one byte at a time straight from UART reception, looks at each character once, and the tree itself is a constant table in flash built by a generator at build time.

Basis: the generator gen.py builds the tree table for 17 AT commands, alg.c with the parser and a scan for comparison built with gcc 12.2.0 on the computer (stm-sys:1) — all commands, abbreviations, errors and the count of character comparisons. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — function sizes; the node size is fixed by _Static_assert. Work is measured by the number of character comparisons, not cycles.

Terms used in the documentation

Original Meaning
trie, prefix tree prefix tree: common beginnings of strings are stored once
left-child right-sibling "left child — right sibling": a tree in an array with two indices per node
AT command set a modem's set of AT commands: AT, AT+CSQ, AT+CREG? …
command abbreviation shortening a command to an unambiguous beginning
streaming parser parsing one character at a time, without a line buffer
generated table a table built by a program at build time
terminator character the end-of-name character: "?", "=", carriage return

In plain words. Imagine a phone book where the surnames starting with "Iv…" are gathered into one branch, and inside it are separate branches "Ivanov", "Ivashin". Reading a surname letter by letter, you choose a branch each time and never go back. A command tree works the same way: "A" arrived — go into branch "A", "T" arrived — into "AT", and by the end of the name it is already clear which command it is, or clear that there is no such command.


76ж.1 Why not a string scan

A scan with strcmp is simple, but almost all AT command names begin with "AT+C", and every comparison goes through those four characters again. A run on 17 commands: to find a command, the scan needs 41.5 character comparisons on average, 86 at worst; the tree needs 8.7 and 12. There is also a second reason: the scan needs the whole string in a buffer before parsing, while the tree takes byte after byte right in the reception handler and by the end of the name already knows the answer.

What Scan with strcmp Prefix tree
character comparisons per lookup, 17 commands 41.5 on average, 86 worst 8.7 on average, 12 worst
line buffer needed not needed, the state is 2 bytes
unknown command compare with all rejection at the first wrong character
letter case needs its own folding folding in one place

76ж.2 A tree in an array in flash

Pointers in a constant table take 4 bytes each and require relocatable addresses. Instead there are node indices in one array: each node knows its first child and its next sibling ("left child — right sibling"). Five bytes per node are enough as long as there are fewer than 256 nodes:

typedef struct {
    char ch;       /* символ на ребре к узлу */
    uint8_t child; /* первый ребёнок; 0 — нет */
    uint8_t sib;   /* следующий брат; 0 — нет */
    uint8_t id;    /* команда, которая здесь кончается; 0 — нет */
    uint8_t uniq;  /* единственная команда в поддереве; 0 — их несколько */
} trie_node_t;
_Static_assert(sizeof(trie_node_t) == 5, "узел — 5 байт без выравнивания");

All fields are bytes, so there is no alignment and a node takes exactly 5 bytes. For 17 AT commands there were 36 nodes — 180 bytes in flash:

A tree of 36 nodes: from the root through A and T branches go to "+", then to C, from which F, G, M, O, P, R, S branch off; below are the branch E with 0 and 1 and the node I; green marks the nodes where a command ends — AT, ATE0, ATE1, ATI, AT+CFUN, AT+CGMI, AT+CGMM, AT+CGMR, AT+CGSN, AT+CMGD, AT+CMGF, AT+CMGR, AT+CMGS, AT+COPS, AT+CPIN, AT+CREG, AT+CSQ

The command names themselves as strings would take 120 bytes plus 68 bytes of pointers to them — comparable. The tree's gain is not in memory but in time and in the absence of a buffer.


76ж.3 The table generator

Such a tree is not written by hand: the index of every child and sibling is easy to mix up. The table is built by a short Python program at build time — from the list of commands — and it writes the header trie_tab.h:

/* Сгенерировано gen.py — не править руками. 17 команд, 36 узлов. */
#define TRIE_NODES 36
#define TRIE_CMDS 17
static const trie_node_t TRIE[TRIE_NODES] = {
    {'\0', 1, 0, 0, 0}, /* 0 */
    {'A', 2, 0, 0, 0}, /* 1 */
    {'T', 3, 0, 1, 0}, /* 2 */

The generator orders the siblings by character and for each node computes uniq — the command number if it is the only one in the subtree. To add a command, append a line to the list and rebuild; the section's check runs the generator again and compares the header byte for byte.


76ж.4 Parsing one byte at a time

The parser state is the current node index and a character counter, two bytes. Each received character is looked up among the children of the current node:

void trie_feed(trie_state_t *s, char c)
{
    if (s->node == TRIE_FAIL)
        return;
    if (c >= 'a' && c <= 'z')
        c = (char)(c - 'a' + 'A'); /* AT-команды не различают регистр */
    for (uint8_t n = TRIE[s->node].child; n; n = TRIE[n].sib) {
        CMP_HOOK();
        if (TRIE[n].ch == c) {
            s->node = n;
            s->len++;
            return;
        }
        if (TRIE[n].ch > c)
            break; /* братья упорядочены: дальше искать бесполезно */
    }
    s->node = TRIE_FAIL;
}

The function can be called right from the receive interrupt: it does not wait, does not copy and runs in a time bounded by the number of siblings of a node — here no more than seven (the children of node "C"). When the end-of-name character arrives — "?", "=" or a carriage return — the answer is taken from the current node:

uint8_t trie_result(const trie_state_t *s, int allow_prefix)
{
    if (s->node == TRIE_FAIL || s->node == 0)
        return 0;
    if (TRIE[s->node].id)
        return TRIE[s->node].id;
    return allow_prefix ? TRIE[s->node].uniq : 0;
}

Parameters after "=" are parsed separately, already knowing the command: each has its own format, and a common parser is not needed for them.


76ж.5 The run: commands, abbreviations, errors

Each line is as it would arrive from the UART; "exact" means without abbreviations, "with abbreviation" means an unambiguous beginning is allowed:

Line exact with abbreviation comparisons in the tree scan found comparisons by scan
AT+CSQ AT+CSQ AT+CSQ 12 AT+CSQ 39
AT+CMGD=1 AT+CMGD AT+CMGD 9 AT+CMGD 86
AT+CREG? AT+CREG AT+CREG 12 AT+CREG 45
at+cops? AT+COPS AT+COPS 10 — 17
ATI ATI ATI 5 ATI 13
AT+CGM — — 7 — 84
AT+CPI — AT+CPIN 10 — 79
AT+XYZ — — 4 — 64
ATZ — — 5 — 51
AT+CMGS="123" AT+CMGS AT+CMGS 12 AT+CMGS 72

What can be seen. The tree folded lowercase letters in one place, while the scan did not find the command at+cops? — it needs its own case folding. AT+CGM is ambiguous (CGMI, CGMM, CGMR) — rejected even with abbreviations; AT+CPI is an unambiguous beginning of AT+CPIN. The unknown AT+XYZ and ATZ were rejected by the tree in 4 and 5 comparisons — at the first character that is not among the siblings — while the scan went through the whole table: 64 and 51.

Abbreviations are convenient in a console for a human and dangerous in a protocol for a machine: a command AT+CPIX was added — and AT+CPI stopped being unambiguous. For the AT protocol they are switched off.


76ж.6 A console with hints

The same tree gives a console two useful things almost for free. The first is tab completion: if the current node has a single child, its character can be typed for the operator, and if uniq is non-zero — the whole name can be completed. The second is listing the options: a walk over the subtree of the current node lists all commands with the beginning already typed. Both actions work with the same two-byte state as the parser.

For a console of a dozen words without common beginnings the tree's gain is small, and the hash index from 76д is simpler. The tree wins where commands have long common beginnings: AT commands, paths like net.wifi.ssid, SCPI commands of instruments.


76ж.7 Code and memory

What M4 M0
trie_feed, code bytes 88 80
trie_result, code bytes 36 40
linear_find, code bytes 60 64
tree table in flash, bytes 180 180

Parsing with the tree is 124 bytes of code and 180 bytes of table; the scan is 60 bytes of code, 120 bytes of strings and 68 bytes of pointers. In memory they are almost equal; the tree pays with a constant table for time, rejection at the first wrong character and working without a buffer.


76ж.8 When to choose what

Command set Choice
5–10 short words a scan with strcmp — the simplest
dozens of words without common beginnings a hash index (76д)
long common beginnings, byte-by-byte parsing from the UART a prefix tree in flash
commands are defined at run time, not at build time a hash table in RAM, not a constant tree

76ж.9 Pitfalls

The tree was edited by hand and broken. A sibling index pointed to the wrong place, and some commands became unreachable. The table is built by a generator, the check compares it with the generator's output.

The search among siblings does not stop. The generator did not order the siblings, while the parser stops the search at the first greater character — a command "disappeared". The order of siblings is part of the table format.

A command stopped being recognised after a new one was added. Abbreviations were on: AT+CPI was unambiguous until a second command starting with "AT+CPI" appeared. In a protocol for a machine — exact names only.

Lowercase letters are not recognised. Modems accept at+csq; case folding is in one place, at the parser input.

There are more than 255 nodes. The indices are bytes. The generator must check the limit and switch to uint16_t rather than silently truncate the indices.


76ж.10 Summary

Next: section 76з "Radix sort and counting sort: 8- and 16-bit keys and the memory cost" — how to sort short keys without comparisons and how much RAM has to be given up for it.

Open in the interactive handbook