A faster UTF-8 validator built on a shift-DFA state machine
The author describes a new state machine for checking whether a byte string is valid UTF-8. It is encoded as a shift-DFA[1], where each transition is a byte lookup into an array of constants followed by a bit shift. The C example is about 30 lines of scalar code and has no special path for ASCII.
On an Apple M5 laptop validating Chinese text, the example runs about 2.5 times slower than simdutf and about 9 times faster than Björn Höhrmann's minimal C validator. The lookup table is reduced from 2 to 1 KiB by fitting the constants into uint32_t values with a SAT solver[2].
States are not merged when they have consumed different numbers of bytes of a partial codepoint, so error recovery means reading how many bytes were consumed, going back that far and inserting a replacement character if wanted. An extra SYNC state absorbs continuation bytes, which allows parallel validation with overlapping 4-byte chunks. The author says this runs almost twice as fast as previous shift-DFA validators.
Read the original orlp.netDiscussion
Sources
-
orlp.net
A Better UTF-8 Automaton

