utf8

    Portable SIMD UTF-8 validation, precise errors, and streaming ported from simdutf8

    utf8
    unicode
    validation
    simd
    simdutf8
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    58 minutes ago
    Downloads
    2

    No dependencies

    #UTF-8 examples

    ///|
    test "validate and decode UTF-8" {
    let data = b"I \xE2\x9D\xA4 UTF-8!"
    assert_true(@utf8.is_valid(data))
    assert_eq(@utf8.from_utf8(data), "I ❤ UTF-8!")
    assert_true(!@utf8.is_valid(b"\xED\xA0\x80"))
    }

    ///|
    test "complete a streamed multibyte sequence" {
    let state = @utf8.Validator::new()
    state.update(b"\xF0\x9F")
    assert_true(!state.finalize())
    state.update(b"\x98\x80")
    assert_true(state.finalize())
    let branch = state.copy()
    branch.update(b"\xFF")
    assert_true(!branch.finalize())
    assert_true(state.finalize())
    }

    Utf8Error

    type Utf8Error derive(Eq,
    Debug
    )

    An invalid or incomplete UTF-8 sequence, with Rust-compatible byte offsets. The representation is private; inspect it with valid_up_to() and error_len(). Offsets are relative to the supplied view, not its backing buffer. An incomplete suffix has no error length.
    impl Show for Utf8Error

    Utf8Error::error_len

    fn Utf8Error::error_len(self : Utf8Error) -> Int?

    Returns the malformed sequence's length, excluding the byte that interrupted a valid prefix of a multibyte sequence. The result is Some(1), Some(2), or Some(3) for invalid input and None for a potentially valid truncated suffix. This matches std::str::Utf8Error::error_len() in Rust.

    Utf8Error::valid_up_to

    fn Utf8Error::valid_up_to(self : Utf8Error) -> Int

    Returns the number of valid bytes before the first malformed sequence. The offset identifies its leading byte, or the unexpected continuation byte. It counts bytes rather than Unicode scalars or UTF-16 code units.

    Validator

    type Validator

    A mutable strict UTF-8 validator for arbitrarily split byte chunks. Assignment aliases the same state; copy() forks independent state. Input views are read synchronously and never retained. Errors are reported only by finalize(), as a boolean rather than an offset, like simdutf8 basic streaming.

    Validator::copy

    fn Validator::copy(self : Validator) -> Validator

    Copies current validation state into an independent mutable validator. Both branches retain the same backend preference and pending continuation requirements; updating or resetting one branch cannot affect the other.

    Validator::finalize

    fn Validator::finalize(self : Validator) -> Bool

    Reports whether all supplied bytes form complete, valid UTF-8. This observes state without consuming or resetting it. Repeated calls agree; after an incomplete result, supplying the missing continuation can make a later result true. A malformed sequence remains false until reset().

    Validator::new

    fn Validator::new(simd? : Bool) -> Validator

    Creates an empty validator; empty input finalizes successfully. simd=true requests vector validation of complete portions of updates of at least 64 bytes on native/Wasm. Sequence fragments and shorter updates use scalar state transitions; Wasm GC and JS always use the scalar fallback.

    Validator::reset

    fn Validator::reset(self : Validator) -> Unit

    Discards all stream input and errors while preserving the SIMD preference. Aliases observe the reset; independent copies do not.

    Validator::update

    fn Validator::update(self : Validator, data : BytesView) -> Unit

    Adds data to the logical stream without retaining or mutating the bytes. A multibyte sequence may cross any number of updates, including empty ones. Invalid input makes failure sticky until reset(). There is no intermediate error result; an incomplete suffix is retained as at most three continuation requirements. Complete large portions use the requested validation backend.

    from_utf8

    fn from_utf8(data : BytesView, simd? : Bool) -> String raise Utf8Error

    Validates UTF-8 and decodes it into an immutable MoonBit UTF-16 string. Unlike Rust's borrowed str, the returned string owns decoded storage and does not alias the byte buffer. Embedded NUL and a leading BOM are preserved. Invalid input raises the same precise Utf8Error as validate.

    simd controls validation only, with the same short-input and backend fallbacks as validate. Decoding uses the installed core UTF-8 decoder after successful validation and is an additional cost.

    is_valid

    fn is_valid(data : BytesView, simd? : Bool) -> Bool

    Checks strict UTF-8 without constructing a string or reporting error details. Empty input, embedded NUL, and a UTF-8 BOM are valid. Overlong encodings, surrogate encodings, values above U+10FFFF, and incomplete suffixes are invalid. Only data is read; unaligned views are supported and input is never mutated.

    simd=true requests native vector range checks or the Wasm lookup3 algorithm for inputs of at least 64 bytes. Shorter inputs, Wasm GC, and JavaScript use scalar validation. The vector path aggregates errors over the full input, like simdutf8's basic flavor; the scalar fallback may stop at the first error.

    test {
    assert_true(@utf8.is_valid(b"\xE2\x9D\xA4"))
    assert_true(!@utf8.is_valid(b"\xED\xA0\x80"))
    }

    validate

    fn validate(data : BytesView, simd? : Bool) -> Unit raise Utf8Error

    Validates strict UTF-8 and raises the first Rust-compatible Utf8Error. The error's offset is relative to data; error_len=None identifies an incomplete final sequence. Validation neither allocates a string nor mutates input. Empty input, embedded NUL, and BOM bytes are accepted.

    With simd=true, native/Wasm inputs of at least 64 bytes use vector validation and check errors after each block. A scalar scan around the first failing block recovers the exact offset and length. Other cases use scalar validation, preserving identical errors on all backends.

    test {
    try @utf8.validate(b"a\xF0\x9Fa") catch {
    error => {
    assert_eq(error.valid_up_to(), 1)
    assert_eq(error.error_len(), Some(2))
    }
    } noraise {
    _ => fail("expected invalid UTF-8")
    }
    }