Tha*_*yne 8 rust async-await rust-tokio
我有一个AsyncRead,想Stream<Item = tokio::io::Result<Bytes>>用 tokio 0.2 和 futures 0.3将它转换为一个。
我能做的最好的是:
use bytes::Bytes; // 0.4.12
use futures::stream::{Stream, TryStreamExt};; // 0.3.1
use tokio::{fs::File, io::Result}; // 0.2.4
use tokio_util::{BytesCodec, FramedRead}; // 0.2.0
#[tokio::main]
async fn main() -> Result<()> {
let file = File::open("some_file.txt").await?;
let stream = FramedRead::new(file, BytesCodec::new()).map_ok(|b| b.freeze());
fn_that_takes_stream(stream)
}
fn fn_that_takes_stream<S, O>(s: S) -> Result<()>
where
S: Stream<Item = Result<Bytes>>,
{
//...
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
似乎应该有一种更简单的方法;我很惊讶 Tokio 没有包含一个编解码器来获取一个流Bytes而不是,BytesMut或者没有一个扩展特性提供一种将 anAsyncRead转换为Stream. 我错过了什么吗?
小智 2
如果您可以使用 tokio 1.0 或 0.3,tokio-util 现在tokio_util::io::ReaderStream从 0.4 版本开始。
let file = File::open("some_file.txt").await?;
let stream = tokio_util::io::ReaderStream::new(file);
fn_that_takes_stream(stream)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2340 次 |
| 最近记录: |