# justjavac/escape

Reusable ASCII escaping in pure MoonBit, with portable V128 scanning and
HTML, HTML5, JSON, and LaTeX presets. This ports the observable behavior of
[v_escape](https://github.com/zzau13/v_escape) 1.0.0 at revision
[8801de7df59ce8218ef1d5900f63e51b08b0ac04](https://github.com/zzau13/v_escape/tree/8801de7df59ce8218ef1d5900f63e51b08b0ac04),
including arbitrary-byte preservation and append semantics.

## Install and import

The module builds independently and depends only on MoonBit core:

```text
moon add justjavac/escape
```

Add the package to your `moon.pkg`:

```text
import {
  "justjavac/escape",
}
```

For byte append operations, also import `"moonbitlang/core/buffer"`.
Use the repository's compatible nightly toolchain, a platform C compiler for
native builds, and Node.js for JavaScript. Validation used moon 0.1.20261120
and moonc v0.10.22+7b085e9a4-nightly (2026-11-22).

## Quick examples

```mbt
test "escape examples" {
  let escaped = @escape.html5.escape("<😀 & />")
  assert_eq(escaped, "&lt;😀 &amp; /&gt;")
  let custom = @escape.Escaper::new([(b'<', "&lt;"), (b'"', "&quot;")])
  assert_eq(custom.escape("Hello,< world!\""), "Hello,&lt; world!&quot;")
  let formatted = @escape.json.escape_fmt("a\nb")
  assert_eq("value: \{formatted}", "value: a\\nb")
}
```

[README.mbt.md](README.mbt.md) contains short checked examples. Public API doc
examples are checked as part of `moon test`.

## Escape tables

Replacements are emitted once, from left to right. Replacement output is
never rescanned. Unmapped input passes through unchanged; existing HTML
entities are therefore escaped again.

| Source | `html` | `html5` |
| --- | --- | --- |
| `"` | `&quot;` | `&quot;` |
| `&` | `&amp;` | `&amp;` |
| `'` | `&#x27;` | `&#x27;` |
| `/` | `&#x2f;` | preserved |
| `<` | `&lt;` | `&lt;` |
| `>` | `&gt;` | `&gt;` |

The lowercase hexadecimal spelling is part of the exact upstream output.
These presets escape text; they do not parse HTML or sanitize markup.

`json` escapes JSON string **content**, without surrounding quotation marks:

| Source | Replacement |
| --- | --- |
| U+0008 / U+0009 / U+000A | `\b` / `\t` / `\n` |
| U+000C / U+000D | `\f` / `\r` |
| Other U+0000..U+001F | lowercase four-digit `\u00xx` |
| `"` / `\${bt} | `\"` / `\\` |

Slash, DEL, non-ASCII text, U+2028, and U+2029 are preserved. For well-formed
text, wrapping the result in quotes produces the corresponding JSON string.
Raw byte output preserves invalid UTF-8 and need not be valid JSON text.

`latex` preserves the exact `v_latexescape` text table:

| Source | Replacement |
| --- | --- |
| `#`, `$`, `%`, `&`, `_`, `{`, `}` | prefix with `\${bt} |
| `<` / `>` | `\textless{}` / `\textgreater{}` |
| `\${bt} | `\textbackslash{}` |
| `^` / `~` | `\textasciicircum{}` / `\textasciitilde{}` |

This is text escaping, with no LaTeX parser or math-mode selection.

## API

`html`, `html5`, `json`, and `latex` are immutable shared `Escaper` values.
All operation parameters accept views; owned String/Bytes values convert to
views implicitly. The generated [interface](pkg.generated.mbti) is the
authoritative declaration inventory.

| API | Result and behavior |
| --- | --- |
| `Escaper::new(ArrayView[(Byte, String)])` | Validates and copies a custom mapping; raises `EscapeError`. |
| `Escaper::escape(StringView, algorithm=Auto)` | Returns escaped String. |
| `Escaper::escape_string(StringView, StringBuilder, algorithm=Auto)` | Appends to the existing builder. |
| `Escaper::to_bytes(BytesView, algorithm=Auto)` | Returns escaped immutable Bytes. |
| `Escaper::escape_bytes(BytesView, Buffer, algorithm=Auto)` | Appends arbitrary escaped bytes to the existing buffer. |
| `Escaper::escape_fmt(StringView, algorithm=Auto)` | Returns an `Escaped` value implementing Show for lazy interpolation. |
| `Escaped::to_string()` | Independently renders the retained view as a String. |
| `simd_available()` | Reports compiled V128 support, independently of input size and dispatch. |

The append methods preserve the names and behavior of upstream
`escape_string`/`escape_bytes`. Allocating operations are additional
MoonBit conveniences. A reusable `Escaper::new` mapping replaces the Rust
procedural macro; clients do not implement architecture-specific Vector or
EscapesBuilder traits.

### Custom tables and failures

Sources are unique bytes in **0..126**. The pinned upstream parser tests
`source < i8::MAX`, which excludes DEL (127) despite its broader ASCII
wording. This port preserves that actual acceptance range. Pair order does
not matter; control bytes and NUL may be mapped. Empty replacement strings
delete a source. Well-formed Unicode replacements are allowed and byte
operations cache their UTF-8 encoding during construction.

Construction raises:

| Error | Meaning |
| --- | --- |
| `EmptyTable` | No mappings were supplied. |
| `InvalidSource(byte)` | The source is outside 0..126. |
| `DuplicateSource(byte)` | A source occurs twice, including identical replacements. |
| `InvalidReplacement(source, code_unit_offset)` | A replacement contains an unpaired surrogate. |

Replacement UTF-16 validation keeps construction consistent across backends:
core UTF-8 encoding otherwise panics on unpaired surrogates on some targets
and replaces them on JavaScript. A failed constructor exposes no partially
built state and never mutates the caller's mapping.

Escaping itself has no typed errors and accepts empty input. Capacity follows
the backend's Int32-sized String/Bytes and buffer allocation limits. This
library performs escaping only; it does not unescape or normalize input.

### State and ownership

Escaper representation is private. Tables are immutable after construction,
and the caller's mapping array is copied. Assigning an escaper safely shares
that immutable configuration; there is no mutable cursor to reset or copy.
Preset tables and cached UTF-8 replacements are allocated once outside scans.

Text operations read UTF-16 code units directly and preserve unmatched
code units, including surrogate pairs. Byte operations substitute only
matching ASCII bytes and forward all other bytes, including malformed UTF-8,
unchanged. No text decoding is performed by the byte APIs.

An unchanged full input view may reuse immutable backing storage through
`to_owned()`. Changed output and partial views are materialized. Escapers
retain no input state. Lazy `Escaped` values retain their input view until
released, so a small view can keep a larger backing String alive. Each
rendering starts afresh and does not consume the value.

StringBuilder and Buffer are mutable reference values. Aliases observe
appends; the library never clears a supplied destination. Use a new builder
or reset it explicitly for a fresh result. Previously materialized output
remains an independent immutable snapshot when a destination is reused.

### Streaming and view boundaries

ASCII substitution has no cross-chunk state. Appending escaped byte chunks
gives the same result as escaping their concatenation, even when chunks
split UTF-8 sequences. Text chunks must use valid StringView boundaries:
MoonBit slice boundaries count UTF-16 code units and snap inward to avoid
splitting surrogate pairs. Byte offsets count bytes.

The scalar remainder of a vector text scan uses the original view's code-unit
indices. It does not create a snapped subview at an arbitrary vector boundary;
that boundary can lie between surrogate halves. This preserves both content
and match positions.

## Algorithm and portability

Windows, Linux, and macOS are supported on `native`, `wasm`, `wasm-gc`,
and `js`. Production code is pure MoonBit and imports only core SIMD,
Buffer, and UTF-8 encoding.

The immutable 128-slot table stores optional replacements. Custom keys are
sorted and split at their two widest gaps to derive at most three bounding
ranges. Scalar initial scans use exact preset predicates or a bounded custom
lookup. Vector scans use compact HTML OR-folding masks, JSON control/equality
masks, or unsigned wrapping-subtraction range tests. Every candidate is
rechecked against the exact table, including HTML and custom-range false
positives.

There are no table gathers or vector byte shuffles. Native lowering uses
portable lane operations; the library requires no optional architecture-specific
instructions or CPU feature detector.

| Request/backend | Behavior |
| --- | --- |
| `Auto` | Uses scalar code on every backend while a complete benchmark policy is pending. |
| `Scalar` | Uses scalar scanning and unchanged-run copies. |
| `Simd` on native / linear-memory Wasm | Scans 16 byte lanes or 8 UTF-16 lanes, with scalar tails. |
| `Simd` on Wasm GC / JS | Uses the scalar fallback. |

Every vector load is bounded by the actual view length. Inputs need no
alignment, and UTF-16 loads use the view's code-unit start offset. Short
input cannot execute a full vector load even if SIMD was requested. The
request and `simd_available()` alone do not establish vector execution.

See [BENCHMARK.md](BENCHMARK.md) for complete-operation measurements, public
adapter costs, sampling, and the status of cross-platform validation.

## Tests and reproduction

From the repository root:

```text
moon update
moon check --target all --deny-warn
moon test --target all
moon info
moon fmt
moon test --target native --enable-coverage
moon run scripts/coverage_report.mbtx local escape
moon -C benchmarks check --target all --deny-warn
moon -C benchmarks test --target all
moon run scripts/benchmark.mbtx escape
moon run scripts/benchmark_report.mbtx --self-test
```

The module can also be checked and tested independently outside this workspace.
Correctness tests cover exact upstream tables and examples, an independent
match/formula reference, all 256 byte values at every vector lane, every
short/tail length, unaligned views and escaping sentinels outside views,
Unicode low-byte collisions, valid BMP/early supplementary characters,
surrogate pairs crossing vector boundaries, invalid UTF-8, empty/deleting
replacements, invalid tables, snapshots and aliases, repeated lazy rendering,
and varied streaming chunks. JSON output round trips through core parsing.
Private mask checks cover all 65,536 possible UTF-16 lane values.

Local native coverage on the validated toolchain is 199/204 lines (97.55%).
The five zero-hit lines are declarations selected only for managed backends;
native trace metadata still includes them. Their behavior is checked on
Wasm GC/JS, and executable code is not excluded to increase the reported rate.

The [comparison harness](../benchmarks/escape) verifies identical adapted
results before timing, and the [collector](../scripts/benchmark.mbtx) and
[report validator](../scripts/escape_benchmark_report.mbtx) independently
validate the exact case inventory and provenance. CI collects correctness
and native coverage across all three operating systems.

## References and license

- [v_escape](https://github.com/zzau13/v_escape): runtime, macro, generated
  presets, and exact acceptance behavior at the pinned revision.
- [Current MoonBit SIMD API](https://mooncakes.io/docs/moonbitlang/core/simd).
- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259#section-7): JSON strings.
- [Development benchmarks](../benchmarks/README.md): versions, adapters,
  reproducible comparison copy, and snapshot publication.

Upstream author: Juan Aguilar Santillana <mhpoin@gmail.com>.
This port selects upstream's MIT option. [LICENSE](LICENSE) preserves
Copyright (c) 2019 Rust-iendo Barcelona and the full MIT notice, together with
the port's copyright. Comparison dependencies retain their own licenses.
