// Is standard input valid UTF-8? Answers `true` or `false` (calculated.world's validate_utf8). // mito build --wasm examples/wasm/validate_utf8.mito -o validate_utf8.wasm // // The method is Keiser and Lemire's ("Validating UTF-8 In Less Than One Instruction Per Byte"). It looks at 16 bytes at once. // For each byte, three tables are asked about it and the byte before it. Each bit of an answer stands for one kind of mistake, // and the pair is wrong where all three tables have the same bit set: // 1 a first byte with no continuation after it 16 a surrogate (U+D800 to U+DFFF) // 2 a continuation after an ASCII byte 32 a 2-byte form of a 1-byte character // 4 a 3-byte form of a shorter character 64 above U+10FFFF, or a 4-byte form of a shorter character // 8 above U+10FFFF 128 two continuations in a row (right only inside a 3 or 4 byte character) // // The text is read 64 bytes at a time in one loop. A load before the start or past the end gives zeros, so the first and last // blocks need no code of their own, and a character cut short at the end is followed by a zero, which is a mistake. platform cli; // every program declares a state; this one has nothing to keep struct Unused { n: i64; } state unused: Unused; fn any(v: u8x16) -> bool { return (v != 0).mask() != 0; } fn valid(text: string) -> bool { // asked with the high 4 bits of the byte before, its low 4 bits, and the high 4 bits of this byte let before_high = u8x16(2, 2, 2, 2, 2, 2, 2, 2, 128, 128, 128, 128, 33, 1, 21, 73); let before_low = u8x16(231, 163, 131, 131, 139, 203, 203, 203, 203, 203, 203, 203, 203, 219, 203, 203); let this_high = u8x16(1, 1, 1, 1, 1, 1, 1, 1, 230, 174, 186, 186, 1, 1, 1, 1); var errors = u8x16(0); var at = 0; foreach block in 0..len(text) / 64 { let a = text.load_u8x16(at); let b = text.load_u8x16(at + 16); let c = text.load_u8x16(at + 32); let d = text.load_u8x16(at + 48); // there is nothing to check in 64 ASCII bytes whose 3 bytes before are ASCII too (the top bits of the 16 before) let has_high_byte = (a | b | c | d).mask() != 0; let follows_high_byte = text.load_u8x16(at - 16).mask() >> 13 != 0; if has_high_byte || follows_high_byte { var here = at; foreach quarter in 0..3 { let bytes = text.load_u8x16(here); let back1 = text.load_u8x16(here - 1); let back2 = text.load_u8x16(here - 2); let back3 = text.load_u8x16(here - 3); let pairs = before_high.lookup(back1 >> 4) & before_low.lookup(back1 & 15) & this_high.lookup(bytes >> 4); // the third byte of a 3 or 4 byte character, and the fourth of a 4 byte one, must be a second continuation let must_continue = (back2 >= 224) | (back3 >= 240); errors = errors | (pairs ^ (must_continue & 128)); here += 16; } // an invalid text need not be read to the end if any(errors) { return false; } } at += 64; } return true; } @main fn main(body: utf8<0..524288> from stdin) -> Response { if valid(body) { return ok("true"); } return ok("false"); }