简体   繁体   中英

Idiomatic way to convert ascii array to string in Rust

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM