# `ihb2032/tervyx/small_vec` — Inline Small Vectors, Fixed-Cap Vector & Inline BitSet

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

AST child lists, graph adjacency lists, HTTP header buckets, and small integer
flag sets typically hold `0..=8` elements or bit indices in `0..63`. Allocating
a separate heap array per short-lived instance creates avoidable GC and
allocator pressure. `ihb2032/tervyx/small_vec` provides 4 low-allocation
containers sharing the unified Sequence & Set vocabulary
([api_conventions.md](../api_conventions.md)):

- **Cross-language design influences**:
  - **C++ (LLVM `SmallVector` / Folly `small_vector`) & Rust (`smallvec`)**: `@small_vec.SmallVec4` and `@small_vec.SmallVec8` store up to 4 or 8 elements inline inside struct fields, spilling transparently to `Array[T]` when exceeded and supporting `shrink_to_inline()`.
  - **C++ (`boost::container::static_vector`) & Rust (`arrayvec`)**: `@small_vec.StaticVec` allocates a single fixed-capacity `UninitializedArray[T]` at construction and exposes capacity bounds explicitly through `try_push -> Bool`.
  - **LLVM `SmallBitVector` / Rust `smallbitvec`**: `@small_vec.SmallBitSet` stores bits `0..63` inline with zero heap allocation, spilling transparently only when a bit `>= 64` is inserted or `capacity > 64` is requested, with wordwise `union_with` / `intersect_with` / `difference_with` and hardware `ctz`/`popcnt` operations.
  - **Go (`Append`-into-dst) & Rust (`retain`)**: Unified `append_to(dst)`, `drain_into(dst)`, `retain(pred)`, and positive `is_inline()` predicate.
- **Rejected alternatives**:
  - **Generic `SmallVec[T, N]`**: MoonBit does not have const-generic struct field expansion; providing `SmallVec4` and `SmallVec8` covers the two most common inline thresholds with zero array-header indirection.

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

- **`StaticVec[T]` (`UninitializedArray[T]`)**: Uses MoonBit 1.0's public `UninitializedArray[T]` (the same backing primitive used by `moonbitlang/core` `Array[T]`). Construction is `O(1)` without an `O(cap)` `None`-fill loop, `clear()` is `O(1)`, and `get`/`set`/`pop`/`swap_remove`/`retain`/`iter`/`each` perform zero `Option` boxing or tagging checks. Popped slots follow `core` `Array`'s retention model (overwritten on reuse or released when the `StaticVec` is dropped).
- **`SmallVec4[T]` / `SmallVec8[T]`**: MoonBit 1.0 does not expose a value-type `MaybeUninit[T]` for struct scalar fields (`UnsafeMaybeUninit` is compiler-private), so inline struct fields (`e0..e3` / `e0..e7`) use `T?` to stay heap-free; once spilled, `heap : Array[T]?` uses `UninitializedArray[T]`. Inlining slot dispatch directly inside `push` and `get` and bypassing repeated `heap` checks during inline construction allows both `SmallVec4` and `SmallVec8` to beat `Array` across `wasm`, `wasm-gc`, `js`, and `native`.
- **`SmallBitSet` per-backend split**:
  - `wasm`, `wasm-gc`, `native` (`small_vec/small_bitset.mbt`): stores bits `0..63` in a single native `UInt64` with single-check unsigned bounds testing (`bit.reinterpret_as_uint() < 64U`) and spills to `FixedArray[UInt64]?`.
  - `js` (`small_vec/small_bitset_js.mbt`): splits bits `0..63` into two signed 32-bit `Int32` halves (`lo`, `hi`) and spills to `FixedArray[Int32]?`, eliminating `BigInt` heap allocations and speeding up inline operations on `js` from `263.58 ns` to **`18.63 ns` (14.15× faster)** while preserving identical 64-bit `is_inline()` thresholds and public APIs.
  - Across the 4 backends, `SmallBitSet::to_array` pre-allocates `Array(capacity=self.length())` and delegates directly to `ctz` bit-clearing via `append_to`.

## 3. Invariants & Formal Verification

- **Colocated Why3/Z3 formal verification (`small_vec/small_bitset_common.mbt` + `small_vec/proof.mbtp`, `proof_enabled = true`)**:
  - `bitset_words_for` (called directly by `SmallBitSet::SmallBitSet`): Z3 proves `capacity <= 64` yields `0` (inline mode), and `capacity > 64` yields the minimal word count `words >= 2` satisfying `(words - 1) * 64 < capacity <= words * 64`.
  - `clamp_nonneg` (called directly by `StaticVec::StaticVec` and `SmallBitSet::next_one`): Z3 proves `res >= 0` and non-negative inputs are preserved unchanged.
  - `bitset_addr` (called directly by `SmallBitSet::next_one`): Z3 proves `(word, offset)` satisfies `word >= 0`, `0 <= offset < 64`, and `word * 64 + offset == bit`.
  - Scope note: `SmallVec4`, `SmallVec8`, `StaticVec`, and `SmallBitSet` contain `mut` fields, which `moonc-prove 1.0.0-rc1` (`[4207]`) does not yet allow directly inside contracted methods. Container methods are covered by 4-backend tests 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/small_vec --target all --release`.

| Benchmark | `wasm` | `wasm-gc` | `js` | `native` |
| :--- | ---: | ---: | ---: | ---: |
| `bench_small_vec4_push4_inline` | `75.33 ns` | `23.32 ns` | `14.62 ns` | `21.69 ns` |
| `bench_array_push4_core` | `100.95 ns` | `30.97 ns` | `35.06 ns` | `24.93 ns` |
| `bench_small_vec8_push8_inline` | `74.04 ns` | `36.29 ns` | `13.79 ns` | `25.36 ns` |
| `bench_array_push8_core` | `108.17 ns` | `49.84 ns` | `35.60 ns` | `26.89 ns` |
| `bench_small_bitset_inline_ops` | `89.92 ns` | `45.03 ns` | `18.63 ns` | `18.14 ns` |
| `bench_map_int_set_core` | `1.01 µs` | `356.78 ns` | `460.25 ns` | `425.87 ns` |

### Takeaways & Guidance

- **`SmallVec4`**: Beats `Array` across the 4 backends (`js` **2.40×**, `wasm` **1.34×**, `wasm-gc` **1.33×**, `native` **1.15×**) — preferred default for short `0..=4` sequences.
- **`SmallVec8`**: Beats `Array` across the 4 backends (`js` **2.58×**, `wasm` **1.46×**, `wasm-gc` **1.37×**, `native` **1.06×**) — strong fit when median length is `5..=8`.
- **`SmallBitSet`**: **24.7×** faster than `core/Map` on `js` (`18.63 ns` via zero-`BigInt` 32-bit split, **14.15×** faster than `UInt64`), **23.5×** on `native` (`18.14 ns`), **11.2×** on `wasm`, and **7.92×** on `wasm-gc`.
