A Better UTF-8 Automaton
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
A Better UTF-8 Automaton 2026-11-29 更好的 UTF-8 自动机 2026-11-29
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. 长话短说,直接上干货:任何未显示的边都指向错误状态。如果你能从 ACC 状态开始,根据输入中的每个字节沿着边跳转,并最终回到 ACC 状态,那么你的字符串就是有效的 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. 以下是实现上述 DFA 的部分 C 代码。它突出了我们新自动机支持的一些巧妙特性,即作为移位 DFA(shift-DFA)的快速无分支转换、简单的并行评估以及即时错误恢复。
#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. 请注意,一个规范的 UTF-8 验证程序至少应该包含针对 ASCII 的热路径,这仅仅是一个示例。虽然上述代码肯定比不上 simdutf,但在我的 Apple M5 笔记本电脑上验证中文时,它仅慢了约 2.5 倍,对于约 30 行标量代码来说,这已经相当不错了。与 Björn Höhrmann 的极简 C 语言 UTF-8 验证器相比,上述代码在同一基准测试中运行速度快了 9 倍。
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 in uint32_ts through the use of a SAT solver and overlapping the constants, reducing the lookup table from 2 → 1 KiB. 我们的状态机并非最小化,但这是有意为之的。它具有三个优良特性:像 Per Vognsen 的移位 DFA 一样,该状态机可以被编码,使得每次转换都表现为对魔数常量数组的字节查找,随后进行位移操作。他们的原始实现将常量打包为 uint64_t,而本实现通过使用 SAT 求解器并重叠常量,将其适配到 uint32_t 中,从而将查找表从 2 KiB 减小到 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 SYNC state 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. 状态机中增加了一个额外的 SYNC 状态,用于吸收后续字节。这使得并行验证变得非常容易,得益于指令级并行,该移位 DFA 的运行速度几乎是之前移位 DFA UTF-8 验证器的两倍。诀窍是将一个字节块的末尾与下一个字节块的开头重叠 4 个字节(因为没有任何有效码点会超过 4 个字节)。第一次并行运行将验证重叠部分,第二次运行则可以在此基础上进行同步。如果这四个字节中存在错误,第二个 DFA 的状态将变得毫无意义,但第一个 DFA 将安全地捕获该错误。
Shift-DFA 移位 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})$. 我强烈建议阅读 Per Vognsen 关于移位 DFA 的原始论述,简而言之,如果你有一个状态和符号数量有限的有限自动机,你可以存储一个转换表。按状态存储每个符号的转换似乎很自然:$(\mathrm{State} \times \mathrm{Symbol}) \to \mathrm{State}$,但如果状态数量非常少,按符号存储每个状态的转换实际上更有效:$\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.
原因有二:内存查找可以全部并行完成,脱离关键依赖链,因为每次查找仅依赖于其符号,而不依赖于前一个状态。$\mathrm{State} \to \mathrm{State}$ 函数所需的所有信息都可以存储在一个寄存器中(对于 $n$ 个状态,朴素编码需要 $n \cdot \lceil \log_2 n \rceil$ 位)。如果你巧妙地选择状态索引,状态转换甚至可以在查找后通过单次操作完成,例如对于最多 32 个状态:state = table[symbol] >> (state % 32)。在大多数硬件上,移位计数会自动回绕,只要是 32 或 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. 我没那么聪明,所以使用了一个 SAT 求解器将移位 DFA 转换表打包成 uint32_t 魔数常量。令人惊讶的是它竟然能装下,因为我们有 13 个状态,这意味着我们需要 4 位来编码一个转换目标,朴素存储需要 $13 \times 4 = 52$ 位。更糟糕的是,由于我们的目标是 uint32_t 魔数常量,自然的模数是 32,这意味着需要 5 位来定义一个状态。幸运的是,如果一个状态的开头与另一个状态的结尾匹配,我们可以重叠相邻状态的位。为了使其适配,我不得不发挥一点创造力:这里没有单一的错误状态。相反,我们有 32 个可能的状态,其中 12 个是有效的,20 个是无效的。对无效状态的唯一要求是它们在每次转换时都保持无效。幸运的是,检查状态是否有效仍然可以通过对位向量进行一次移位来完成。
What follows is the Z3 code to find our magic DFA constants, it runs in ~15 minutes on my machine. 以下是用于寻找我们魔数 DFA 常量的 Z3 代码,在我的机器上运行大约需要 15 分钟。