Function mutf8::encode[][src]

pub fn encode(str: &str) -> Cow<'_, [u8]>

Converts a string slice to MUTF-8 bytes.

If the string slice’s representation in MUTF-8 would be identical to its present UTF-8 representation, this function is functionally no different than (&str).as_bytes(); this means that encode() does not need to perform any further operations and doesn’t need to allocate any additional memory.

If the string slice’s representation in UTF-8 is not equivalent in MUTF-8, encode() encodes the string slice to its MUTF-8 representation as a slice of bytes.

use std::borrow::Cow;

let str = "Hello, world!";
// Since 'str' contains valid UTF-8 and MUTF-8 data, 'mutf8::encode' can
// encode data without allocating memory.
assert_eq!(mutf8::encode(str), Cow::Borrowed(str.as_bytes()));

let str = "\u{10401}";
let mutf8_data = Cow::Borrowed(&[0xED, 0xA0, 0x81, 0xED, 0xB0, 0x81]);
// 'str' is a 4-byte UTF-8 character, which becomes the 6-byte MUTF-8
// surrogate pair 'mutf8_data'.
assert_eq!(mutf8::encode(str), mutf8_data);

let str = "\0";
let mutf8_data = Cow::Borrowed(&[0xC0, 0x80]);
// 'str' is a null character which becomes a two byte representation in
// MUTF-8.
assert_eq!(mutf8::encode(str), mutf8_data);