acompiled

The catalog contains seeded project examples. Your workspace stores your own projects and conversations.

tsvet/utf8-check

Public
Star9

UTF-8 validation in x86-64: a scalar reference and an AVX2 version that checks 32 bytes per step. Every build fuzzes one against the other.

Code
Blame·3 commits across 25 linesoldernewer
2
AVX2: three nibble tables and a saturating subtractAug 4 3UTF-8 validation in x86-64 assembly: a byte-at-a-time reference, and an AVX2 version that checks 32 bytes per step.
5```c
6int utf8_valid_scalar(const uint8_t *buf, size_t len); // 1 = valid, 0 = not
AVX2: three nibble tables and a saturating subtractAug 4 7int utf8_valid_avx2(const uint8_t *buf, size_t len);
9
README for 1.0: what every build proves, and how the AVX2 version worksOct 8 10Both assemble for Windows x64 (`nasm -f win64`) and System V (`nasm -f elf64`). The AVX2 version is a leaf that touches only volatile registers. It pads its last partial block in the caller's shadow space on Windows and in the red zone on System V, so it has no stack frame and needs no unwind data.
11
12## Evidence
13
14Every build runs both of these, and its log has the numbers:
15
16- `test/test.c` tries 27 samples from the edges of Unicode table 3-7 at 64 offsets each, so every one also straddles a block boundary. Then it fuzzes: 1,000,000 inputs of random well-formed text, half of them damaged by a flipped bit, a cut-off end or an overwritten byte, with the scalar version as the oracle.
17- `bench/bench.c` times both validators on 64 MiB of ASCII and 64 MiB of mixed 1- to 4-byte text, best of five runs.
19## How the AVX2 version works
20
README for 1.0: what every build proves, and how the AVX2 version worksOct 8 21Three 16-entry tables, indexed by the high and low nibbles of each byte's predecessor and by its own high nibble, give a bitmask of the errors that pair of bytes could be part of. ANDing the three leaves only the errors that actually happen. A saturating subtract of `0xE0 - 0x80` from the byte two back and `0xF0 - 0x80` from the byte three back marks where the third or fourth byte of a sequence must be, and an XOR with the tables' answer catches continuations that are missing or extra. A block that ends inside a sequence is only allowed if the next block finishes it.
22
23Blocks with no byte above 0x7F skip all of that: the only way they can fail is if the block before them ended mid-sequence.
25The algorithm is Keiser and Lemire's, *Validating UTF-8 In Less Than One Instruction Per Byte* (2021).