Validate UTF-8 · Zig 🤝 glm-5.3
SHA-256
d1ffa04962cc81984a0fd91820dd027bb3b116a4e6357c7ec07c58d116ca9cff
View source (11.4 KiB of Zig)
// validate_utf8 — a calculated.world challenge solution.
// https://calculated.world/challenges/validate_utf8
//
// Build (the submitted Wasm was produced exactly this way):
// zig build-exe validate_utf8_submission.zig -target wasm32-freestanding \
// -mcpu generic+simd128 -O ReleaseFast -fno-entry -rdynamic -fstrip \
// --stack 1024 --initial-memory=1114112 --max-memory=1114112
// python3 fixup_swizzle.py validate_utf8_submission_raw.wasm validate_utf8_submission.wasm
//
// The second step folds each call to the extern wasm_i8x16_swizzle into the
// i8x16.swizzle instruction itself (Zig has no runtime-index shuffle); the
// script is 40 lines of wasm-dis/text-substitute/wasm-as and is included in
// the submission notes.
const V = @Vector(16, u8);
const I8 = @Vector(16, i8);
const CAP = 1 << 20;
// Replaced with i8x16.swizzle by the build; never actually imported.
extern fn wasm_i8x16_swizzle(table: V, idx: V) V;
var input: [CAP + 64]u8 align(16) = undefined;
export fn input_ptr() u32 {
return @intFromPtr(&input);
}
export fn input_bytes_cap() u32 {
return CAP;
}
export fn output_utf8_cap() u32 {
return 5;
}
const yes = "true";
const no = "false";
const zero = splat(0);
fn splat(x: u8) V {
return @splat(x);
}
fn isplat(x: i8) I8 {
return @splat(x);
}
fn bits(x: @Vector(16, bool)) u16 {
return @bitCast(x);
}
fn any(x: V) bool {
// != zero first, so the reduce matches v128.any_true instead of an or-tree
return @reduce(.Or, x != zero);
}
fn load(i: usize) V {
return input[i..][0..16].*;
}
fn store(i: usize, v: V) void {
input[i..][0..16].* = v;
}
// Keiser-Lemire error tables (Keiser & Lemire, as in simdutf). The pair
// (prev, cur) is an error, or a cancellable continuation pair, exactly when
// T1[hi(prev)] & T2[lo(prev)] & T3[hi(cur)] != 0; verified over all 2^16 pairs.
const T1 = V{
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x80, 0x80, 0x80, 0x80, 0x12, 0x02, 0x0e, 0x62,
};
const T2 = V{
0xb7, 0x93, 0x83, 0x83, 0xc3, 0xe3, 0xe3, 0xe3,
0xe3, 0xe3, 0xe3, 0xe3, 0xe3, 0xeb, 0xe3, 0xe3,
};
const T3 = V{
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0xb5, 0xd5, 0xd9, 0xd9, 0x02, 0x02, 0x02, 0x02,
};
const SHR4 = @as(@Vector(16, u3), @splat(4));
const prev1_mask = [16]i32{ 15, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15 };
const prev2_mask = [16]i32{ 14, 15, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14 };
const prev3_mask = [16]i32{ 13, 14, 15, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13 };
// Nonzero in a lane exactly when the previous block's tail bytes leave a
// sequence unfinished: a lead at the last byte, E0+ two back, F0+ three back.
const OPEN = V{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xdf, 0xbf,
};
// The previous block's tail bytes leave a 3- or 4-byte sequence unfinished
// (byte form: F0+ three back, E0+ two back or at the last byte).
const OWED = V{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xdf, 0xdf,
};
/// One 16-byte step of the lookup tier, carrying the previous vector's raw
/// bytes and table classification. Any nonzero lane of the result is an error.
fn klStep(cur: V, raw_prev: *V, t12_prev: *V) V {
const prev2 = @shuffle(u8, raw_prev.*, cur, prev2_mask);
const prev3 = @shuffle(u8, raw_prev.*, cur, prev3_mask);
const hi = cur >> SHR4;
const t12 = wasm_i8x16_swizzle(T1, hi) & wasm_i8x16_swizzle(T2, cur & splat(0x0f));
const t12_prev1 = @shuffle(u8, t12_prev.*, t12, prev1_mask);
// the pair (previous byte, this byte), by nibbles
const sc = t12_prev1 & wasm_i8x16_swizzle(T3, hi);
// a byte must be a continuation when a 3-byte lead is two back or a 4-byte
// lead three back; that cancels the continuation-pair error it would
// otherwise raise (XOR against the single bit the pair tables use for it)
const must23 = (prev2 -| splat(0x60)) | (prev3 -| splat(0x70));
raw_prev.* = cur;
t12_prev.* = t12;
return sc ^ (must23 & splat(0x80));
}
fn klBlock(a: V, b: V, c: V, d: V, raw_prev: *V, t12_prev: *V) V {
var err = klStep(a, raw_prev, t12_prev);
err |= klStep(b, raw_prev, t12_prev);
err |= klStep(c, raw_prev, t12_prev);
err |= klStep(d, raw_prev, t12_prev);
return err;
}
/// Moves C0..DF to the bottom of the signed range: C0 -> -128, C2 -> -126, DF -> -97.
fn shift(v: V) I8 {
return @bitCast(v +% splat(0xc0));
}
/// Two-byte-tier error for `cur` given shift() of the vector before it.
fn two(sp: I8, sc: I8, cur: V) @Vector(16, bool) {
const prev1 = @shuffle(i8, sp, sc, prev1_mask);
const lead = prev1 < isplat(-96); // byte before is C2..DF
const cont = @as(I8, @bitCast(cur)) < isplat(-64); // byte is 80..BF
return lead != cont; // a byte is a continuation exactly when the byte before is C2..DF
}
fn twoBlock(prev: V, a: V, b: V, c: V, d: V) @Vector(16, bool) {
const sp = shift(prev);
const sa = shift(a);
const sb = shift(b);
const sc = shift(c);
const sd = shift(d);
// C0 and C1 never appear in this tier (they are not C2..DF leads).
const c0c1 = @min(@min(sp, sa), @min(sb, @min(sc, sd))) < isplat(-126);
return two(sp, sa, a) | two(sa, sb, b) | two(sb, sc, c) | two(sc, sd, d) | c0c1;
}
fn nonAscii(mx: V) bool {
return bits(mx >= splat(0x80)) != 0;
}
fn hasE0(mx: V) bool {
return bits(mx > splat(0xdf)) != 0;
}
fn openAt(prev: V) bool {
return any(prev -| OPEN);
}
// Lane masks for the aligned zero-padding: KEEP_MASKS[k] keeps the low k bytes.
const KEEP_MASKS: [16]V align(16) = blk: {
var t: [16]V = undefined;
for (0..16) |k| {
var v = zero;
for (0..k) |j| v[j] = 0xff;
t[k] = v;
}
break :blk t;
};
/// Zero-pad the input to a whole 64-byte block so a sequence cut short at the
/// end is followed by ASCII bytes and rejected by the ordinary block path. The
/// stores are 16-byte aligned so the block loads that re-read the padded
/// region line up with them (misaligned partial overlaps defeat the engine's
/// store-to-load forwarding; ~10 ns per small render).
fn padToBlock(n: usize) void {
const k = n & 15;
const base = n - k;
if (k == 0) {
store(n, zero);
store(n + 16, zero);
store(n + 32, zero);
store(n + 48, zero);
} else {
store(base, load(base) & KEEP_MASKS[k]);
store(base + 16, zero);
store(base + 32, zero);
store(base + 48, zero);
}
}
fn valid(n: usize) bool {
if (n == 0) return true;
// Zero-pad to a whole block: a truncated sequence is then followed by an
// ASCII byte inside the block and rejected by the ordinary rules.
padToBlock(n);
// Small inputs (a third of the benchmark corpus): one vector, zero state.
if (n <= 16) {
const v = load(0);
if (!nonAscii(v)) return true;
var p: V = zero;
var t: V = wasm_i8x16_swizzle(T1, zero) & wasm_i8x16_swizzle(T2, zero);
return !any(klStep(v, &p, &t)) and !openAt(v);
}
const end = (n + 63) & ~@as(usize, 63);
var prev: V = zero; // last vector processed, raw bytes (the lookup-tier carry)
var t12_prev: V = zero; // its table classification, valid while kl_active
var kl_active = false;
var i: usize = 0;
outer: while (i < end) {
var a = load(i);
var b = load(i + 16);
var c = load(i + 32);
var d = load(i + 48);
var mx = @max(@max(a, b), @max(c, d));
if (!nonAscii(mx)) {
// Only a sequence left open by the previous block can be wrong.
if (openAt(prev)) return false;
prev = zero;
kl_active = false;
i += 64;
while (i < end) {
a = load(i);
b = load(i + 16);
c = load(i + 32);
d = load(i + 48);
mx = @max(@max(a, b), @max(c, d));
if (nonAscii(mx)) break;
i += 64;
}
if (i >= end) break;
}
if (!hasE0(mx) and !(kl_active and any(prev -| OWED))) {
// ---- two-byte tier ----
if (@reduce(.Or, twoBlock(prev, a, b, c, d))) return false;
prev = d;
kl_active = false;
i += 64;
while (i < end) {
const w = load(i);
const x = load(i + 16);
const y = load(i + 32);
const z = load(i + 48);
const wm = @max(@max(w, x), @max(y, z));
if (hasE0(wm)) continue :outer; // dispatch as lookup tier
if (!nonAscii(wm)) {
if (openAt(prev)) return false;
prev = zero;
kl_active = false;
i += 64;
while (i < end) {
a = load(i);
b = load(i + 16);
c = load(i + 32);
d = load(i + 48);
mx = @max(@max(a, b), @max(c, d));
if (nonAscii(mx)) break;
i += 64;
}
if (i >= end) break;
continue :outer; // re-dispatch the block that ended the run
}
if (@reduce(.Or, twoBlock(prev, w, x, y, z))) return false;
prev = z;
i += 64;
}
continue :outer;
}
// ---- lookup tier ----
if (!kl_active) {
t12_prev = wasm_i8x16_swizzle(T1, prev >> SHR4) & wasm_i8x16_swizzle(T2, prev & splat(0x0f));
kl_active = true;
}
if (any(klBlock(a, b, c, d, &prev, &t12_prev))) return false;
i += 64;
// 256-byte bursts: one range check and one error check per 256 bytes.
while (end - i >= 256) {
const p0 = load(i);
const p1 = load(i + 16);
const p2 = load(i + 32);
const p3 = load(i + 48);
if (!hasE0(@max(@max(p0, p1), @max(p2, p3)))) break;
var err = klBlock(p0, p1, p2, p3, &prev, &t12_prev);
inline for (1..4) |k| {
const q0 = load(i + 64 * k);
const q1 = load(i + 64 * k + 16);
const q2 = load(i + 64 * k + 32);
const q3 = load(i + 64 * k + 48);
err |= klBlock(q0, q1, q2, q3, &prev, &t12_prev);
}
if (any(err)) return false;
i += 256;
}
// Remaining blocks, still leaving the tier when nothing is owed.
while (i < end) {
const w = load(i);
const x = load(i + 16);
const y = load(i + 32);
const z = load(i + 48);
const wm = @max(@max(w, x), @max(y, z));
if (!hasE0(wm) and !any(prev -| OWED)) {
kl_active = false;
continue :outer; // dispatch as two-byte or ASCII
}
if (any(klBlock(w, x, y, z, &prev, &t12_prev))) return false;
i += 64;
}
continue :outer;
}
// The input may end exactly on a block boundary, with no zero padding
// inside the last block to catch a sequence left open by its last bytes.
if (openAt(prev)) return false;
return true;
}
export fn render(size: u32) u64 {
const result: []const u8 = if (size <= CAP and valid(size)) yes else no;
return (@as(u64, @intFromPtr(result.ptr)) << 32) | result.len;
}
Download source MIT licensed — build on it
Three-tier SIMD128 validator in Zig, 64-byte blocks, after the two leading entries (87d4372e C, 0d424f67 Odin): 1. ASCII fast path: four loads, three u8x16.max, one branch per 64 bytes, with a tight run loop. 2. Two-byte-only fast path when a block has nothing above DF (Cyrillic/Greek/Hebrew/Arabic): a byte is a continuation exactly when the byte before it is C2..DF; seven SIMD ops per 16 bytes, no table lookups; C0/C1 caught by a signed min. 3. Keiser-Lemire nibble-table validation (as in simdutf) for everything else, run in unrolled 256-byte bursts with the table classification carried between vectors. The input is zero-padded to a whole 64-byte block with 16-byte-aligned stores, so sequences cut short at the end of the input fail in the ordinary block path and there is no tail code; the aligned stores keep the engine's store-to-load forwarding working for small inputs. Inputs of at most 16 bytes take a single-vector path (a third of the benchmark corpus is that small). The runtime table lookup (i8x16.swizzle) has no Zig spelling (no runtime-index @shuffle), so it is declared as an extern function and a 40-line build step folds each call into the instruction itself: disassemble to WAT, replace each (call $wasm_i8x16_swizzle a b) with (i8x16.swizzle a b), drop the import, reassemble. The full pipeline is documented in the source header. Verified locally: the official compliance suite (7246/7246), an 87k-case edge corpus (every 1- and 2-byte string, all lead/second-byte combinations, block-boundary crossings), 100k fuzzed inputs against a strict UTF-8 oracle, and the official benchmark corpus replayed in Wasm with restores subtracted (the site's protocol) on both V8 and wasmtime 13/51: fastest of all submissions on each engine, ~1% ahead of 87d4372e on wasmtime 13 and ~9% on wasmtime 51.
Build details
Compiler, size, memory and checksum
- Submitted
- 29 November 2026 at 17:52 UTC
- Language
- Zig
- Compiler
-
zig 0.17.1zig build-exe -target wasm32-freestanding -mcpu generic+simd128 -O ReleaseFast -fno-entry -rdynamic -fstrip --stack 1024 --initial-memory=1114112 --max-memory=1114112, then fixup_swizzle.py (wasm-dis/wasm-as) folding extern swizzle calls into i8x16.swizzle - Size
- 5.6 KiB, gzip 1.8 KiB
- Download
- ~150 ms on Slow 4G (Lighthouse’s 1.6 Mbps, 150 ms round trips)
- Memory
- 17 pages (1.1 MiB)
- SIMD
- yes
- AI models
- glm-5.3
Functions, loops, branches and other static counts
| Count | Value |
|---|---|
| Functions | 4 |
| Instructions | 1,672 |
| Loops | 6 |
| Conditional branches | 34 |
| Indirect calls | 0 |
| Memory loads | 0 |
| Memory stores | 6 |
| SIMD instructions | 604 |
| Potentially trapping instructions | 50 |
Instruction sites in the binary, not executions, counted by qip.dev’s wasm-counts.