为什么Read::read_exact不从Vec::with_capacity()填充缓冲区?



我有以下代码:

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。这是怎么呢

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,您可能最终得到一个包含无效内容的缓冲区。

最新更新