Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to stream a vector of bytes to BufWriter?

I’m trying to stream bytes to a tcp server by using io::copy(&mut reader, &mut writer), but it gives me this error: the trait "std::io::Read" is not implemented for "Vec<{integer}>". Here I have a vector of bytes which would be the same as me opening a file and converting it to bytes. I want to write the bytes to the BufWriter. What am I doing wrong?

use std::io;
use std::net::TcpStream;
use std::io::BufWriter;

pub fn connect() {
    if let Ok(stream) = TcpStream::connect("localhost:8080") {
        println!("Connection established!");
        let mut reader = vec![
            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 70, 0, 0, 0, 70,
        ];
        let mut writer = BufWriter::new(&stream);
        io::copy(&mut reader, &mut writer).expect("Failed to write to stream");
    } else {
        println!("Couldn't connect to the server")
    }
}
error[E0277]: the trait bound `Vec<{integer}>: std::io::Read` is not satisfied
  --> src/lib.rs:12:31
   |
12 |         io::copy(&mut reader, &mut writer).expect("Failed to write to stream");
   |         --------              ^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `Vec<{integer}>`
   |         |
   |         required by a bound introduced by this call
   |
note: required by a bound in `std::io::copy`

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the compiler have a little trouble here, Vec doesn’t implement Read but &[u8] do, you just have a get a slice from the vec before create a mutable reference:

copy(&mut reader.as_slice(), &mut writer).expect("Failed to write to stream");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading