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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Unicode Code Point ExplorerExplore Unicode code points of any text input. View each character with its code point, UTF-8 byte sequence, and official name for internationalization debugging.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.