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 54 linesoldernewer
Scalar validator with every range from table 3-7Jul 20 1// test.c: the boundaries of Unicode table 3-7.
2//
3// build/test.exe
4
5#include <stdint.h>
6#include <stdio.h>
7#include <string.h>
8
9int utf8_valid_scalar(const uint8_t *buf, size_t len);
10
11static const struct {
12 const char *bytes;
13 int valid;
14 const char *what;
15} samples[] = {
16 { "", 1, "nothing at all" },
17 { "plain ASCII", 1, "ASCII" },
18 { "\xC2\x80", 1, "U+0080, the first two-byte code point" },
19 { "\xDF\xBF", 1, "U+07FF, the last" },
20 { "\xE0\xA0\x80", 1, "U+0800, the first three-byte code point" },
21 { "\xED\x9F\xBF", 1, "U+D7FF, just below the surrogates" },
22 { "\xEE\x80\x80", 1, "U+E000, just above them" },
23 { "\xEF\xBF\xBF", 1, "U+FFFF" },
24 { "\xF0\x90\x80\x80", 1, "U+10000, the first four-byte code point" },
25 { "\xF4\x8F\xBF\xBF", 1, "U+10FFFF, the last code point" },
26 { "\xC0\x80", 0, "an overlong NUL" },
27 { "\xC1\xBF", 0, "an overlong U+007F" },
28 { "\xE0\x9F\xBF", 0, "an overlong U+07FF" },
29 { "\xED\xA0\x80", 0, "U+D800, a surrogate" },
30 { "\xED\xBF\xBF", 0, "U+DFFF, a surrogate" },
31 { "\xF0\x8F\xBF\xBF", 0, "an overlong U+FFFF" },
32 { "\xF4\x90\x80\x80", 0, "U+110000, past the end of Unicode" },
33 { "\xF5\x80\x80\x80", 0, "F5, which never appears" },
34 { "\xFF", 0, "FF, which never appears" },
35 { "\x80", 0, "a continuation with no lead" },
36 { "\xC3\xA9\xA9", 0, "one continuation too many" },
37 { "\xC3", 0, "a two-byte lead at the very end" },
38 { "\xC3" "A", 0, "a two-byte lead followed by ASCII" },
39};
40#define SAMPLES (sizeof samples / sizeof samples[0])
41
42int main(void)
43{
44 int wrong = 0;
45 for (size_t i = 0; i < SAMPLES; i++) {
46 int got = utf8_valid_scalar((const uint8_t *)samples[i].bytes, strlen(samples[i].bytes));
47 if (got == samples[i].valid)
48 continue;
49 wrong++;
50 printf("wrong: %s: got %d\n", samples[i].what, got);
51 }
52 printf("cases: %zu samples, %d wrong\n", SAMPLES, wrong);
53 return wrong != 0;
54}