hn.today

A Better UTF-8 Automaton

orlp.net9 points0 comments
Screenshot of A Better UTF-8 Automaton

A compact UTF-8 validator is presented as a finite-state automaton: start in an accepting state, process each byte, and accept only if the final state is accepting; unshown transitions signal invalid input. Its design tracks ordinary continuation-byte sequences as well as special cases needed to reject overlong encodings, surrogate code points, and values above Unicode’s maximum. It also distinguishes an accepting boundary from a synchronization state, allowing validation to resume at a known byte boundary after an error. The accompanying C implementation uses these states to report the first invalid position and identify incomplete trailing sequences.

The main optimization is a shift-DFA, which stores each byte’s state-transition function in a 32-bit constant. A transition then requires a table lookup followed by a shift, avoiding a serial lookup whose address depends on the previous state. This arrangement supports branchless processing and parallel evaluation of separate input blocks, with overlapping bytes used to check boundaries and synchronize the later block. Packing the automaton is nontrivial: although it has 13 meaningful states, the constants must encode transitions across 32 possible state indices. A Z3 solver finds a workable layout, using 12 valid states and 20 invalid states that remain invalid under every transition. The design therefore combines fast transitions, parallelizable validation, and error recovery in a small representation.

Read on orlp.net0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.