utf16
import std::encoding::utf16; · source
UTF-16 is the text encoding the Windows wide-character (*W) calls take. The codec is plain Cryo, with no OS dependency, so it builds and behaves the same on every target.
Types
Utf16
type struct Utf16 {}
The codec is stateless; its operations are statics.
encodeturns UTF-8 text into UTF-16 units followed by one NUL unit, the form every*Wpath and name parameter expects. A malformed byte encodes as U+FFFD, asStr::charsreads it.encode_intoappends the units of UTF-8 bytes that arrive in pieces, with no NUL, and answers how many bytes it encoded: all of them except a multi-byte sequence cut short at the end, which a later call completes when those bytes are passed again ahead of the rest. A stream writing to a console encodes this way without splitting a character.decodeturns units an OS call wrote back into aString. A surrogate that is not half of a pair is refused with aUtf8Errorwhosevalid_up_tois the index of the unit; itserror_lengthisNonewhen the input ends on a high surrogate whose pair could still follow.decode_lossyreads such a surrogate as U+FFFD instead, for text that must be read even when it is not well-formed, such as a Windows argument or environment variable.
import std::encoding::utf16::{ Utf16 };
const wide: Array<u16> = Utf16::encode(Str::new("hé")); // 'h', 'é', NUL
match (Utf16::decode(wide.as_slice())) {
Result::Ok(text) => { /* "hé" and the NUL, which is text like any other */ }
Result::Err(e) => { /* a lone surrogate */ }
}
Static functions
static encode(text: Str) -> Array<u16>;
static encode(text: Str) -> Array<u16>;text as UTF-16 code units followed by one NUL unit, ready to pass to a wide-character call. A malformed byte in text encodes as U+FFFD, as Str::chars reads it.
static encode_into(bytes: &Slice<u8>, out: mut &Array<u16>) -> i64;
static encode_into(bytes: &Slice<u8>, out: mut &Array<u16>) -> i64;Append the UTF-16 units of the UTF-8 bytes to out, with no NUL, and answer how many bytes were encoded: all of them except a multi-byte sequence cut short at the end, which a later call completes when those bytes are passed again ahead of the rest. Text arriving in pieces, as a stream writes it, encodes this way without splitting a character. A malformed byte encodes as U+FFFD, as in encode.
static decode(units: &Slice<u16>) -> Result<String, Utf8Error>;
static decode(units: &Slice<u16>) -> Result<String, Utf8Error>;The text in units, which end at the slice's end (a NUL unit, if present, is text like any other). A surrogate that is not half of a pair is refused: the error's valid_up_to is the index of the unit, and its error_length is None when the input ends on a high surrogate whose pair could still follow.
static decode_lossy(units: &Slice<u16>) -> String;
static decode_lossy(units: &Slice<u16>) -> String;The text in units, as decode reads it, except that a surrogate that is not half of a pair becomes U+FFFD instead of refusing the whole. For text that must be read even when it is not well-formed, such as a Windows argument or environment variable.
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct Utf16 {}The UTF-16 codec. Stateless; its operations are statics.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::encoding::utf16;UTF-16: the text encoding the Windows wide-character (*W) calls take.
const NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const wide: Array<u16>type struct Array<T, A = GlobalAllocator> where A: Allocator {}A growable sequence of Ts stored contiguously, owning its elements; A is the allocator its storage comes from. Indexing out of range panics; get answers None instead.
static Utf16::encode(text: Str) -> Array<u16>text as UTF-16 code units followed by one NUL unit, ready to pass to a wide-character call. A malformed byte in text encodes as U+FFFD, as Str::chars reads it.
type struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
static Str::new(text: string) -> StrConstruct from a NUL-terminated C-style string literal. The caller certifies that text is valid UTF-8 and outlives this view. The NUL terminator is not included in the view.
match (subject) {
Pattern(x) => { ... }
_ => { ... }
}The primary discriminator: branches on enum variants, integers, ranges, constants, and tuple and destructuring patterns, such as (0, 1..8) or Option::Some((count, _)), and the compiler rejects a match that misses a case. There is no fallthrough. As an expression it evaluates to the chosen arm's value, so every arm must produce the same type.
static Utf16::decode(units: &Slice<u16>) -> Result<String, Utf8Error>The text in units, which end at the slice's end (a NUL unit, if present, is text like any other). A surrogate that is not half of a pair is refused: the error's valid_up_to is the index of the unit, and its error_length is None when the input ends on a high surrogate whose pair could still follow.
const wide: Array<u16>type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
Result::Ok(T)text: Stringpattern => { body }Separates a match arm's pattern from its body. Arms do not fall through.
Result::Err(E)e: Utf8ErrorStr::chars(&this) -> implement Iterator<char>Iterator over the Unicode scalar values of this string, decoding UTF-8 on the fly. Each scalar is yielded as a char, so the character methods read it (c.is_digit()), and c as u32 is its code point. This is the scalar-level counterpart to byte_at/as_bytes, which stay byte-level.
static Utf16::encode_into(bytes: &Slice<u8>, out: mut &Array<u16>) -> i64Append the UTF-16 units of the UTF-8 bytes to out, with no NUL, and answer how many bytes were encoded: all of them except a multi-byte sequence cut short at the end, which a later call completes when those bytes are passed again ahead of the rest.
type struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
type struct Utf8Error {
valid_up_to: i64;
error_length: Option<i64>;
}Where a byte sequence stops being UTF-8; see Str::from_utf8.
Option::Nonestatic Utf16::decode_lossy(units: &Slice<u16>) -> StringThe text in units, as decode reads it, except that a surrogate that is not half of a pair becomes U+FFFD instead of refusing the whole. For text that must be read even when it is not well-formed, such as a Windows argument or environment variable.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
(parameter) text: Str(parameter) bytes: &Slice<u8>type struct Slice<T> {}The elements are reached through ptr, declared read-only: through a mut &Slice<T> it reads as a writable pointer, through a &Slice<T> as the read-only one it is.
(parameter) out: mut &Array<u16>mut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
(parameter) units: &Slice<u16>