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 115 linesoldernewer
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
20
System V buildSep 30 21%ifidn __OUTPUT_FORMAT__, win64
22 %define ARG0 rcx
23 %define ARG1 rdx
24%else
25 %define ARG0 rdi
26 %define ARG1 rsi
27%endif
28
31
32utf8_valid_scalar:
System V buildSep 30 33 mov r8, ARG0 ; cursor
34 mov r9, ARG1
36.next: cmp r8, r9
37 jae .valid
38 movzx eax, byte [r8]
39 inc r8
40 cmp al, 0x80
41 jb .next ; ASCII
42 cmp al, 0xC2
43 jb .invalid ; stray continuation, or overlong C0/C1
44 cmp al, 0xE0
45 jb .two
46 cmp al, 0xF0
47 jb .three
48 cmp al, 0xF5
49 jb .four
50 jmp .invalid
51
52.two: cmp r8, r9
53 jae .invalid
54 movzx ecx, byte [r8]
55 and ecx, 0xC0
56 cmp ecx, 0x80
57 jne .invalid
58 inc r8
59 jmp .next
60
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
67 jne .t1
68 mov edx, 0xA0 ; E0: no overlongs
69.t1: cmp al, 0xED
70 jne .t2
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
80 jne .invalid
81 add r8, 2
82 jmp .next
83
84.four: lea rcx, [r8 + 3]
85 cmp rcx, r9
87 mov edx, 0x80
88 mov r10d, 0xBF
89 cmp al, 0xF0
90 jne .f1
91 mov edx, 0x90 ; F0: no overlongs
92.f1: cmp al, 0xF4
93 jne .f2
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
109 jmp .next
110
111.valid: mov eax, 1
112 ret
113.invalid:
114 xor eax, eax
115 ret