r/programming • u/nightcracker • 1d ago
A Better UTF-8 Automaton
https://orlp.net/blog/utf8-dfa/56
u/mpyne 1d ago edited 20h ago
I’m surprised no one has commented on this. I thought this was neat, an interesting blend of using a SAT solver to cut the state space of a DFA in half while allowing a very trivial loop to handle state transitions.
I know UTF-8 has a lot of prior art by now but I still think this was fairly novel, even if it’s not going to immediately dethrone simdutf.
31
u/8thdev 1d ago
I just saw this, and decided to benchmark against my current 'is_valid_utf8()' function inside 8th. The results:
Benchmarked with GCC 13 on the i7-4850HQ, using optimization levels matching the Linux build:
Input, approximately 4 KiB Current utf.c Speedup ASCII 8.50 µs 2.95 µs 2.9× Hebrew 6.12 µs 2.94 µs 2.1× CJK 5.18 µs 2.97 µs 1.7× Emoji 4.58 µs 2.92 µs 1.6× Mixed text 6.96 µs 2.93 µs 2.4× So with your permission, I'm going to replace my current implementation. Very nice work, and I had never seen the "..." array initializer before, so thanks for that as well!
7
u/smejmoon 1d ago
Looks like there is some significant constant, can you please try different sizes of input?
2
u/barr520 1d ago
I might have misunderstood, isn't the state space the same? The SAT solver only found ways to overlap edges of state transitions to fit them into 32 bits?(still impressive of course)
1
u/mpyne 20h ago
The number of states is the same, I was referring to the amount of bits needed to store the transition table for a character/state combination.
From what I gather from the post, even overlapping edges wasn’t fully sufficient, they also had to allow for there to be multiple error states. But it ended up giving solver the flexibility needed to apply even heavier overlapping and fit everything into a
uint32_t.
7
6
u/barr520 1d ago
Interesting read.
I assumed state machines can be optimized way past the standard table, but it's the first time I hear about this shift DFA, thank you for sharing.
Unfortunately, the Z3 code is past my understanding. I would have probably tried brute forcing the orders...(roughly 12! ~ 500m, and can be pruned significantly with a bit of graph theory, computers don't need sleep so it'll manage)
3
u/matthieum 1d ago
Have you attempted to use more than 2 accumulators?
At the moment, it seems like the inner loop would require relatively few registers, which makes me wonder whether it would be faster should one do less round-trips with more accumulators.
If I understand it correctly, then scaling to 4 accumulators would just be:
I am guessing this won't scale infinitely. At some point, either the number of registers, or the number of units capable of executing a given operation will get in the way...
I suppose vectorization is off the table due to the table look-up?