Skip to content
CryoCryo home
Stdlibencoding

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.

  • encode turns UTF-8 text into UTF-16 units followed by one NUL unit, the form every *W path and name parameter expects. A malformed byte encodes as U+FFFD, as Str::chars reads it.
  • encode_into appends 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.
  • decode turns units an OS call wrote back into a String. A surrogate that is not half of a pair is refused with a Utf8Error whose valid_up_to is the index of the unit; its error_length is None when the input ends on a high surrogate whose pair could still follow.
  • decode_lossy reads 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>;

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;

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>;

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;

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.