r/cpp • u/User_Deprecated • Sep 30 '26
Transcoding UTF-8 to UTF-16 with replacement at gigabytes per second
https://lemire.me/blog/2026/09/30/transcoding-utf-8-to-utf-16-with-replacement-at-gigabytes-per-second/
74
Upvotes
View all comments
Show parent comment
6
u/ack_error Oct 02 '26
Kind of, in that you do logic expressions as logical ops on masks instead of branching. Though there are some tricks like using swizzle/table lookups, or abusing psadbw for horizontal adds.
The hard part is variable length input or output, as most SIMD ISAs don't have good support for compress/expand operations. AVX-512 does, and I believe SVE does too. Doing so at lower ISA levels typically involves large shuffle tables.
Hybrid vector/scalar techniques can be useful, where you build a vector mask and move it over to the scalar side with pmovmskb or vqrshrn. Then you can iterate over the bitmask with clz or lzcnt, count with popcnt, or just compare for a fast skip when all 4/8/16 elements are a fast path. For instance, you might have a UTF-8 routine that mostly handles ASCII, so the vector side can help quickly scan for the rare multibyte cases. For a prefix matching routine in a data compressor, compare vectors at a time until a mismatch is found, move the mismatch mask to the scalar side, then count trailing zeros to find the number of matching bytes in the final vector.