2

I have a function with the following signature:

fn f(input: &mut Read, output: &mut Write)

And I try to pass Vec<u8>s as both input and output:

let mut in: Vec<u8> = Vec::new();
let mut out: Vec<u8> = Vec::new();
f(&mut in[..], &mut out);

The compiler seems to be fine with out, but I get errors about in:

error[E0277]: the trait bound `[u8]: std::io::Read` is not satisfied
--> src/crypto.rs:109:25
    |
109 |     f(&mut in[..], &mut out);     
            ^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `[u8]`
    |
    = help: the following implementations were found:
              <&'a [u8] as std::io::Read>
    = note: required for the cast to the object type `std::io::Read`

error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied
--> src/crypto.rs:109:25
    |
109 |     f(&mut in[..], &mut out);
    |       ^^^^^^^^^^^ `[u8]` does not have a constant size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[u8]`
    = note: required for the cast to the object type `std::io::Read`

What is the right way to pass a Vec into such interface?

Innot Kauker
  • 1,333
  • 1
  • 18
  • 30
  • @Hellseher just tried - it doest't want to take an iterator instead of &[u8] needed for conversion to Read. – Innot Kauker Sep 02 '18 at 21:42
  • 1
    Potential duplicate of ["How to create an in-memory object that can be used as a Reader or Writer in Rust?"](https://stackoverflow.com/questions/41069865/how-to-create-an-in-memory-object-that-can-be-used-as-a-reader-or-writer-in-rust). – Lukas Kalbertodt Sep 03 '18 at 00:23
  • Please try to create a [MCVE](https://stackoverflow.com/help/mcve) next time. It will help you and us to solve your problem easier. – hellow Sep 03 '18 at 06:17
  • `in` is a reserved keyword and cannot be used as a variable name. – hellow Sep 03 '18 at 06:17

1 Answers1

4

Your example is fairly easy solveable, just borrow the slice!

use std::io::{copy, Read, Write};

fn f(input: &mut Read, output: &mut Write) {
    copy(input, output).unwrap();
}

fn main() {
    let i = vec![0u8, 1, 2, 3];
    let mut o = Vec::new();
    f(&mut &i[..], &mut o);
    println!("{:?} {:?}", i, o);
}

Although I don't know, why you do i[..], because read does not alter the reader in this specific case (note that it can alter the reader, because it takes a mutable reference, which can (e.g. on sockets) consume the bytes it reads).

You could also just write

f(&mut i.as_slice(), &mut o);

if you are not compelled to clone the vec.

hellow
  • 12,430
  • 7
  • 56
  • 79