;; validate_utf8 for calculated.world, hand-written WAT, no SIMD, no tables. Smallest-size attempt. ;; ;; Builds on patrickgwsmith's "WAT / Fable 5.2" entry (8b1c547b), MIT: the same algorithm, one byte per turn, with a shift ;; register $m whose sign bit is set while continuation bytes are owed, and at each lead byte one range test plus three ;; holes on lead*128 + next byte (every Table 3-7 rule about the first two bytes). What changed is the wrapper: ;; * input_ptr, input_utf8_cap and output_utf8_cap are the same function exported three times, returning 1 MiB. The input ;; lives at 1 MiB, so the loads carry that offset, and the 1 MiB cap covers inputs up to 512 KiB. ;; * the answer text is at address 0, so "true" is the one-byte-wide constant 4 (address 0, length 4) and "false" is ;; address 4, length 5. ;; * input_utf8_cap is a byte shorter than input_bytes_cap, and the checker accepts either name. ;; * no data-count section, and memory is fixed at 32 pages. (module (memory (export "memory") 32 32) (data (i32.const 0) "truefalse") (func (export "input_ptr") (export "input_utf8_cap") (export "output_utf8_cap") (result i32) i32.const 1048576) (func (export "render") (param $n i32) (result i64) (local $i i32) (local $x i32) (local $m i32) (local $v i32) block $false block $end loop $next local.get $i local.get $n i32.eq br_if $end ;; x = input[i++], sign-extended local.get $i i32.const 1 i32.add local.tee $i i32.load8_s offset=1048575 local.set $x ;; continuation owed? local.get $m i32.const 0 i32.lt_s if local.get $x i32.const -64 i32.ge_s br_if $false local.get $m i32.const 1 i32.shl local.set $m br $next end ;; ASCII local.get $x i32.const 0 i32.ge_s br_if $next ;; lead byte: 110x -> 1 owed, 1110 -> 2, 11110 -> 3 local.get $x i32.const 25 i32.shl local.set $m ;; v = lead*128 + next byte local.get $x i32.const 7 i32.shl local.get $i i32.load8_s offset=1048576 i32.add local.tee $v ;; outside C2 80 .. F4 8F i32.const 8064 i32.add i32.const 6416 i32.ge_u ;; E0 80..9F local.get $v i32.const 5 i32.shr_s local.tee $x i32.const -132 i32.eq i32.or ;; ED A0..BF local.get $x i32.const -79 i32.eq i32.or ;; F0 80..8F local.get $v i32.const 4 i32.shr_s i32.const -136 i32.eq i32.or br_if $false br $next end end ;; input ended mid-sequence? local.get $m i32.const 0 i32.lt_s br_if $false i64.const 4 ;; "true": address 0, 4 bytes return end i64.const 0x400000005)) ;; "false": address 4, 5 bytes