# `ihb2032/tervyx/memscan` — `V128` SIMD & Unpacked Byte / Substring Scanning

## 1. Purpose, Cross-Language Selection & Tradeoffs

Lexing, HTTP/JSON/CSV delimiter scanning, ASCII validation, and substring
search spend most of their time linearly scanning `BytesView`. Naive scalar
byte-by-byte loops leave wide vector lanes unused on linear-memory targets and
repeat `BytesView` offset arithmetic on GC/JS targets. `ihb2032/tervyx/memscan`
provides portable per-backend-specialized scanning primitives:

- **Cross-language design influences**:
  - **Rust (`memchr` crate)**: `@memscan.find_byte`, `@memscan.rfind_byte`, `@memscan.find_byte2`, `@memscan.find_byte3`, `@memscan.count_byte`, and first+last byte filtered `@memscan.find_bytes` (compares both `needle[0]` and `needle[n - 1]` before verifying inner bytes).
  - **.NET (`System.Buffers.SearchValues<byte>`)**: `@memscan.SearchValues` precompiles a 256-byte lookup table (and on `wasm`/`native`, multi-strategy `V128` masks) for `@memscan.SearchValues::find_any` and `@memscan.SearchValues::find_any_except`.
  - **Go (`Append`-into-dst)**: `@memscan.find_all_byte_into` appends match offsets directly into a caller-owned `Array[Int32]` with zero intermediate array allocation.
  - **SIMD / 8× unrolled ASCII validation**: `@memscan.find_non_ascii` and `@memscan.is_valid_ascii` test 32 bytes per loop via `V128` `i8x16_bitmask` on `wasm`/`native` and 8 bytes per loop via bitwise OR on `wasm-gc`/`js`.
- **Rejected alternatives**:
  - **Two-Way / Boyer-Moore tables for `find_bytes`**: First+last byte filtering avoids preprocessing allocations and delivers superior branch predictability on typical short-to-medium needles (2–64 bytes).
  - **Lane-packed `V128` on `wasm-gc`**: On `wasm-gc`, `Bytes` is a GC `(array (mut i8))` without linear-memory `v128.load`, so 16-byte vector loads lower to 16 scalar loads plus 16 `i8x16.replace_lane` ops (64 ops per iteration in dual-anchor `find_bytes`). Unpacking `data()` once and running 8× unrolled scalar loops beats lane-packing across `find_byte`, `is_valid_ascii`, and `find_bytes` (up to **3.36×** faster on `find_bytes`).

## 2. MoonBit Data Layout & Multi-Backend Tradeoffs

- **Per-target compilation split**:
  - `wasm`, `native`: compile `memscan/memscan_simd.mbt`, delegating 16-byte linear-memory loads, comparisons, and bitmask extraction to `internal/simd_probe` (`V128`) with a tight scalar tail for trailing `< 16` bytes.
  - `wasm-gc`, `js`: compile `memscan/memscan_scalar.mbt` (zero `V128` lane-packing), unpacking `BytesView::data()` and `start_offset()` once outside each loop and unrolling 8× for `find_byte`, `find_non_ascii`, and `find_bytes` (4× OR/AND-combined table lookups for `SearchValues`).
- **Multi-strategy `SearchValues` on `wasm`/`native` (baseline SSE2/Wasm-SIMD first, nibble-LUT fallback)**:
  - `find_byte`, `is_valid_ascii`, `find_bytes`, and `SearchValues` (for 0 bytes, 1–4 unique bytes, and contiguous byte ranges `[lo..=hi]`) use baseline SSE2 / Wasm-SIMD / NEON instructions (`i8x16_eq`, `i8x16_sub`, `i8x16_lt_s`, `i8x16_bitmask`) with **zero SSSE3 `i8x16_swizzle` dependency**, reaching **38.4 GB/s** on `find_byte`, **43.4 GB/s** on `is_valid_ascii`, and **21.7 GB/s** on 4-byte `SearchValues` even under default `-march=x86-64` native builds.
  - `find_byte` and `is_valid_ascii` unroll 2× (32 bytes per iteration) with a single combined `i8x16_bitmask` check per 32 bytes; `find_bytes` fuses first+last byte comparisons into one `i8x16_bitmask`.
  - General `>= 5`-byte non-range sets fall back to 4-bit nibble-LUT (`i8x16_swizzle`, full speed on Wasm/ARM64 and SSSE3-enabled native builds).

