How to print u8 vector as a string?

Here is my code:

let mut altbuf: Vec<u8> = Vec::new();

// Stuff here...

match stream.read_byte() {
    Ok(d) => altbuf.push(d),
    Err(e) => { println!("Error: {}", e); doneflag = true; }
}

for x in altbuf.iter() {
    println!("{}", x);
}

The code prints u8 bytes that are correct, but I can’t understand how much I can convert a vector of pure u8 bytes to a string? The only answer to a similar stack overflow question is that you are working with a vector like & [u8].

+4
source share
2 answers

If you look at the Stringdocumentation , you can use several methods. There String::from_utf8, which accepts Vec<u8>, as well String::from_utf8_lossyas which accepts &[u8].

, a Vec<T> [T]. , Vec<u8>, &[u8], , (.. &*some_vec). , &[T] Vec<T> ( , , Deref).

+5

altbuf u8, , :

println!("{:?}", altbuf);

, , - :

let rebuilt: Vec<u8>;

unsafe {
    ret = proc_pidpath(pid, buffer_ptr, buffer_size);
    rebuilt = Vec::from_raw_parts(buffer_ptr as *mut u8, ret as usize, buffer_size as usize);
};

println!("Returned a {} byte string", ret);
println!("{:?}", rebuilt);

u8 , C, FFI, , , UTF-8.

, :

49

[47, 85, 115, 101, 114, 115, 47, 97, 110, 100, 114, 101, 119, 47, 46, 114, 98, 101, 110, 118, 47, 118, 101, 114, 115, 105, 111, 110, 115, 47, 49, 46, 57, 46, 51, 45, 112, 51, 57, 50, 47, 98, 105, 110, 47, 114, 117, 98, 121].

( , ..) {}.

String, String::from_utf8(rebuilt), .

match String::from_utf8(rebuilt) {
    Ok(path) => Ok(path),
    Err(e) => Err(format!("Invalid UTF-8 sequence: {}", e)),
}
0

All Articles