Skip to content
CryoCryo home
Stdlibencoding

utf8

import std::encoding::utf8; · source

Reading one Unicode scalar at a byte position.

Types

Utf8

type struct Utf8 {}

Utf8::decode_at reads the scalar a position starts and Utf8::decode_before the one that ends there, each with the number of bytes it takes. Both are strict: a sequence that is not well-formed UTF-8 — a continuation byte where a scalar would start, an overlong form, a surrogate half, a value past U+10FFFF, or a sequence cut short — decodes to nothing, so a caller decides what a malformed byte means. Str::from_utf8 refuses it; Str::chars reads it as U+FFFD.

import std::encoding::utf8::{ Utf8, DecodedScalar };

function main() -> int {
    const text: Str = "héllo";
    match (Utf8::decode_at(text.as_bytes(), 1)) {
        Option::Some(d) => { return if (d.scalar == 0xE9 && d.length == 2) { 0 } else { 1 }; }
        Option::None    => { return 1; }
    }
}

Static functions

static decode_at(bytes: &Slice<u8>, index: i64) -> Option<DecodedScalar>;

The scalar whose encoding starts at byte index of bytes, or None at or past the end, before the start, or where the bytes from index are not one well-formed sequence. [0xC3, 0xA9] at 0 is U+00E9 over 2 bytes; at 1, a continuation byte, it is None.

static decode_before(bytes: &Slice<u8>, index: i64) -> Option<DecodedScalar>;

The scalar whose encoding ends just before byte index of bytes, or None at or before the start, past the end, or where the bytes before index do not end one well-formed sequence. [0x61, 0xC3, 0xA9] before 3 is U+00E9 over 2 bytes; before 2 it is None.

DecodedScalar

type struct DecodedScalar {
    scalar: u32;
    length: i64;
}

One decoded scalar: its value, and how many bytes of the input it took.

Properties

PropertyTypeNotes
scalaru32The Unicode scalar value, at most U+10FFFF and never a surrogate.
lengthi64The bytes its encoding takes: 1 to 4.