encode

Encodes c into the static array, buf, and returns the actual length of the encoded character (a number between 1 and 4 for char[4] buffers and a number between 1 and 2 for wchar[2] buffers).

  1. size_t encode(char[4] buf, dchar c)
  2. size_t encode(wchar[2] buf, dchar c)
    @safe pure
    size_t
    encode
    (
    UseReplacementDchar useReplacementDchar = No.useReplacementDchar
    )
    (
    out wchar[2] buf
    ,
    dchar c
    )
  3. size_t encode(dchar[1] buf, dchar c)
  4. void encode(char[] str, dchar c)
  5. void encode(wchar[] str, dchar c)
  6. void encode(dchar[] str, dchar c)

Throws

UTFException if c is not a valid UTF code point.

Examples

import std.exception : assertThrown;
import std.typecons : Yes;

char[4] buf;

assert(encode(buf, '\u0000') == 1 && buf[0 .. 1] == "\u0000");
assert(encode(buf, '\u007F') == 1 && buf[0 .. 1] == "\u007F");
assert(encode(buf, '\u0080') == 2 && buf[0 .. 2] == "\u0080");
assert(encode(buf, '\uE000') == 3 && buf[0 .. 3] == "\uE000");
assert(encode(buf, 0xFFFE) == 3 && buf[0 .. 3] == "\xEF\xBF\xBE");
assertThrown!UTFException(encode(buf, cast(dchar) 0x110000));

encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000);
auto slice = buf[];
assert(slice.decodeFront == replacementDchar);
import std.exception : assertThrown;
import std.typecons : Yes;

wchar[2] buf;

assert(encode(buf, '\u0000') == 1 && buf[0 .. 1] == "\u0000");
assert(encode(buf, '\uD7FF') == 1 && buf[0 .. 1] == "\uD7FF");
assert(encode(buf, '\uE000') == 1 && buf[0 .. 1] == "\uE000");
assert(encode(buf, '\U00010000') == 2 && buf[0 .. 2] == "\U00010000");
assert(encode(buf, '\U0010FFFF') == 2 && buf[0 .. 2] == "\U0010FFFF");
assertThrown!UTFException(encode(buf, cast(dchar) 0xD800));

encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000);
auto slice = buf[];
assert(slice.decodeFront == replacementDchar);
import std.exception : assertThrown;
import std.typecons : Yes;

dchar[1] buf;

assert(encode(buf, '\u0000') == 1 && buf[0] == '\u0000');
assert(encode(buf, '\uD7FF') == 1 && buf[0] == '\uD7FF');
assert(encode(buf, '\uE000') == 1 && buf[0] == '\uE000');
assert(encode(buf, '\U0010FFFF') == 1 && buf[0] == '\U0010FFFF');
assertThrown!UTFException(encode(buf, cast(dchar) 0xD800));

encode!(Yes.useReplacementDchar)(buf, cast(dchar) 0x110000);
assert(buf[0] == replacementDchar);

Meta