Idiomatic way to convert ascii array to string in Rust

Advertisements

From a byte array, I want to convert a slice to a string using the ASCII-encoding.
The solution

fn main() {
    let buffer: [u8; 9] = [255, 255, 255, 255, 77, 80, 81, 82, 83];
    let s = String::from_iter(buffer[5..9].iter().map(|v| { *v as char }));
    println!("{}", s);
    assert_eq!("PQRS", s);
}

does not seem to be idiomatic, and has a smell of poor performance.
Can we do better?
Without external crates?

>Solution :

A Rust string can be directly created from a UTF-8 encoded byte buffer like so:

fn main() {
    let buffer: [u8; 9] = [255, 255, 255, 255, 77, 80, 81, 82, 83];
    let s = std::str::from_utf8(&buffer[5..9]).expect("invalid utf-8 sequence");
    println!("{}", s);
    assert_eq!("PQRS", s);
}

The operation can fail if the input buffer contains an invalid UTF-8 sequence, however ASCII characters are valid UTF-8 so it works in this case.

Note that here, the type of s is &str, meaning that it is a reference to buffer. No allocation takes place here, so the operation is very efficient.

See it in action: Playground link

Leave a ReplyCancel reply