How to print a piece of u8 as text if I don't need a specific encoding?

When printing an array u8in Rust using println!("{:?}", some_u8_slice);this, it prints numerical values ​​(as it should be).

What is the most direct way to format characters as they are in a string without assuming any particular encoding.

Something like iterating over a byte string and writing each character in stdout(without too much trouble).

Can this be done using Rusts format!?

Otherwise, the most convenient way to print a piece of u8?

+1
source share
3 answers

, , , std::ascii::escape_default. , ASCII, , . , Unicode, UTF-8, :

use std::ascii::escape_default;
use std::str;

fn show(bs: &[u8]) -> String {
    let mut visible = String::new();
    for &b in bs {
        let part: Vec<u8> = escape_default(b).collect();
        visible.push_str(str::from_utf8(&part).unwrap());
    }
    visible
}

fn main() {
    let bytes = b"foo\xE2\x98\x83bar\xFFbaz";
    println!("{}", show(bytes));
}

: foo\xe2\x98\x83bar\xffbaz

, . UTF-8, Unicode , Unicode UTF-8:

fn show(bs: &[u8]) -> String {
    String::from_utf8_lossy(bs).into_owned()
}

fn main() {
    let bytes = b"foo\xE2\x98\x83bar\xFFbaz";
    println!("{}", show(bytes));
}

: foo☃bar baz

+5

- stdout().write_all(some_u8_slice). , . , .

, , UTF-8 ( UTF-8, ASCII), :

use std::str;

fn main() {
    let some_utf8_slice = &[104, 101, 0xFF, 108, 111];
    if let Ok(s) = str::from_utf8(some_utf8_slice) {
        println!("{}", s);
    }
}

, UTF-8 .

+6

, stdout, , , :

let out = std::io::stdout();
out.write_all(slice)?;
out.flush()?;

flush , write_all .

+3
source

Source: https://habr.com/ru/post/1665672/


All Articles