我有以下代码:
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`'
}
Run Code Online (Sandbox Code Playgroud)
根据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);
Run Code Online (Sandbox Code Playgroud)
因此,该方法尝试读取 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");
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的 -.read_exact()
可能会失败。如果您不检查返回的内容,Result
您最终可能会得到一个包含无效内容的缓冲区。
归档时间: |
|
查看次数: |
68 次 |
最近记录: |