## 3. Invariants & Formal Verification

- **Colocated Why3/Z3 formal verification (`memscan/memscan.mbt` + `memscan/proof.mbtp`, `proof_enabled = true`)**:
  - `bytes_match_inner` (the live inner-range verification function called by `find_bytes`) carries direct `where { proof_require / proof_ensure }` contracts and loop invariants proved by Z3, guaranteeing exact equivalence to `∀ j, 1 <= j < nlen - 1 → haystack[pos + j] == needle[j]` and strict bounds safety.
  - Scope note: `memscan/memscan_simd.mbt` uses `V128` intrinsics, which `moonc-prove 1.0.0-rc1` does not yet model in Why3. Both `memscan/memscan_simd.mbt` and `memscan/memscan_scalar.mbt` are verified across the 4 backends by exhaustive boundary tests (`0..=130` bytes, misaligned subviews, non-ASCII injection at each offset) with 100% line coverage.

## 4. 4-Backend `--release` Benchmarks (WSL2 Local)

Environment: **AMD Ryzen 7 7840HS** (16 CPUs), `Linux 6.18.58.1-microsoft-standard-WSL2`,
MoonBit `v1.0.0-rc1+3c0520448`, `moon bench -p ihb2032/tervyx/memscan --target all --release`.

| Benchmark (4096 B input) | `wasm` | `wasm-gc` | `js` | `native` |
| :--- | ---: | ---: | ---: | ---: |
| `bench_find_byte_4096_simd` | `144.30 ns` | `1.10 µs` | `1.19 µs` | `106.64 ns` |
| `bench_find_byte_4096_scalar` | `1.70 µs` | `1.74 µs` | `1.87 µs` | `895.58 ns` |
| `bench_is_valid_ascii_4096_simd` | `130.30 ns` | `959.55 ns` | `1.18 µs` | `94.32 ns` |
| `bench_is_valid_ascii_4096_scalar` | `1.76 µs` | `2.02 µs` | `1.86 µs` | `907.30 ns` |
| `bench_search_values_4096_simd` | `238.74 ns` | `1.55 µs` | `1.78 µs` | `188.57 ns` |
| `bench_search_values_4096_scalar` | `3.36 µs` | `3.09 µs` | `3.35 µs` | `1.81 µs` |
| `bench_find_bytes_4096_simd` | `442.16 ns` | `1.30 µs` | `1.20 µs` | `211.57 ns` |

### Takeaways & Guidance

- **`find_byte`**: **11.8×** faster on `wasm`, **8.4×** on `native` (~`38.4 GB/s`), **1.58×** on `wasm-gc`, and **1.57×** on `js`.
- **`is_valid_ascii`**: **13.5×** faster on `wasm`, **9.6×** on `native` (~`43.4 GB/s`), **2.11×** on `wasm-gc`, and **1.58×** on `js`.
- **`SearchValues::find_any`**: **14.1×** faster on `wasm`, **9.6×** on `native` (~`21.7 GB/s`, zero SSSE3 required), **1.99×** on `wasm-gc`, and **1.88×** on `js`.
- **`find_bytes`**: Unpacking `data()` + 8× unrolled anchor scanning cuts `wasm-gc` from `4.37 µs` to `1.30 µs` (**3.36×** faster) and `js` from `2.91 µs` to `1.20 µs` (**2.43×** faster), while `native` stays at `211.57 ns` and `wasm` at `442.16 ns`.
