简体   繁体   中英

How to convert IoSliceMut array into Vec<u8>?

let mut buffer = Vec::with_capacity(10);
stream.read_vectored(&mut buffer);

The code above turns buffer into an IoSliceMut vector, but I don't know how to read from this vector or how to convert it back into a Vec<u8> .

You don't have to convert the IoSliceMut structs back to u8 arrays, the read_vectored writes the bytes directly into the array buffers since you pass them by mutable references. You can just use the buffers afterward and they will have the data written in them. Example:

use std::io::IoSliceMut;
use std::io::Read;

fn main() {
    let mut buffer: [u8; 10] = [0; 10];
    let mut io_slices = [IoSliceMut::new(&mut buffer)];
    let mut data: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    data.read_vectored(&mut io_slices);
    dbg!(data, buffer); // data is now in buffer
}

playground

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