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.
Scalar validator with every range from table 3-7Jul 20
1; utf8_scalar.asm: the reference. One byte at a time, every range spelled out.
2;
3; int utf8_valid_scalar(const uint8_t *buf, size_t len); 1 = valid, 0 = not
4;
5; Unicode 15, table 3-7 (well-formed byte sequences):
6; 00..7F
7; C2..DF 80..BF
8; E0 A0..BF 80..BF
9; E1..EC 80..BF 80..BF
10; ED 80..9F 80..BF
11; EE..EF 80..BF 80..BF
12; F0 90..BF 80..BF 80..BF
13; F1..F3 80..BF 80..BF 80..BF
14; F4 80..8F 80..BF 80..BF
15;
Fuzz the AVX2 version against the scalar oneAug 5
16; The AVX2 version is fuzzed against this one on every build.
18 default rel
19 bits 64
22 %define ARG0 rcx
23 %define ARG1 rdx
24%else
25 %define ARG0 rdi
26 %define ARG1 rsi
27%endif
30 global utf8_valid_scalar
32utf8_valid_scalar:
34 mov r9, ARG1
36.next: cmp r8, r9
38 movzx eax, byte [r8]
39 inc r8
40 cmp al, 0x80
42 cmp al, 0xC2
44 cmp al, 0xE0
46 cmp al, 0xF0
48 cmp al, 0xF5
52.two: cmp r8, r9
54 movzx ecx, byte [r8]
55 and ecx, 0xC0
56 cmp ecx, 0x80
58 inc r8
61.three: lea rcx, [r8 + 2]
62 cmp rcx, r9
64 mov edx, 0x80 ; second byte: low bound
65 mov r10d, 0xBF ; high bound
66 cmp al, 0xE0
68 mov edx, 0xA0 ; E0: no overlongs
69.t1: cmp al, 0xED
71 mov r10d, 0x9F ; ED: no surrogates
72.t2: movzx ecx, byte [r8]
73 cmp ecx, edx
75 cmp ecx, r10d
77 movzx ecx, byte [r8 + 1]
78 and ecx, 0xC0
79 cmp ecx, 0x80
81 add r8, 2
84.four: lea rcx, [r8 + 3]
85 cmp rcx, r9
87 mov edx, 0x80
88 mov r10d, 0xBF
89 cmp al, 0xF0
91 mov edx, 0x90 ; F0: no overlongs
92.f1: cmp al, 0xF4
94 mov r10d, 0x8F ; F4: nothing past U+10FFFF
95.f2: movzx ecx, byte [r8]
96 cmp ecx, edx
98 cmp ecx, r10d
100 movzx ecx, byte [r8 + 1]
101 and ecx, 0xC0
102 cmp ecx, 0x80
104 movzx ecx, byte [r8 + 2]
105 and ecx, 0xC0
106 cmp ecx, 0x80
108 add r8, 3
111.valid: mov eax, 1
112 ret
113.invalid:
114 xor eax, eax
115 ret