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·1 commit across 107 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;
16; This is the oracle for the SIMD version to come.
17
18 default rel
19 bits 64
20
21 section .text
23
24utf8_valid_scalar:
25 mov r8, rcx ; cursor
26 mov r9, rdx
27 add r9, r8 ; end
28.next: cmp r8, r9
29 jae .valid
30 movzx eax, byte [r8]
31 inc r8
32 cmp al, 0x80
33 jb .next ; ASCII
34 cmp al, 0xC2
35 jb .invalid ; stray continuation, or overlong C0/C1
36 cmp al, 0xE0
37 jb .two
38 cmp al, 0xF0
39 jb .three
40 cmp al, 0xF5
41 jb .four
42 jmp .invalid
43
44.two: cmp r8, r9
45 jae .invalid
46 movzx ecx, byte [r8]
47 and ecx, 0xC0
48 cmp ecx, 0x80
49 jne .invalid
50 inc r8
51 jmp .next
52
53.three: lea rcx, [r8 + 2]
54 cmp rcx, r9
56 mov edx, 0x80 ; second byte: low bound
57 mov r10d, 0xBF ; high bound
58 cmp al, 0xE0
59 jne .t1
60 mov edx, 0xA0 ; E0: no overlongs
61.t1: cmp al, 0xED
62 jne .t2
63 mov r10d, 0x9F ; ED: no surrogates
64.t2: movzx ecx, byte [r8]
65 cmp ecx, edx
67 cmp ecx, r10d
69 movzx ecx, byte [r8 + 1]
70 and ecx, 0xC0
71 cmp ecx, 0x80
72 jne .invalid
73 add r8, 2
74 jmp .next
75
76.four: lea rcx, [r8 + 3]
77 cmp rcx, r9
79 mov edx, 0x80
80 mov r10d, 0xBF
81 cmp al, 0xF0
82 jne .f1
83 mov edx, 0x90 ; F0: no overlongs
84.f1: cmp al, 0xF4
85 jne .f2
86 mov r10d, 0x8F ; F4: nothing past U+10FFFF
87.f2: movzx ecx, byte [r8]
88 cmp ecx, edx
90 cmp ecx, r10d
92 movzx ecx, byte [r8 + 1]
93 and ecx, 0xC0
94 cmp ecx, 0x80
95 jne .invalid
96 movzx ecx, byte [r8 + 2]
97 and ecx, 0xC0
98 cmp ecx, 0x80
99 jne .invalid
100 add r8, 3
101 jmp .next
102
103.valid: mov eax, 1
104 ret
105.invalid:
106 xor eax, eax
107 ret