// Is standard input valid UTF-8? The same answer as validate_utf8.mito, one byte at a time, to compare with it. // mito build --wasm examples/wasm/validate_utf8_scalar.mito -o validate_utf8_scalar.wasm --cflag -O3 --cflag -mno-simd128 // The ranges are Unicode's table of well-formed byte sequences (Table 3-7). A byte past the end reads as -1, which is in none of // them, so a character cut short is refused without a test of its own. platform cli; // every program declares a state; this one has nothing to keep struct Unused { n: i64; } state unused: Unused; // is the byte at `at` a continuation byte (80 to BF)? fn continuation(text: string, at: i64) -> bool { let byte = byte_at(text, at); return byte >= 128 && byte <= 191; } fn valid(text: string) -> bool { var at = 0; while at < len(text) { let first = byte_at(text, at); if first < 128 { at += 1; continue; } // the first byte says how long the character is and which values its second byte may have var length = 0; var low = 128; var high = 191; if first >= 194 && first <= 223 { length = 2; } else if first >= 224 && first <= 239 { length = 3; if first == 224 { low = 160; } // a shorter character written long if first == 237 { high = 159; } // a surrogate } else if first >= 240 && first <= 244 { length = 4; if first == 240 { low = 144; } // a shorter character written long if first == 244 { high = 143; } // above U+10FFFF } else { return false; } let second = byte_at(text, at + 1); if second < low || second > high { return false; } if length >= 3 && !continuation(text, at + 2) { return false; } if length == 4 && !continuation(text, at + 3) { return false; } at += length; } return true; } @main fn main(body: utf8<0..524288> from stdin) -> Response { if valid(body) { return ok("true"); } return ok("false"); }