rust - read in chunks with async-std
问题描述
I'm trying to implement something similar to reading a file in Java with AsynchronousByteChannel like
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path...
channel.read(buffer,... new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result) {
...use buffer
}
i.e. read as much as OS gives, process, ask for more and so on. What would be the most straightforward way to achieve this with async_std?
解决方案
You can use the read
method of the async_std::io::Read
trait:
use async_std::prelude::*;
let mut reader = obtain_read_somehow();
let mut buf = [0; 4096]; // or however large you want it
// read returns a Poll<Result> so you have to handle the result
loop {
let byte_count = reader.read(&mut buf).await?;
if byte_count == 0 {
// 0 bytes read means we're done
break;
}
// call whatever handler function on the bytes read
handle(&buf[..byte_count]);
}
推荐阅读
- regex - .httaccess 中的正则表达式重定向以修复 404 错误页面
- python - 如何为 python Invoke 编写面向对象的任务?
- javascript - React Native 中的意外 Promise
- python - 使用 python 和 numpy 加载文件的最快方法是什么?
- python - 网格搜索的所有参数组合
- java - 在 jshell 中按 Tab 时出现“输入错误:java.io.IOException:资源暂时不可用”
- stock - 如何用 1 分钟的股价数据计算技术指标?
- javascript - 为什么我的 $_SESSION['user_login'] 没有更改为 true?
- primefaces - 如何从primefaces中的切换器获取切换值
- math - 二进制 2 的补码