# Tervyx Unified API Conventions

This document is the authoritative specification for container, scanner, and
hasher naming across `ihb2032/tervyx`. Operations with the same semantics share
the same verb, parameter order, and return convention across packages, avoiding
synonymous duplicates while preserving clear cross-language ergonomics.

## 1. Construction, Conversion & Trait Conventions

| Pattern | Canonical Signature | Notes |
| :--- | :--- | :--- |
| Canonical constructor | `Type::Type(...)` | Follows MoonBit 1.0 canonical constructors: `@flat_map.FlatHashMap(entries, capacity~)`, `@btree.BTreeMap(entries)`, `@small_vec.SmallVec4(xs)`, `@small_vec.SmallBitSet(capacity~)`, `@slot_map.SlotMap(capacity~)`, `@memscan.SearchValues(needles)`, `@hash.RapidHasher(seed~)` |
| View alias | `#alias(from_array)` | Retained on constructors accepting `ArrayView[...]` for zero-copy slice inputs |
| Iterator builder | `from_iter(Iter[...]) -> Self` | Provided by unbounded collections: `FlatHashMap`, `FlatHashSet`, `IntMap`, `SortedFlatMap`, `BTreeMap`, `BTreeSet`, `SmallVec4`, `SmallVec8` |
| Default instance | `impl Default` | Implemented by stateful public types except `StaticVec` (requires an explicit fixed capacity) and `SearchValues` (requires a byte-set pattern) |
| Structured debug | `impl @debug.Debug` | Supports `debug_inspect` snapshots without redundant `Show` formatters |
| Equality | `impl Eq` | Implemented by value-semantic containers and handle types |

### Ownership & Zero-Allocation Output Boundaries

- Public functions do not retain caller-owned mutable containers (`Array`, etc.) without a visible copy; this rule is statically enforced by `.github/scripts/check_array_copy_boundaries.py`.
- Batch export methods follow Go's `Append`-into-destination pattern by accepting a caller-owned `dst : Array[...]` buffer (`append_to`, `drain_into`, `range_into`, `find_all_byte_into`).

## 2. Map Vocabulary

Applies to `@flat_map.FlatHashMap`, `@flat_map.IntMap`, `@flat_map.SortedFlatMap`,
and `@btree.BTreeMap`.

| Category | Method | Unified Semantics | Cross-Language Inspiration |
| :--- | :--- | :--- | :--- |
| Size | `length()` / `is_empty()` | Entry count and emptiness check (`O(1)`) | MoonBit / Rust |
| Membership | `contains(k) -> Bool` | Presence check (`contains`, not `contains_key`) | MoonBit `core` |
| Lookup | `get(k) -> V?` | Value lookup | Standard |
| Insert / replace | `set(k, v) -> V?` | Inserts or overwrites and returns the previous value (no duplicate `insert` or `insert_if_absent`) | MoonBit `core` |
| Lazy init | `get_or_init(k, () -> V raise?) -> V raise?` | Evaluates `init()` on miss, stores and returns the value | MoonBit `core` / Rust `or_insert_with` |
| Atomic state transition | `change(k, (V?) -> V? raise?) -> Unit raise?` | Single-lookup four-state transition (insert, update, delete, or no-op) | OCaml Jane Street `Core` |
| Atomic upsert | `update(k, (V?) -> V raise?) -> Unit raise?` | Single-lookup insert-or-update | OCaml Jane Street `Core` |
| Deletion | `remove(k) -> V?` | Removes key and returns the previous value | Standard |
| Reset | `clear()` | Removes entries while keeping allocated capacity where applicable | Standard |
| Filter | `retain((K, V) -> Bool raise?)` | Retains entries where the predicate returns `true` | Rust `std` |
| Conditional extract | `extract_if((K, V) -> Bool raise?, dst)` | Removes matching entries and appends them to `dst` | Rust `extract_if` + Go `dst` |
| Iteration | `iter()` / `iter2()` / `keys()` / `values()` | Lazy iterators with `size_hint` | MoonBit `core` |
| Export | `to_array()` / `append_to(dst)` | Allocates a fresh array or appends into caller-owned `dst` | MoonBit + Go `Append` |

### Ordered Map Extensions

Applies to `@flat_map.SortedFlatMap` and `@btree.BTreeMap`.

| Method | Semantics | Availability |
| :--- | :--- | :--- |
| `min()` / `max()` | Minimum / maximum `(K, V)?` entry | Both |
| `range(lo, hi) -> Iter2[K, V]` | Lazy inclusive `[lo, hi]` range iterator | Both |
| `range_into(lo, hi, dst)` | Zero-intermediate-allocation inclusive `[lo, hi]` export into `dst` | Both |
| `lower_bound(k)` / `upper_bound(k)` | Sorted array index boundaries (`O(log n)`) | `SortedFlatMap` |
| `pop_min()` / `pop_max()` | Removes and returns minimum / maximum entry (`O(log n)`) | `BTreeMap` |

### Hash Map Capacity Controls

