2
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>.

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
  • Unless you consumed the original `u8` vector, nothing happened to it, `read_vectored` is a way of referencing the original `stream`. When `buffer` goes out of scope, it's like all the references are gone and you can use original data as always – Alexey S. Larionov Dec 16 '20 at 14:38
  • To read the data you iterate `buffer` and your can `Deref` each `IoSliceMut` into a slice of `u8` there are [plenty of methods](https://doc.rust-lang.org/std/io/struct.IoSliceMut.html#deref-methods) to read out of those. – Alexey S. Larionov Dec 16 '20 at 14:39
  • @AlexLarionov Thanks for the input, I'll look into it right now. – Michelangelo Dec 16 '20 at 14:44

1 Answers1

1

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

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98