Char Encode UTF-8 Scratch Buffer

Write chars into a fixed byte buffer with char::encode_utf8 and check that the returned length matches the UTF-8 width.

RustData Integrity

Code

snippet
fn main() {
    let samples = ['a', 'é', '世', '🎉'];

    for ch in samples {
        // char::encode_utf8 writes the UTF-8 bytes into the buffer
        let mut buffer = [0_u8; 4];
        let encoded = ch.encode_utf8(&mut buffer);
        println!("{ch:?} -> {} bytes {:?}", encoded.len(), encoded.as_bytes());
        println!("matches bytes: {}", encoded.as_bytes() == ch.to_string().as_bytes());
    }

    let total: usize = samples.iter().map(|ch| ch.len_utf8()).sum();
    println!("total utf8 bytes: {total}");
    println!("scratch width: {}", std::mem::size_of_val(&[0_u8; 4]));
}

How the snippet works

All of the logic lives in the function main.

The one repetition in this snippet is the loop for ch in samples.

Caveats

  • Nothing to install: the snippet stays inside the standard library.

Applying it

Entry signature: fn main()

The file announces its steps in the output: matches bytes:, total utf8 bytes:, scratch width:.

Statements that matter

let total: usize = samples.iter().map(|ch| ch.len_utf8()).sum();

Interactive Tools for This Topic

FAQ

What does Char Encode UTF-8 Scratch Buffer print when run?
The script runs standalone; its 3 labeled outputs include `matches bytes:`, `total utf8 bytes:`, `scratch width:`.