Applies to `@flat_map.FlatHashMap`, `@flat_map.IntMap`, and `@flat_map.FlatHashSet`
(with `shrink_to_fit` on `FlatHashMap` and `IntMap`):

- `capacity()`: current bucket count (`0` or a power of two `>= 16`).
- `reserve(additional)`: ensures room for at least `additional` new entries without reallocating.
- `shrink_to_fit()`: compacts bucket storage to the smallest valid power-of-two capacity.

## 3. Set Vocabulary

Applies to `@flat_map.FlatHashSet`, `@btree.BTreeSet`, and `@small_vec.SmallBitSet`.

| Category | Method | Unified Semantics |
| :--- | :--- | :--- |
| Cardinality | `length()` / `is_empty()` | Number of elements (`SmallBitSet::length` counts set bits) and emptiness check |
| Membership | `contains(x)` / `insert(x) -> Bool` / `remove(x) -> Bool` / `clear()` | `insert` and `remove` return whether membership changed |
| Export | `iter()` / `to_array()` / `append_to(dst)` | Lazy iteration and caller-buffer reuse |
| Filtering | `retain(pred)` / `extract_if(pred, dst)` | Provided by `FlatHashSet` and `BTreeSet` |
| Set algebra | General sets: `union` / `intersection` / `difference` / `is_subset` / `is_disjoint`; bitset: `union_with` / `intersect_with` / `difference_with` | General sets return new sets; `SmallBitSet` performs zero-allocation in-place wordwise operations |
| Ordered & bit helpers | `min()` (`BTreeSet` & `SmallBitSet`); `max()` / `pop_min()` / `pop_max()` / `range()` / `range_into()` (`BTreeSet`); `is_inline()` / `toggle(bit)` / `next_one(from)` (`SmallBitSet`) | Consistent extremum and storage-mode naming |

## 4. Sequence Vocabulary

Applies to `@small_vec.SmallVec4`, `@small_vec.SmallVec8`, and `@small_vec.StaticVec`.

| Category | Method | Unified Semantics |
| :--- | :--- | :--- |
| Size | `length()` / `is_empty()` | Element count and emptiness check |
| Storage state | `is_inline()` (`SmallVec4`, `SmallVec8`, `SmallBitSet`); `capacity()` / `remaining_capacity()` / `is_full()` (`StaticVec`) | Positive storage predicate `is_inline()` replaces `is_spilled` |
| Indexed access | `get(i) -> T?` / `set(i, v) -> Bool` | Bounds-checked without panicking |
| Mutation | `push(v)` (`SmallVec4`/`SmallVec8`) or `try_push(v) -> Bool` (`StaticVec`), `pop() -> T?`, `swap_remove(i) -> T?`, `clear()` | `SmallVec4`/`SmallVec8` also support `insert`, `remove`, `truncate`, `shrink_to_inline` |
| Batch & iteration | `retain(pred)` / `each(f)` / `iter()` / `to_array()` / `append_to(dst)` / `drain_into(dst)` | `drain_into` moves elements in order into `dst` and empties the sequence |

## 5. Generational Arena Vocabulary

Applies to `@slot_map.SlotMap`, `@slot_map.DenseSlotMap`, and
`@slot_map.SecondaryMap`, sharing `#valtype` handle `@slot_map.Key`.

| Category | Method | Unified Semantics |
| :--- | :--- | :--- |
| Handle allocation | `insert(v) -> Key` (`SlotMap`/`DenseSlotMap`), `insert_with_key((Key) -> T) -> Key` (`SlotMap`) | Allocates a slot and mints a live odd-version `Key` |
| Keyed write | `set(k, v)` (`SlotMap`/`DenseSlotMap` return `Bool`; `SecondaryMap` returns `T?`) | Writes by existing `Key`, cleanly distinct from handle-minting `insert` |
| Presence & lookup | `contains(k) -> Bool` / `get(k) -> T?` | Unified `contains` verb (replaces `contains_key`) |
| In-place transform | `update(k, (T) -> T raise?) -> Bool raise?` | Single version-checked in-place transformation |
| Removal | `remove(k) -> T?` / `clear()` | Advances slot version to permanently invalidate stale handles |
| Batch & export | `retain` / `extract_if` / `append_to(dst)` / `drain_into(dst)` | Consistent with Map and Sequence export conventions |
| Iteration | `iter()` / `iter2()` / `keys()` / `values()` | Implemented across the 3 arena types |

## 6. Scanner & Hasher Conventions

- **`memscan`**: Search functions use the `find_` / `rfind_` prefix (`find_byte`, `rfind_byte`, `find_byte2`, `find_byte3`, `find_bytes`, `find_non_ascii`, `find_all_byte_into`); `SearchValues` exposes `contains`, `find_any`, and `find_any_except`.
- **`hash`**: One-shot functions use the `hash_` prefix (`hash_bytes`, `hash_string`, `hash_int`, `hash_int64`, `hash_uint64`) with optional `seed~ : UInt64 = DEFAULT_SEED`; streaming `RapidHasher` exposes `write_byte`, `write_bytes`, `write_int`, `write_int64`, `write_uint64`, `write_string`, and `finish`.
