如何将字节向量流式传输到 BufWriter?

How to stream a vector of bytes to BufWriter?

我正在尝试使用 io::copy(&mut reader, &mut writer) 将字节流式传输到 TCP 服务器,但它给了我这个错误:the trait "std::io::Read" is not implemented for "Vec<{integer}>"。这里我有一个字节向量,这与我打开一个文件并将其转换为字节是一样的。我想将字节写入 BufWriter。我做错了什么?

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`

像这样使用 .as_slice() 对我有用:

pub fn connect() {
    if let Ok(stream) = TcpStream::connect("localhost:8080") {
        println!("Connection established!");
        let 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.as_slice(), &mut writer).expect("Failed to write to stream");
    } else {
        println!("Couldn't connect to the server")
    }
}

那是因为std::io::Read支持切片。

编译器在这里有点麻烦,Vec 没有实现 Read&[u8] do, you just have a get a slice 从 vec 创建可变引用之前:

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

另请参阅:

  • What are the differences between Rust's `String` and `str`?