1

我有以下代码:

use std::io::{Cursor, BufReader, Read};

fn main() {
    let string = String::from("Cello");
    let bytes = string.as_bytes();
    let cursor = Cursor::new(bytes);
    let mut reader = BufReader::new(cursor);
    let mut buf: Vec<u8> = Vec::with_capacity(4);
    assert_eq!(4, buf.capacity());
    reader.read_exact(&mut buf);
    assert_eq!(4, buf.len()); //thread 'main' panicked at 'assertion failed: `(left == right)`
                              //left: `4`, right: `0`'
}

根据std::io::read_exact的文档,它将“读取填充 buf 所需的确切字节数”。但在这种情况下,尽管有 4 个字节的容量,但没有字节被读入 vec。这是怎么回事?

4

1 回答 1

6

read_exact()方法需要一个&mut [u8]切片 - 即它需要知道缓冲区长度。但是您正在传递一个长度为 0 的切片(缓冲区的容量与其长度不同):

// capacity = 4
// length = 0
let mut buf: Vec<u8> = Vec::with_capacity(4);

// the &mut [u8] slice has a length of 0
reader.read_exact(&mut buf);

结果,该方法尝试读取 0 个字节。为了解决这个问题,您必须传递一个非零长度缓冲区:

// capacity = 4
// length = 4
let mut buf: Vec<u8> = vec![0; 4];

// the &mut [u8] slice has a length of 4
reader.read_exact(&mut buf).expect("read failed");

最后但并非最不重要的 -.read_exact()可能会失败。如果您不检查返回Result的内容,您最终可能会得到一个包含无效内容的缓冲区。

于 2021-08-30T07:05:07.080 回答