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·2 commits across 61 linesoldernewer
AVX2: three nibble tables and a saturating subtractAug 4 1// test.c: the boundaries of Unicode table 3-7, for both versions.
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);
AVX2: three nibble tables and a saturating subtractAug 4 10int utf8_valid_avx2(const uint8_t *buf, size_t len);
12static const struct {
13 const char *bytes;
14 int valid;
15 const char *what;
16} samples[] = {
17 { "", 1, "nothing at all" },
18 { "plain ASCII", 1, "ASCII" },
19 { "\xC2\x80", 1, "U+0080, the first two-byte code point" },
20 { "\xDF\xBF", 1, "U+07FF, the last" },
21 { "\xE0\xA0\x80", 1, "U+0800, the first three-byte code point" },
22 { "\xED\x9F\xBF", 1, "U+D7FF, just below the surrogates" },
23 { "\xEE\x80\x80", 1, "U+E000, just above them" },
24 { "\xEF\xBF\xBF", 1, "U+FFFF" },
25 { "\xF0\x90\x80\x80", 1, "U+10000, the first four-byte code point" },
26 { "\xF4\x8F\xBF\xBF", 1, "U+10FFFF, the last code point" },
27 { "\xC0\x80", 0, "an overlong NUL" },
28 { "\xC1\xBF", 0, "an overlong U+007F" },
29 { "\xE0\x9F\xBF", 0, "an overlong U+07FF" },
30 { "\xED\xA0\x80", 0, "U+D800, a surrogate" },
31 { "\xED\xBF\xBF", 0, "U+DFFF, a surrogate" },
32 { "\xF0\x8F\xBF\xBF", 0, "an overlong U+FFFF" },
33 { "\xF4\x90\x80\x80", 0, "U+110000, past the end of Unicode" },
34 { "\xF5\x80\x80\x80", 0, "F5, which never appears" },
35 { "\xFF", 0, "FF, which never appears" },
36 { "\x80", 0, "a continuation with no lead" },
37 { "\xC3\xA9\xA9", 0, "one continuation too many" },
38 { "\xC3", 0, "a two-byte lead at the very end" },
39 { "\xC3" "A", 0, "a two-byte lead followed by ASCII" },
40};
41#define SAMPLES (sizeof samples / sizeof samples[0])
42
43int main(void)
44{
AVX2: three nibble tables and a saturating subtractAug 4 45 if (!__builtin_cpu_supports("avx2")) {
46 puts("this CPU has no AVX2; nothing to test");
47 return 2;
48 }
50 for (size_t i = 0; i < SAMPLES; i++) {
AVX2: three nibble tables and a saturating subtractAug 4 51 const uint8_t *p = (const uint8_t *)samples[i].bytes;
52 size_t n = strlen(samples[i].bytes);
53 int a = utf8_valid_scalar(p, n), b = utf8_valid_avx2(p, n);
54 if (a == samples[i].valid && b == samples[i].valid)
56 wrong++;
AVX2: three nibble tables and a saturating subtractAug 4 57 printf("wrong: %s: scalar %d, avx2 %d\n", samples[i].what, a, b);
59 printf("cases: %zu samples, %d wrong\n", SAMPLES, wrong);
60 return wrong != 0;
61}