A Better UTF-8 Automaton
Without wasting your time, here it is:
Any edge not shown goes to an error state. If you can start in ACC, follow
the edges for each byte in your input and end up back in ACC, your string is
valid UTF-8.
Some C code implementing the above DFA is as follows. It highlights some of the neat features that our new automaton supports, namely quick branchless transitions as a shift-DFA, trivial parallel evaluation, and instant error recovery.
#include <stddef.h>
#include <stdint.h>
enum { DFA_ACCEPT = 2, DFA_SYNC = 16 };
static const uint32_t DFA[256] = {
[0x00 ... 0x7f] = 0xcae2bb8a, [0x80 ... 0x8f] = 0xaef05f22,
[0x90 ... 0x9f] = 0xbff05f22, [0xa0 ... 0xbf] = 0xbf905f22,
[0xc0 ... 0xc1] = 0xc6318cbb, [0xc2 ... 0xdf] = 0xcb8dc637,
[0xe0] = 0xc6565dd9, [0xe1 ... 0xec] = 0xc8c7771d,
[0xed] = 0xc63318cc, [0xee ... 0xef] = 0xc8c7771d,
[0xf0] = 0xcbbaeeeb, [0xf1 ... 0xf3] = 0xc8c97725,
[0xf4] = 0xc6546551, [0xf5 ... 0xff] = 0xc6318cbb,
};
uint32_t step(uint32_t s, uint8_t b) { return DFA[b] >> (s & 31); }
int is_error(uint32_t s) { return !((0x4459a285 >> (s & 31)) & 1); }
int partial(uint32_t s) { return (0x92283845 >> ((s + 12) & 31)) & 3; }
size_t utf8_valid_up_to(const uint8_t *buf, size_t len) {
uint32_t s = DFA_ACCEPT, t;
size_t i = 0;
for (; i + 32 <= len; i += 32) {
uint32_t s1 = s, s2 = DFA_SYNC;
for (int j = 0; j < 18; j++) {
s1 = step(s1, buf[i + j]);
s2 = step(s2, buf[i + j + 14]);
}
if (is_error(s1) | is_error(s2)) break;
s = s2;
}
for (; i < len && !is_error(t = step(s, buf[i])); i++) s = t;
return i - partial(s);
}
Note that a proper UTF-8 validation routine should at the very least have hot paths for ASCII, this is just an example. And while the above definitely doesn’t beat simdutf, it runs only ~2.5x slower on my Apple M5 laptop when validating Chinese, which isn’t bad for ~30 lines of scalar code. Compared to Björn Höhrmann’s minimal C UTF-8 validator, the above runs 9 times faster in the same benchmark.
State machine
Our state machine isn’t minimal, but that’s on purpose. It has three nice properties:
-
Like Per Vognsen’s shift-DFA, this state machine can be encoded so each transition is a byte lookup into an array of magic constants followed by a bit shift. Their original implementation packed the constants as
uint64_ts, this one fits them inuint32_ts through the use of a SAT solver and overlapping the constants, reducing the lookup table from 2 → 1 KiB. -
Because we do not merge states which have consumed a different number of bytes of a partial codepoint, error recovery is trivial. In case of an error we can directly read off from the state machine how many bytes we consumed, go back that much, and insert a replacement character if desired.
-
An extra
SYNCstate is added to the state machine, which absorbs continuation bytes. This makes it super easy to do parallel validation, allowing the shift-DFA to run almost twice as fast as previous shift-DFA UTF-8 validators due to instruction-level parallelism.The trick is to overlap the end of one chunk of bytes with the start of the next chunk by 4 bytes (since no valid codepoint can be > 4 bytes). The first parallel run will validate the overlap, and the second can synchronize on it. If there was an error in these four bytes the second DFA’s state will be nonsense, but the first will catch the error safely.
Shift-DFA
I would highly recommend reading Per Vognsen’s original shift-DFA exposition, but in short, if you have a finite automaton with a limited number of states and symbols, you can store a transition table.
It seems natural to store per state what transition to take for each symbol: $$(\mathrm{State} \times \mathrm{Symbol}) \to \mathrm{State},$$ but if you have a very small number of states it is actually more efficient to store for each symbol how each state transitions: $$\mathrm{Symbol} \to (\mathrm{State} \to \mathrm{State}).$$ This is for two reasons:
-
The memory lookups can all be done in parallel, off the critical dependency chain, as each lookup only depends on its symbol, not the previous state.
-
All the information needed for a $\mathrm{State} \to \mathrm{State}$ function can be stored in one register (naive encoding is $n \cdot \lceil \log_2 n \rceil$ bits for $n$ states).
If you choose your state indices cleverly, doing a state transition can even be a single operation after the lookup, e.g. for at most 32 states:
state = table[symbol] >> (state % 32)On most hardware shift counts automatically wrap around, making the mod free, as long as it’s 32 or 64.
I’m not clever enough, so a SAT solver was used to pack the shift-DFA transition
table into uint32_t magic constants. It is somewhat surprising this fit at
all, since we have thirteen states, meaning we need 4 bits to encode a
transition target, and ${13 \times 4 = 52}$ bits to store it naively. Worse
still, since we want to target uint32_t magic constants, our natural modulo is
32, meaning five bits define a state. Luckily we can overlap the bits of
neighboring states, if the start of one matches the end of another.
To make it fit I still had to be a bit creative: there isn’t a single error state. Instead, we have 32 possible states, of which 12 are valid and 20 are invalid. The only requirement on the invalid states is that they remain invalid on every transition. Luckily checking if a state is valid can still be done with just one shift into a bit vector.
What follows is the Z3 code to find our magic DFA constants, it runs in ~15 minutes on my machine.
from z3 import *
STATES = 'ACC SYNC 1/2 1/3 2/3 1/4 2/4 3/4 E0 ED F0 F4'.split()
CONT = {'SYNC': 'SYNC', '1/2': 'ACC', '1/3': '2/3', '2/3': 'ACC',
'1/4': '2/4', '2/4': '3/4', '3/4': 'ACC'}
CLASSES = {
'00-7f': {'ACC': 'ACC', 'SYNC': 'ACC'},
'80-8f': {**CONT, 'ED': '2/3', 'F4': '2/4'},
'90-9f': {**CONT, 'ED': '2/3', 'F0': '2/4'},
'a0-bf': {**CONT, 'E0': '2/3', 'F0': '2/4'},
'c0-c1 f5-ff': {},
'c2-df': {'ACC': '1/2', 'SYNC': '1/2'},
'e0': {'ACC': 'E0', 'SYNC': 'E0'},
'e1-ec ee-ef': {'ACC': '1/3', 'SYNC': '1/3'},
'ed': {'ACC': 'ED', 'SYNC': 'ED'},
'f0': {'ACC': 'F0', 'SYNC': 'F0'},
'f1-f3': {'ACC': '1/4', 'SYNC': '1/4'},
'f4': {'ACC': 'F4', 'SYNC': 'F4'},
}
# The offset of valid state s, and the word of class c.
off = {s: BitVec(s, 32) for s in STATES}
word = {c: BitVec(c, 32) for c in CLASSES}
valid = lambda x: Or([x == o for o in off.values()])
# Each state has a unique offset below 32.
solver = Solver()
solver.add(*[ULT(o, 32) for o in off.values()])
solver.add(Distinct(*off.values()))
for c, trans in CLASSES.items():
step = lambda o: LShR(word[c], o) & 31
# State s should go to its target state or error.
for s in STATES:
if s in trans:
solver.add(step(off[s]) == off[trans[s]])
else:
solver.add(Not(valid(step(off[s]))))
# Error states only transition to error states.
for e in range(32):
e = BitVecVal(e, 32)
solver.add(Or(valid(e), Not(valid(step(e)))))
solver.check()
model = solver.model()
for s in STATES:
print(s, model[off[s]])
for c in CLASSES:
print(c, f'{model[word[c]].as_long():08x}')Acknowledgements
I’d like to thank Thom Chiovoloni for their discussions and their earlier work on packing the lookup tables using Z3, and Max Hollmann for bringing shift-DFA UTF-8 validation to my attention at RustWeek 2026 and exchanging further thoughts.