escape

    Portable SIMD escaping with reusable ASCII tables, HTML, HTML5, JSON, and LaTeX presets ported from v_escape

    escape
    html
    json
    latex
    simd
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    58 minutes ago
    Downloads
    2

    No dependencies

    #Checked escape examples

    See README.md for tables, ownership, byte semantics, and backend limits.

    ///|
    test "HTML5 preserves slash and Unicode" {
    assert_eq(@escape.html5.escape("<😀 & />"), "&lt;😀 &amp; /&gt;")
    }

    ///|
    test "custom table and lazy formatting" {
    let escaper = @escape.Escaper::new([(b'<', "&lt;"), (b'\"', "&quot;")])
    assert_eq(escaper.escape("Hello,< world!\""), "Hello,&lt; world!&quot;")
    let escaped = @escape.json.escape_fmt("a\nb")
    assert_eq("[\{escaped}]", "[a\\nb]")
    }

    EscapeError

    pub(all) suberror EscapeError {
    EmptyTable
    InvalidSource(Byte)
    DuplicateSource(Byte)
    InvalidReplacement(source~ : Byte, code_unit_offset~ : Int)
    } derive(Eq,
    Debug
    )

    Reports an invalid custom escape table before constructing any public state.

    EmptyTable rejects an empty mapping. InvalidSource identifies a byte outside 0..126, matching the pinned upstream macro's actual accepted range. DuplicateSource identifies a repeated source byte, even when its two replacements are equal. InvalidReplacement identifies an unpaired surrogate's UTF-16 offset so construction rejects it equally on all backends. Empty and well-formed Unicode replacement strings are allowed.

    Algorithm

    pub(all) enum Algorithm {
    Auto
    Scalar
    Simd
    } derive(Eq,
    Debug
    )

    Selects the implementation used by an escape operation.

    Scalar scans individual bytes or UTF-16 code units. Simd requests portable V128 scanning on native and linear-memory Wasm; short remainders, Wasm GC, and JavaScript use scalar code. Auto uses the scalar default until a complete cross-platform benchmark snapshot establishes a policy.

    Escaped

    pub struct Escaped {
    // private fields
    }

    A lazy escaped text view for interpolation and Show output.

    Creating this value retains the immutable escaper and input view without scanning or copying input. Each rendering independently escapes that view into the receiving logger; repeated rendering returns the same text. A partial view can keep its entire backing string alive. There is no mutable cursor, and neither rendering nor assignment consumes the value.
    impl Show for Escaped

    Escaped::to_string

    fn Escaped::to_string(self : Escaped) -> String

    Materializes this lazy view as a String through the standard Show renderer.

    Each call independently scans the retained view using its selected algorithm and returns the same escaped content, including empty output. Neither the view nor the escaper is mutated or consumed. Rendering allocates a String; backend allocation limits apply and there are no typed errors.

    Escaper

    pub struct Escaper {
    // private fields
    }

    An immutable, reusable mapping from ASCII source bytes to replacement text.

    Only source bytes are substituted, once, from left to right. Replacement text is never scanned again. Text operations preserve every other UTF-16 code unit; byte operations preserve every other byte, including invalid UTF-8. Representation is private. Construction copies the mapping and caches UTF-8 replacements, so changing the caller's array cannot affect it. Assignments safely share this immutable state; no reset or copy is needed.

    Escaper::escape

    fn Escaper::escape(self : Escaper, input : StringView, algorithm? : Algorithm) -> String

    Returns escaped text from exactly the supplied UTF-16 view.

    Each matching ASCII code unit is replaced once. Non-ASCII code units, surrogate pairs, NUL, and all other unmatched input are preserved without UTF-8 conversion or normalization. The input and escaper are never mutated. When nothing changes, to_owned() can reuse a full view's immutable string; a changed result or partial view is materialized. Empty input returns "". Allocation limits follow the backend's String/Int32 capacity. algorithm controls scanning only and cannot change output or introduce typed errors.

    test {
    assert_eq(@escape.html5.escape("<😀 & />"), "&lt;😀 &amp; /&gt;")
    assert_eq(@escape.json.escape("a\n\"b"), "a\\n\\\"b")
    }

    Escaper::escape_bytes

    fn Escaper::escape_bytes(self : Escaper, input : BytesView, output :
    Buffer
    , algorithm? : Algorithm) -> Unit

    Appends escaped arbitrary bytes to output, retaining its existing prefix.

    This matches upstream escape_bytes. Every unmatched byte, including NUL and invalid UTF-8, is forwarded unchanged; matching ASCII bytes emit their cached UTF-8 replacement. Replacement output is not rescanned. The mutable Buffer has reference semantics, is never cleared, and aliases observe the append. Empty input leaves it unchanged. Arbitrary byte chunk boundaries produce the same concatenated result as one call. Input and escaper remain immutable. Backend allocation limits and algorithm fallbacks still apply.

    Escaper::escape_fmt

    fn Escaper::escape_fmt(self : Escaper, input : StringView, algorithm? : Algorithm) -> Escaped

    Creates a lazy escaped view for string interpolation or another Show sink.

    Construction performs no scan and allocates no escaped text. It retains the immutable input view and escaper. Rendering uses the selected algorithm, writes directly to the logger, and never consumes or mutates the value. Empty input renders empty text. Rendering follows the same substitutions, UTF-16 preservation, and allocation limits as escape; logger output cannot report the formatter errors exposed by Rust's Display API.

    test {
    let escaped = @escape.html5.escape_fmt("<a>")
    assert_eq("value: \{escaped}", "value: &lt;a&gt;")
    assert_eq(escaped.to_string(), "&lt;a&gt;")
    }

    Escaper::escape_string

    fn Escaper::escape_string(self : Escaper, input : StringView, output : StringBuilder, algorithm? : Algorithm) -> Unit

    Appends escaped text to output, retaining its existing prefix.

    This is the counterpart of upstream escape_string. The builder is mutable and has reference semantics: aliases observe appended text. It is never cleared. Empty input leaves it unchanged. Calls on separate chunks concatenate to the whole-input result when StringView boundaries are valid. The escaper and input remain immutable. Non-ASCII code units and replacement strings are written verbatim; replacements are not rescanned. Backend allocation limits apply, and algorithm has the same fallback rules as escape.

    Escaper::new

    fn Escaper::new(pairs : ArrayView[(Byte, String)]) -> Escaper raise EscapeError

    Constructs a reusable custom table from (source byte, replacement) pairs.

    Sources must be unique and within 0..126, as accepted by v_escape 1.0.0 at the documented source revision. Pair order is irrelevant. Raises EmptyTable, InvalidSource(byte), or DuplicateSource(byte) on invalid mappings. InvalidReplacement(source, code_unit_offset) rejects an unpaired surrogate before UTF-8 encoding on every backend. Empty replacements delete a source; well-formed Unicode replacements are allowed. Byte operations emit their UTF-8 encoding and text preserves their code units. The input array is copied, never mutated or retained.

    test {
    let escaper = @escape.Escaper::new([(b'<', "&lt;"), (b'\"', "&quot;")])
    assert_eq(escaper.escape("Hello,< world!\""), "Hello,&lt; world!&quot;")
    }

    Escaper::to_bytes

    fn Escaper::to_bytes(self : Escaper, input : BytesView, algorithm? : Algorithm) -> Bytes

    Returns escaped bytes, preserving every unmatched byte including invalid UTF-8.

    Replacements use their cached UTF-8 bytes. Input is not decoded, normalized, or mutated, and the escaper retains no input state. Empty input returns empty bytes; an unchanged full view can reuse its immutable backing bytes via to_owned(). Changed output and partial views are materialized. Results share no mutable output buffer. algorithm selects scanning as for escape; backend Int32 allocation limits apply and this method does not raise typed errors.

    html

    let html : Escaper

    The v_htmlescape table, including slash escaping.

    Replaces ", &, ', /, <, and > with &quot;, &amp;, &#x27;, &#x2f;, &lt;, and &gt; respectively. Other bytes/code units are preserved. Existing entities are escaped again; this operation is not idempotent. The immutable table is allocated once and may be shared across calls.

    html5

    let html5 : Escaper

    The v_html5escape table, which preserves /.

    Replaces ", &, ', <, and > with the same entities as html. All other input is preserved and emitted entities are never rescanned. This is an immutable preset, not an HTML parser or sanitizer.

    json

    let json : Escaper

    The v_jsonescape JSON string-content table, without surrounding quotes.

    Replaces U+0000..U+001F, ", and \. Backspace, tab, newline, form feed, and carriage return use \b, \t, \n, \f, and \r; other controls use lowercase four-digit \u00xx escapes. Slash, DEL, non-ASCII text, U+2028, and U+2029 are preserved. Byte output does not validate UTF-8, so arbitrary byte input need not produce valid JSON text. The table is immutable.

    latex

    let latex : Escaper

    The exact twelve-entry v_latexescape text table.

    Prefixes #, $, %, &, _, {, and } with a backslash. Replaces <, >, \, ^, and ~ with \textless{}, \textgreater{}, \textbackslash{}, \textasciicircum{}, and \textasciitilde{} respectively. Other input is preserved; this does not parse LaTeX or choose math-mode escaping. Replacement macros are emitted once. The table is immutable.

    simd_available

    fn simd_available() -> Bool

    Reports whether this backend contains the portable V128 escape kernels.

    Returns true on native and linear-memory Wasm. This describes compiled support, not optional CPU feature detection or proof that a particular call executes vectors: text needs eight code units and bytes need sixteen bytes for a complete load. This function has no side effects.