file - 为什么 std::io::Read 中的函数需要缓冲区?

标签 file io rust

为什么 std::io::Read 中的方法,即read_to_end , read_to_string ,和read_exact获取缓冲区而不是返回结果?当前返回值为 Result<usize> (或 Result<()> ),但是不能将其制成一个元组,也包含结果吗?

最佳答案

RFC 517讨论这些函数并描述了这些函数使用缓冲区而不是返回值的两个原因:

  • Performance. When it is known that reading will involve some large number of bytes, the buffer can be preallocated in advance.

  • "Atomicity" concerns. For read_to_end, it's possible to use this API to retain data collected so far even when a read fails in the middle. For read_to_string, this is not the case, because UTF-8 validity cannot be ensured in such cases; but if intermediate results are wanted, one can use read_to_end and convert to a String only at the end.

对于第一点,可以使用关联函数 String::with_capacity 预先分配字符串。 。向量存在一个非常相似的函数: Vec::with_capacity .

关于file - 为什么 std::io::Read 中的函数需要缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913851/

相关文章:

java - 如何在android中解压带有子目录的文件?

rust - 即使 NLL 打开,循环中的双可变借用错误也会发生

stream - 如何读取 rocket::Data 到整流罩内的字符串?

string - 如何连接Rust Vector的两个 `&str`类型元素并将其添加到零索引

javascript - 复制 XREExeF 并粘贴为文件快捷方式

访问程序文件时出现 Java fileNotFoundException

PHP读取和解析大文件?

file - 从网页访问服务器上的文件

c - 如何将输入/输出重定向放在新创建的 c shell 中?

java - 我收到错误 : "exception FileNotFoundException is never thrown in body of corresponding try statement" and cannot figure out why