如何从流中读取特定数量的字节? [英] How to read a specific number of bytes from a stream?
问题描述
我有一个带有 BufStream
的结构,其中 T: Read+Write
.BufStream
可以是 TcpStream
并且我想从中读取 n 个字节.预定义缓冲区中的字节数不是固定的,但我有一个字符串/流,指示接下来要读取的字节数.
I have a struct with a BufStream<T>
where T: Read+Write
.
The BufStream
can be a TcpStream
and I'd like to read n bytes from it.
Not a fixed amount of bytes in a predefined buffer, but I have a string/stream which indicates the number of bytes to read next.
有什么好的方法可以做到这一点吗?
Is there a nice way to do that?
推荐答案
从 Rust 1.6 开始,Read::read_exact
可用于执行此操作.如果 bytes_to_read
是您需要读取的字节数,可能在运行时确定,而 reader
是要从中读取的流:
Since Rust 1.6, Read::read_exact
can be used to do this. If bytes_to_read
is the number of bytes you need to read, possibly determined at runtime, and reader
is the stream to read from:
let mut buf = vec![0u8; bytes_to_read];
reader.read_exact(&mut buf)?;
read_exact
文档中我不清楚的部分是目标缓冲区可以是动态分配的 Vec
.
The part that wasn't clear to me from the read_exact
documentation was that the target buffer can be a dynamically-allocated Vec
.
感谢 Rust Gitter 社区为我指出这个解决方案.
Thanks to the Rust Gitter community for pointing me to this solution.
这篇关于如何从流中读取特定数量的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!