;; validate_utf8 for calculated.world, hand-written WAT, no SIMD, no tables. ;; ;; One byte per loop turn. $m is a shift register holding the lead byte's ;; remaining length bits: its sign bit is set while a continuation byte is owed. ;; At a lead byte, v = lead*128 + next byte (both sign-extended) folds every ;; Table 3-7 rule about the first two bytes into one range and three holes: ;; range C2 80 .. F4 8F (rejects 80..C1 and F5..FF as leads, and > U+10FFFF) ;; holes E0 80..9F (overlong), ED A0..BF (surrogates), F0 80..8F (overlong) ;; If the next byte is not a continuation, the next turn rejects it anyway. (module (memory (export "memory") 17 17) (data (i32.const 1) "truefalse") (func (export "input_ptr") (result i32) i32.const 16) (func (export "input_bytes_cap") (result i32) i32.const 1048576) (func (export "output_utf8_cap") (result i32) i32.const 5) (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=15 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=16 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 0x100000004 ;; "true": address 1, 4 bytes return end i64.const 0x500000005)) ;; "false": address 5, 5 bytes