【问题标题】:How do I interpret the signature of read_until and what is AsyncRead + BufRead in Tokio?如何解释 read_until 的签名以及 Tokio 中的 AsyncRead + BufRead 是什么?
【发布时间】:2019-05-31 23:52:25
【问题描述】:

我正在尝试理解 Rust 中的异步 I/O。以下代码基于 Katharina Fey 的 sn-p Jan 2019 talk 对我有用:

use futures::future::Future;
use std::io::BufReader;
use tokio::io::*;

fn main() {
    let reader = BufReader::new(tokio::io::stdin());
    let buffer = Vec::new();

    println!("Type something:");
    let fut = tokio::io::read_until(reader, b'\n', buffer)
        .and_then(move |(stdin, buffer)| {
            tokio::io::stdout()
                .write_all(&buffer)
                .map_err(|e| panic!(e))
        })
        .map_err(|e| panic!(e));

    tokio::run(fut);
}

在找到该代码之前,我尝试从 read_until 文档中找出它。

如何解释read_until 的签名以在上述代码示例中使用它?

pub fn read_until<A>(a: A, byte: u8, buf: Vec<u8>) -> ReadUntil<A> 
where
    A: AsyncRead + BufRead, 

具体来说,通过阅读文档,我如何知道传入and_then闭包的参数和预期结果是什么?

【问题讨论】:

    标签: rust rust-tokio


    【解决方案1】:

    and_then 的参数

    不幸的是,Rust 文档的标准布局使得未来很难遵循。

    从您链接的read_until 文档开始,我可以看到它返回ReadUntil&lt;A&gt;。我会点击那个去ReadUntil documentation

    这个返回值描述为:

    一个future,可用于轻松地将流的内容读入向量,直到到达分隔符。

    我希望它实现 Future 特征——我可以看到它确实实现了。我还假设未来解析为的Item 是某种向量,但我不知道具体是什么,所以我继续挖掘:

    1. 首先我在“Trait implementations”下查看并找到impl&lt;A&gt; Future for ReadUntil&lt;A&gt;
    2. 我点击了[+] 扩展器

    我终于看到了关联的type Item = (A, Vec&lt;u8&gt;)。这意味着它是一个Future,它将返回一对值:A,所以它可能会返回我传入的原始reader,以及一个字节向量。

    当未来解析到这个元组时,我想用and_then 附加一些额外的处理。这是Future 特征的一部分,因此我可以进一步向下滚动以找到该函数。

    fn and_then<F, B>(self, f: F) -> AndThen<Self, B, F>
    where
        F: FnOnce(Self::Item) -> B,
        B: IntoFuture<Error = Self::Error>,
        Self: Sized,
    

    函数and_then被记录为带有两个参数,但是self在使用点语法到函数时被编译器隐式传递,这告诉我们可以写read_until(A, '\n', buffer).and_then(...) .文档中的第二个参数f: F 成为我们代码中传递给and_then 的第一个参数。

    我可以看到f 是一个闭包,因为F 类型显示为FnOnce(Self::Item) -&gt; B(如果我单击指向Rust book closure chapter 的链接。

    传入的闭包fSelf::Item为参数。我刚刚发现Item(A, Vec&lt;u8&gt;),所以我希望写类似.and_then(|(reader, buffer)| { /* ... /* }) 的东西

    AsyncRead + BufRead

    这是对可以读取哪种类型的阅读器的限制。创建的BufReader实现BufRead

    Tokio 提供了an implementation of AsyncRead for BufReader,所以我们不必担心,我们可以继续使用BufReader

    【讨论】:

    • 太有帮助了!面包屑路径帮助我看到 [+] 并遵循参数参考语法。我建议进行编辑以澄清未来的读者,并测试我对闭包语法的理解——谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2022-06-20
    • 2013-10-13
    • 2020-05-28
    • 2012-06-19
    • 2020-12-04
    • 2012-06-24
    相关资源
    最近更新 更多