rust异步编程:futures-rs之futures-util

概述

futures-util算得上是巨无霸,它整个futures-rs内容最多的一个子类库,它依赖futures-core 、futures-task 、futures-channel、futures-io、futures-sink、futures-macro、tokio-io 等类库。不过核心的还是这几个Trait:FutureExt、TryFutureExt、StreamExt、TryStreamExt、SinkExt、AsyncReadExt,、AsyncWriteExt、AsyncSeekExt、 AsyncBufReadExt,所有方法它们都提供了默认实现。

目录结构如下( 只列出第一层级,子目录和文件太多,未列出)

├── async_await //这个模块包含许多函数和组合器,用于处理`async` /`await`代码。
├── compat //Futures 0.1 / 0.3 兼容垫片,仅在`compat`feature启用时该模块才可用。
├── fns.rs
├── future //该模块包含许多用于处理`Future`的函数,包括[`FutureExt`]trait和[`TryFutureExt`]trait,该trait继承了Future
├── io //仅在`io` and `std` features启用时该模块才可用,主要包括“ AsyncReadExt”,“ AsyncWriteExt”,“ AsyncSeekExt”和“ AsyncBufReadExt”,它们分别继承了AsyncRead,AsyncWrite,AsyncSeek,和`AsyncBufRead`
├── lib.rs
├── lock //仅在`std` or `alloc` feature启用时该模块才可用,Futures-powered同步原语
├── never.rs
├── sink //仅在 `sink` feature启用时该模块才可用,包含许多用于处理“Sink”的函数,包括“ SinkExt” trait,该trait继承了“Sink”trait。
├── stream //该模块包含许多用于处理Stream的函数,包括[StreamExt`]trait和[`TryStreamExt`]trait,分别继承了Stream、TryStream
└── task// 包含[`SpawnExt`] trait和[`LocalSpawnExt`] trait,分别继承了Spawn、LocalSpawn

对外暴露的api

pub mod future;
pub use crate::future::{
    
    FutureExt, TryFutureExt};

pub mod stream;
pub use crate::stream::{
    
    StreamExt, TryStreamExt};

#[cfg(feature = "sink")]
pub mod sink;
#[cfg(feature = "sink")]
pub use crate::sink::SinkExt;

pub mod task;

pub mod never;

#[cfg(feature = "compat")]
pub mod compat;

#[cfg(feature = "io")]
#[cfg(feature = "std")]
pub mod io;
#[cfg(feature = "io")]
#[cfg(feature = "std")]
pub use crate::io::{
    
    AsyncReadExt, AsyncWriteExt, AsyncSeekExt, AsyncBufReadExt};

mod fns;

cfg_target_has_atomic! {
    
    
    #[cfg(feature = "alloc")]
    pub mod lock;
}

FutureExt

所有的Future都实现了FutureExt


impl<T: ?Sized> FutureExt for T where T: Future {
    
    }

///`Future`的扩展trait,提供了多种便捷适配器。
pub trait FutureExt: Future {
    
    
    ///
    /// 类似 `Option::map` or `Iterator::map` 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    ///
    /// let future = async { 1 };
    /// let new_future = future.map(|x| x + 3);
    /// assert_eq!(new_future.await, 4);
    /// # });
    /// ```
    fn map<U, F>(self, f: F) -> Map<Self, F>
    where
        F: FnOnce(Self::Output) -> U,
        Self: Sized,
    {
    
    
        assert_future::<U, _>(Map::new(self, f))
    }

    /// 将此Future的输出映射到其他类型,返回新的Future
    fn map_into<U>(self) -> MapInto<Self, U>
    where
        Self::Output: Into<U>,
        Self: Sized,
    {
    
    
        assert_future::<U, _>(MapInto::new(self))
    }

    /// 链式调用
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    ///
    /// let future_of_1 = async { 1 };
    /// let future_of_4 = future_of_1.then(|x| async move { x + 3 });
    /// assert_eq!(future_of_4.await, 4);
    /// # });
    /// ```
    fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
    where
        F: FnOnce(Self::Output) -> Fut,
        Fut: Future,
        Self: Sized,
    {
    
    
        assert_future::<Fut::Output, _>(Then::new(self, f))
    }

   
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    ///
    /// let x = 6;
    /// let future = if x < 10 {
    
    
    ///     async { true }.left_future()
    /// } else {
    
    
    ///     async { false }.right_future()
    /// };
    ///
    /// assert_eq!(future.await, true);
    /// # });
    /// ```
    fn left_future<B>(self) -> Either<Self, B>
    where
        B: Future<Output = Self::Output>,
        Self: Sized,
    {
    
    
        Either::Left(self)
    }

    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    ///
    /// let x = 6;
    /// let future = if x > 10 {
    
    
    ///     async { true }.left_future()
    /// } else {
    
    
    ///     async { false }.right_future()
    /// };
    ///
    /// assert_eq!(future.await, false);
    /// # });
    /// ```
    fn right_future<A>(self) -> Either<A, Self>
    where
        A: Future<Output = Self::Output>,
        Self: Sized,
    {
    
    
        Either::Right(self)
    }

    /// 将future转换成stream
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    /// use futures::stream::StreamExt;
    ///
    /// let future = async { 17 };
    /// let stream = future.into_stream();
    /// let collected: Vec<_> = stream.collect().await;
    /// assert_eq!(collected, vec![17]);
    /// # });
    /// ```
    fn into_stream(self) -> IntoStream<Self>
    where
        Self: Sized,
    {
    
    
        IntoStream::new(self)
    }

    /// 当此future的输出本身是另一个future时,则展开该future的执行。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    ///
    /// let nested_future = async { async { 1 } };
    /// let future = nested_future.flatten();
    /// assert_eq!(future.await, 1);
    /// # });
    /// ```
    fn flatten(self) -> Flatten<Self>
    where
        Self::Output: Future,
        Self: Sized,
    {
    
    
        let f = Flatten::new(self);
        assert_future::<<<Self as Future>::Output as Future>::Output, _>(f)
    }

    /// 当此future的成功结果是一个流时,展开该future的执行。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream_items = vec![17, 18, 19];
    /// let future_of_a_stream = async { stream::iter(stream_items) };
    ///
    /// let stream = future_of_a_stream.flatten_stream();
    /// let list: Vec<_> = stream.collect().await;
    /// assert_eq!(list, vec![17, 18, 19]);
    /// # });
    /// ```
    fn flatten_stream(self) -> FlattenStream<Self>
    where
        Self::Output: Stream,
        Self: Sized,
    {
    
    
        FlattenStream::new(self)
    }

    /// fuse一个future,使得一旦完成`poll`再也不会被调用。此方法可用于将任何“Future”变成“FusedFuture”。
    fn fuse(self) -> Fuse<Self>
    where
        Self: Sized,
    {
    
    
        let f = Fuse::new(self);
        assert_future::<Self::Output, _>(f)
    }

    /// 在传递future之前,对future的输出进行处理。
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    ///
    /// let future = async { 1 };
    /// let new_future = future.inspect(|&x| println!("about to resolve: {}", x));
    /// assert_eq!(new_future.await, 1);
    /// # });
    /// ```
    fn inspect<F>(self, f: F) -> Inspect<Self, F>
    where
        F: FnOnce(&Self::Output),
        Self: Sized,
    {
    
    
        assert_future::<Self::Output, _>(Inspect::new(self, f))
    }

    ///  polling future的时候消除panic,发生panic时程序可以捕获panic原因不会退出
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::{self, FutureExt, Ready};
    ///
    /// let future = future::ready(2);
    /// assert!(future.catch_unwind().await.is_ok());
    ///
    /// let future = future::lazy(|_| -> Ready<i32> {
    
    
    ///     unimplemented!()
    /// });
    /// assert!(future.catch_unwind().await.is_err());
    /// # });
    /// ```
    #[cfg(feature = "std")]
    fn catch_unwind(self) -> CatchUnwind<Self>
    where
        Self: Sized + ::std::panic::UnwindSafe,
    {
    
    
        CatchUnwind::new(self)
    }

    /// 为此future创建一个可克隆的句柄,其中所有句柄都将解析为相同的结果。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    ///
    /// let future = async { 6 };
    /// let shared1 = future.shared();
    /// let shared2 = shared1.clone();
    ///
    /// assert_eq!(6, shared1.await);
    /// assert_eq!(6, shared2.await);
    /// # });
    /// ```
    ///
    /// ```
    /// 注意,与大多数示例不同,它是在同步函数的上下文中编写的,目的是更好地说明“共享”组合器的跨线程特性。
    ///
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::FutureExt;
    /// use futures::executor::block_on;
    /// use std::thread;
    ///
    /// let future = async { 6 };
    /// let shared1 = future.shared();
    /// let shared2 = shared1.clone();
    /// let join_handle = thread::spawn(move || {
    
    
    ///     assert_eq!(6, block_on(shared2));
    /// });
    /// assert_eq!(6, shared1.await);
    /// join_handle.join().unwrap();
    /// # });
    /// ```
    #[cfg(feature = "std")]
    fn shared(self) -> Shared<Self>
    where
        Self: Sized,
        Self::Output: Clone,
    {
    
    
        Shared::new(self)
    }

    /// ?
    #[cfg(feature = "channel")]
    #[cfg(feature = "std")]
    fn remote_handle(self) -> (Remote<Self>, RemoteHandle<Self::Output>)
    where
        Self: Sized,
    {
    
    
        remote_handle::remote_handle(self)
    }

    ///  将future包装在Box里, 并pin住它
    #[cfg(feature = "alloc")]
    fn boxed<'a>(self) -> BoxFuture<'a, Self::Output>
    where
        Self: Sized + Send + 'a,
    {
    
    
        Box::pin(self)
    }

    /// 将future包装在Box里, 并pin住它,类似boxed(没有send)
    #[cfg(feature = "alloc")]
    fn boxed_local<'a>(self) -> LocalBoxFuture<'a, Self::Output>
    where
        Self: Sized + 'a,
    {
    
    
        Box::pin(self)
    }

    /// 转换 [`Future<Output = T>`](Future) 到
    /// [`TryFuture<Ok = T, Error = ()`>](futures_core::future::TryFuture).
    fn unit_error(self) -> UnitError<Self>
    where
        Self: Sized,
    {
    
    
        UnitError::new(self)
    }

    /// 转换[`Future<Output = T>`](Future) 到
    /// [`TryFuture<Ok = T, Error = Never`>](futures_core::future::TryFuture).
    fn never_error(self) -> NeverError<Self>
    where
        Self: Sized,
    {
    
    
        NeverError::new(self)
    }

    /// 在`Unpin`future类型上调用`Future :: poll`的快捷方式。
    fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
    where
        Self: Unpin,
    {
    
    
        Pin::new(self).poll(cx)
    }

    /// 评估并消费futre,如果在首次调用`Future :: poll'之后future已准备就绪,则返回结果输出。
    ///
    /// # Examples
    ///
    /// ```
    /// # use futures::prelude::*;
    /// use futures::{future::ready, future::pending};
    /// let future_ready = ready("foobar");
    /// let future_pending = pending::<&'static str>();
    ///
    /// assert_eq!(future_ready.now_or_never(), Some("foobar"));
    /// assert_eq!(future_pending.now_or_never(), None);
    /// ```
    ///
    /// 如果确切知道futre应该总是立即完成并且永远不要返回`Poll :: Pending`,可以将此方法与`expect()`结合使用:
    ///
    /// ```
    /// # use futures::{prelude::*, future::ready};
    /// let future_ready = ready("foobar");
    ///
    /// assert_eq!(future_ready.now_or_never().expect("Future not ready"), "foobar");
    /// ```
    fn now_or_never(mut self) -> Option<Self::Output>
    where
        Self: Sized,
    {
    
    
        let noop_waker = crate::task::noop_waker();
        let mut cx = Context::from_waker(&noop_waker);

        let pinned = unsafe {
    
     Pin::new_unchecked(&mut self) };

        match pinned.poll(&mut cx) {
    
    
            Poll::Ready(x) => Some(x),
            _ => None,
        }
    }
}

TryFutureExt

所有TryFuture都实现TryFutureExt

impl<Fut: ?Sized + TryFuture> TryFutureExt for Fut {
    
    }

/// Adapters specific to [`Result`]-returning futures
pub trait TryFutureExt: TryFuture {
    
    
    /// 当此future的success结果为[`Sink`]时,将使该future的执行平展
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::{Future, TryFutureExt};
    /// use futures::sink::Sink;
    /// # use futures::channel::mpsc::{self, SendError};
    /// # type T = i32;
    /// # type E = SendError;
    ///
    /// fn make_sink_async() -> impl Future<Output = Result<
    ///     impl Sink<T, Error = E>,
    ///     E,
    /// >> { // ... }
    /// # let (tx, _rx) = mpsc::unbounded::<i32>();
    /// # futures::future::ready(Ok(tx))
    /// # }
    /// fn take_sink(sink: impl Sink<T, Error = E>) { /* ... */ }
    ///
    /// let fut = make_sink_async();
    /// take_sink(fut.flatten_sink())
    /// ```
    #[cfg(feature = "sink")]
    fn flatten_sink<Item>(self) -> FlattenSink<Self, Self::Ok>
    where
        Self::Ok: Sink<Item, Error = Self::Error>,
        Self: Sized,
    {
    
    
        FlattenSink::new(self)
    }

    /// 将此future的success值映射为其他值。
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Ok::<i32, i32>(1) };
    /// let future = future.map_ok(|x| x + 3);
    /// assert_eq!(future.await, Ok(4));
    /// # });
    /// ```
    ///
    /// 发生错误时不会调用 [`map_ok`](TryFutureExt::map_ok)
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Err::<i32, i32>(1) };
    /// let future = future.map_ok(|x| x + 3);
    /// assert_eq!(future.await, Err(1));
    /// # });
    /// ```
    fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
    where
        F: FnOnce(Self::Ok) -> T,
        Self: Sized,
    {
    
    
        assert_future::<Result<T, Self::Error>, _>(MapOk::new(self, f))
    }

    /// 将此Future的sucdess值映射到其他值,并允许进行错误处理以产生相同的类型。
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Ok::<i32, i32>(5) };
    /// let future = future.map_ok_or_else(|x| x * 2, |x| x + 3);
    /// assert_eq!(future.await, 8);
    /// 
    /// let future = async { Err::<i32, i32>(5) };
    /// let future = future.map_ok_or_else(|x| x * 2, |x| x + 3);
    /// assert_eq!(future.await, 10);
    /// # });
    /// ```
    /// 
    fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E>
    where
        F: FnOnce(Self::Ok) -> T,
        E: FnOnce(Self::Error) -> T,
        Self: Sized,
    {
    
    
        assert_future::<T, _>(MapOkOrElse::new(self, f, e))
    }

    ///将此Future的error值映射到其他值
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Err::<i32, i32>(1) };
    /// let future = future.map_err(|x| x + 3);
    /// assert_eq!(future.await, Err(4));
    /// # });
    /// ```
    ///
    /// sueccess时不会调用 [`map_err`](TryFutureExt::map_err)
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Ok::<i32, i32>(1) };
    /// let future = future.map_err(|x| x + 3);
    /// assert_eq!(future.await, Ok(1));
    /// # });
    /// ```
    fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
    where
        F: FnOnce(Self::Error) -> E,
        Self: Sized,
    {
    
    
        assert_future::<Result<Self::Ok, E>, _>(MapErr::new(self, f))
    }

    /// 映射这个future的 [`Error`](TryFuture::Error) 到新的trait [`Into`](std::convert::Into)
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future_err_u8 = async { Err::<(), u8>(1) };
    /// let future_err_i32 = future_err_u8.err_into::<i32>();
    /// # });
    /// ```
    fn err_into<E>(self) -> ErrInto<Self, E>
    where
        Self: Sized,
        Self::Error: Into<E>,
    {
    
    
        assert_future::<Result<Self::Ok, E>, _>(ErrInto::new(self))
    }

    /// 映射这个future的 [`Ok`](TryFuture::Ok)到一个新的trait [`Into`](std::convert::Into)
    fn ok_into<U>(self) -> OkInto<Self, U>
    where
        Self: Sized,
        Self::Ok: Into<U>,
    {
    
    
        assert_future::<Result<U, Self::Error>, _>(OkInto::new(self))
    }

    /// 成功解决此问题后,执行另一个future。success值将传递给闭包以创建此后续future。 
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Ok::<i32, i32>(1) };
    /// let future = future.and_then(|x| async move { Ok::<i32, i32>(x + 3) });
    /// assert_eq!(future.await, Ok(4));
    /// # });
    /// ```
    ///
    /// 当发生error时不会调用 [`and_then`](TryFutureExt::and_then) 
    /// effect:
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Err::<i32, i32>(1) };
    /// let future = future.and_then(|x| async move { Err::<i32, i32>(x + 3) });
    /// assert_eq!(future.await, Err(1));
    /// # });
    /// ```
    fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
    where
        F: FnOnce(Self::Ok) -> Fut,
        Fut: TryFuture<Error = Self::Error>,
        Self: Sized,
    {
    
    
        assert_future::<Result<Fut::Ok, Fut::Error>, _>(AndThen::new(self, f))
    }

    /// 如果解决了错误,则执行另一个future。错误值将传递到闭包以创建此后续future。 
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Err::<i32, i32>(1) };
    /// let future = future.or_else(|x| async move { Err::<i32, i32>(x + 3) });
    /// assert_eq!(future.await, Err(4));
    /// # });
    /// ```
    ///
    /// 调用 [`or_else`](TryFutureExt::or_else) 在success的future没有任何影响
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Ok::<i32, i32>(1) };
    /// let future = future.or_else(|x| async move { Ok::<i32, i32>(x + 3) });
    /// assert_eq!(future.await, Ok(1));
    /// # });
    /// ```
    fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
    where
        F: FnOnce(Self::Error) -> Fut,
        Fut: TryFuture<Ok = Self::Ok>,
        Self: Sized,
    {
    
    
        assert_future::<Result<Fut::Ok, Fut::Error>, _>(OrElse::new(self, f))
    }

    /// 在传递success之前,要对future的success值做处理。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::TryFutureExt;
    ///
    /// let future = async { Ok::<_, ()>(1) };
    /// let new_future = future.inspect_ok(|&x| println!("about to resolve: {}", x));
    /// assert_eq!(new_future.await, Ok(1));
    /// # });
    /// ```
    fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
    where
        F: FnOnce(&Self::Ok),
        Self: Sized,
    {
    
    
        assert_future::<Result<Self::Ok, Self::Error>, _>(InspectOk::new(self, f))
    }

    /// 在传递future之前,使用future的错误值进行操作。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::TryFutureExt;
    ///
    /// let future = async { Err::<(), _>(1) };
    /// let new_future = future.inspect_err(|&x| println!("about to error: {}", x));
    /// assert_eq!(new_future.await, Err(1));
    /// # });
    /// ```
    fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
    where
        F: FnOnce(&Self::Error),
        Self: Sized,
    {
    
    
        assert_future::<Result<Self::Ok, Self::Error>, _>(InspectErr::new(self, f))
    }

    /// 当此future的成功结果是另一个future时,则平展该future的执行。
    ///
    /// This is equivalent to `future.and_then(|x| x)`.
    fn try_flatten(self) -> TryFlatten<Self, Self::Ok>
    where
        Self::Ok: TryFuture<Error = Self::Error>,
        Self: Sized,
    {
    
    
        TryFlatten::new(self)
    }

    /// 当此future的成功结果是一个流时,平展该future的执行
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future::TryFutureExt;
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let stream_items = vec![17, 18, 19].into_iter().map(Ok);
    /// let future_of_a_stream = async { Ok::<_, ()>(stream::iter(stream_items)) };
    ///
    /// let stream = future_of_a_stream.try_flatten_stream();
    /// let list = stream.try_collect::<Vec<_>>().await;
    /// assert_eq!(list, Ok(vec![17, 18, 19]));
    /// # });
    /// ```
    fn try_flatten_stream(self) -> TryFlattenStream<Self>
    where
        Self::Ok: TryStream<Error = Self::Error>,
        Self: Sized,
    {
    
    
        TryFlattenStream::new(self)
    }

   /// 解包此future的输出,以该future的[`Ok`](TryFuture :: Ok)类型作为其[`Output`](std :: future :: Future :: Output)类型生成一个future。
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::TryFutureExt;
    ///
    /// # futures::executor::block_on(async {
    
    
    /// let future = async { Err::<(), &str>("Boom!") };
    /// let future = future.unwrap_or_else(|_| ());
    /// assert_eq!(future.await, ());
    /// # });
    /// ```
    fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F>
    where
        Self: Sized,
        F: FnOnce(Self::Error) -> Self::Ok,
    {
    
    
        assert_future::<Self::Ok, _>(UnwrapOrElse::new(self, f))
    }

    /// 将[`TryFuture`]包装成与Futures 0.1 future definitons兼容类型。需要启用“ compat”功能。
    #[cfg(feature = "compat")]
    fn compat(self) -> Compat<Self>
    where
        Self: Sized + Unpin,
    {
    
    
        Compat::new(self)
    }

    /// 将[`TryFuture`] 包装成实现了[`Future`](std::future::Future)的类型
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future::{Future, TryFuture, TryFutureExt};
    ///
    /// # type T = i32;
    /// # type E = ();
    /// fn make_try_future() -> impl TryFuture<Ok = T, Error = E> { // ... }
    /// # async { Ok::<i32, ()>(1) }
    /// # }
    /// fn take_future(future: impl Future<Output = Result<T, E>>) { /* ... */ }
    ///
    /// take_future(make_try_future().into_future());
    /// ```
    fn into_future(self) -> IntoFuture<Self>
    where
        Self: Sized,
    {
    
    
        IntoFuture::new(self)
    }

    /// A convenience method for calling [`TryFuture::try_poll`] on [`Unpin`]
    /// future types.
    fn try_poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<Self::Ok, Self::Error>>
    where
        Self: Unpin,
    {
    
    
        Pin::new(self).try_poll(cx)
    }
}

StreamExt

所有的Stream都实现了StreamExt


impl<T: ?Sized> StreamExt for T where T: Stream {
    
    }

/// `Stream`的扩展trait,它提供了多种快捷便利组合函数。
pub trait StreamExt: Stream {
    
    
    /// 返回一个新的Future,像迭代器那样迭代
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let mut stream = stream::iter(1..=3);
    ///
    /// assert_eq!(stream.next().await, Some(1));
    /// assert_eq!(stream.next().await, Some(2));
    /// assert_eq!(stream.next().await, Some(3));
    /// assert_eq!(stream.next().await, None);
    /// # });
    /// ```
    fn next(&mut self) -> Next<'_, Self>
    where
        Self: Unpin,
    {
    
    
        Next::new(self)
    }

    /// 将此流转换为`(next_item,tail_of_stream)`的future。如果流终止,则下一项为[`None`]。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=3);
    ///
    /// let (item, stream) = stream.into_future().await;
    /// assert_eq!(Some(1), item);
    ///
    /// let (item, stream) = stream.into_future().await;
    /// assert_eq!(Some(2), item);
    /// # });
    /// ```
    fn into_future(self) -> StreamFuture<Self>
    where
        Self: Sized + Unpin,
    {
    
    
        StreamFuture::new(self)
    }

    /// 将此流的item映射到其他类型,并返回resulting类型的新流。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=3);
    /// let stream = stream.map(|x| x + 3);
    ///
    /// assert_eq!(vec![4, 5, 6], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn map<T, F>(self, f: F) -> Map<Self, F>
    where
        F: FnMut(Self::Item) -> T,
        Self: Sized,
    {
    
    
        Map::new(self, f)
    }

    /// 创建一个流,该流提供当前迭代器当前索引以及下一个值。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(vec!['a', 'b', 'c']);
    ///
    /// let mut stream = stream.enumerate();
    ///
    /// assert_eq!(stream.next().await, Some((0, 'a')));
    /// assert_eq!(stream.next().await, Some((1, 'b')));
    /// assert_eq!(stream.next().await, Some((2, 'c')));
    /// assert_eq!(stream.next().await, None);
    /// # });
    /// ```
    fn enumerate(self) -> Enumerate<Self>
    where
        Self: Sized,
    {
    
    
        Enumerate::new(self)
    }

    /// 根据提供的过滤条件过滤此流产生的值。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=10);
    /// let evens = stream.filter(|x| future::ready(x % 2 == 0));
    ///
    /// assert_eq!(vec![2, 4, 6, 8, 10], evens.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn filter<Fut, F>(self, f: F) -> Filter<Self, Fut, F>
    where
        F: FnMut(&Self::Item) -> Fut,
        Fut: Future<Output = bool>,
        Self: Sized,
    {
    
    
        Filter::new(self, f)
    }

    /// 过滤此流产生的值,同时根据提供的异步闭包将它们同时映射到其他类型。
    ///
    /// # Examples
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=10);
    /// let evens = stream.filter_map(|x| async move {
    
    
    ///     if x % 2 == 0 { Some(x + 1) } else { None }
    /// });
    ///
    /// assert_eq!(vec![3, 5, 7, 9, 11], evens.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn filter_map<Fut, T, F>(self, f: F) -> FilterMap<Self, Fut, F>
    where
        F: FnMut(Self::Item) -> Fut,
        Fut: Future<Output = Option<T>>,
        Self: Sized,
    {
    
    
        FilterMap::new(self, f)
    }

    /// 使用异步闭包从此流的item中计算不同类型的新item。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=3);
    /// let stream = stream.then(|x| async move { x + 3 });
    ///
    /// assert_eq!(vec![4, 5, 6], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
    where
        F: FnMut(Self::Item) -> Fut,
        Fut: Future,
        Self: Sized,
    {
    
    
        Then::new(self, f)
    }

    /// 将流转换为集合,返回表示该计算结果的Future。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::stream::StreamExt;
    /// use std::thread;
    ///
    /// let (tx, rx) = mpsc::unbounded();
    ///
    /// thread::spawn(move || {
    
    
    ///     for i in 1..=5 {
    
    
    ///         tx.unbounded_send(i).unwrap();
    ///     }
    /// });
    ///
    /// let output = rx.collect::<Vec<i32>>().await;
    /// assert_eq!(output, vec![1, 2, 3, 4, 5]);
    /// # });
    /// ```
    fn collect<C: Default + Extend<Self::Item>>(self) -> Collect<Self, C>
    where
        Self: Sized,
    {
    
    
        Collect::new(self)
    }

    /// 将流的所有item连接到一个可扩展的目标中,并返回表示最终结果的Future。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::stream::StreamExt;
    /// use std::thread;
    ///
    /// let (tx, rx) = mpsc::unbounded();
    ///
    /// thread::spawn(move || {
    
    
    ///     for i in (0..3).rev() {
    
    
    ///         let n = i * 3;
    ///         tx.unbounded_send(vec![n + 1, n + 2, n + 3]).unwrap();
    ///     }
    /// });
    ///
    /// let result = rx.concat().await;
    ///
    /// assert_eq!(result, vec![7, 8, 9, 4, 5, 6, 1, 2, 3]);
    /// # });
    /// ```
    fn concat(self) -> Concat<Self>
    where
        Self: Sized,
        Self::Item: Extend<<<Self as Stream>::Item as IntoIterator>::Item> + IntoIterator + Default,
    {
    
    
        Concat::new(self)
    }

    /// 对流执行累积异步计算,将所有值收集到一个最终结果中
    /// resolve to this value.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let number_stream = stream::iter(0..6);
    /// let sum = number_stream.fold(0, |acc, x| async move { acc + x });
    /// assert_eq!(sum.await, 15);
    /// # });
    /// ```
    fn fold<T, Fut, F>(self, init: T, f: F) -> Fold<Self, Fut, T, F>
    where
        F: FnMut(T, Self::Item) -> Fut,
        Fut: Future<Output = T>,
        Self: Sized,
    {
    
    
        Fold::new(self, f, init)
    }

    /// 将流的流平整为一个连续的流。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::stream::StreamExt;
    /// use std::thread;
    ///
    /// let (tx1, rx1) = mpsc::unbounded();
    /// let (tx2, rx2) = mpsc::unbounded();
    /// let (tx3, rx3) = mpsc::unbounded();
    ///
    /// thread::spawn(move || {
    
    
    ///     tx1.unbounded_send(1).unwrap();
    ///     tx1.unbounded_send(2).unwrap();
    /// });
    /// thread::spawn(move || {
    
    
    ///     tx2.unbounded_send(3).unwrap();
    ///     tx2.unbounded_send(4).unwrap();
    /// });
    /// thread::spawn(move || {
    
    
    ///     tx3.unbounded_send(rx1).unwrap();
    ///     tx3.unbounded_send(rx2).unwrap();
    /// });
    ///
    /// let output = rx3.flatten().collect::<Vec<i32>>().await;
    /// assert_eq!(output, vec![1, 2, 3, 4]);
    /// # });
    /// ```
    fn flatten(self) -> Flatten<Self>
    where
        Self::Item: Stream,
        Self: Sized,
    {
    
    
        Flatten::new(self)
    }

    /// 映射成类似于[`StreamExt::map`]的流,但是展平嵌套的`Stream`s
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=3);
    /// let stream = stream.flat_map(|x| stream::iter(vec![x + 3; x]));
    ///
    /// assert_eq!(vec![4, 5, 5, 6, 6, 6], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
    where
        F: FnMut(Self::Item) -> U,
        U: Stream,
        Self: Sized,
    {
    
    
        FlatMap::new(self, f)
    }

    /// 类似于[`StreamExt::fold`]的组合器,它保持内部状态并产生新的流。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=10);
    ///
    /// let stream = stream.scan(0, |state, x| {
    
    
    ///     *state += x;
    ///     future::ready(if *state < 10 { Some(x) } else { None })
    /// });
    ///
    /// assert_eq!(vec![1, 2, 3], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn scan<S, B, Fut, F>(self, initial_state: S, f: F) -> Scan<Self, S, Fut, F>
    where
        F: FnMut(&mut S, Self::Item) -> Fut,
        Fut: Future<Output = Option<B>>,
        Self: Sized,
    {
    
    
        Scan::new(self, initial_state, f)
    }

    /// 在提供的过滤表单时解析为“true”时,跳过此流上的元素。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=10);
    ///
    /// let stream = stream.skip_while(|x| future::ready(*x <= 5));
    ///
    /// assert_eq!(vec![6, 7, 8, 9, 10], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn skip_while<Fut, F>(self, f: F) -> SkipWhile<Self, Fut, F>
    where
        F: FnMut(&Self::Item) -> Fut,
        Fut: Future<Output = bool>,
        Self: Sized,
    {
    
    
        SkipWhile::new(self, f)
    }

    /// 在提供的过滤表达式解析为“true”时,从此流中take元素。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=10);
    ///
    /// let stream = stream.take_while(|x| future::ready(*x <= 5));
    ///
    /// assert_eq!(vec![1, 2, 3, 4, 5], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn take_while<Fut, F>(self, f: F) -> TakeWhile<Self, Fut, F>
    where
        F: FnMut(&Self::Item) -> Fut,
        Fut: Future<Output = bool>,
        Self: Sized,
    {
    
    
        TakeWhile::new(self, f)
    }

    /// 从此流中take元素,直到提供的future能解析为止。
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, StreamExt};
    /// use futures::task::Poll;
    ///
    /// let stream = stream::iter(1..=10);
    ///
    /// let mut i = 0;
    /// let stop_fut = future::poll_fn(|_cx| {
    
    
    ///     i += 1;
    ///     if i <= 5 {
    
    
    ///         Poll::Pending
    ///     } else {
    
    
    ///         Poll::Ready(())
    ///     }
    /// });
    ///
    /// let stream = stream.take_until(stop_fut);
    ///
    /// assert_eq!(vec![1, 2, 3, 4, 5], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn take_until<Fut>(self, fut: Fut) -> TakeUntil<Self, Fut>
    where
        Fut: Future,
        Self: Sized,
    {
    
    
        TakeUntil::new(self, fut)
    }

    /// 运行此流直至完成,对流上的每个元素执行提供的异步闭包。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let mut x = 0;
    ///
    /// {
    
    
    ///     let fut = stream::repeat(1).take(3).for_each(|item| {
    
    
    ///         x += item;
    ///         future::ready(())
    ///     });
    ///     fut.await;
    /// }
    ///
    /// assert_eq!(x, 3);
    /// # });
    /// ```
    fn for_each<Fut, F>(self, f: F) -> ForEach<Self, Fut, F>
    where
        F: FnMut(Self::Item) -> Fut,
        Fut: Future<Output = ()>,
        Self: Sized,
    {
    
    
        ForEach::new(self, f)
    }

    /// 运行此流以完成操作,并在元素可用时同时为流上的每个元素执行提供的异步关闭。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::oneshot;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let (tx1, rx1) = oneshot::channel();
    /// let (tx2, rx2) = oneshot::channel();
    /// let (tx3, rx3) = oneshot::channel();
    ///
    /// let fut = stream::iter(vec![rx1, rx2, rx3]).for_each_concurrent(
    ///     /* limit */ 2,
    ///     |rx| async move {
    
    
    ///         rx.await.unwrap();
    ///     }
    /// );
    /// tx1.send(()).unwrap();
    /// tx2.send(()).unwrap();
    /// tx3.send(()).unwrap();
    /// fut.await;
    /// # })
    /// ```
    #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))]
    #[cfg(feature = "alloc")]
    fn for_each_concurrent<Fut, F>(
        self,
        limit: impl Into<Option<usize>>,
        f: F,
    ) -> ForEachConcurrent<Self, Fut, F>
    where
        F: FnMut(Self::Item) -> Fut,
        Fut: Future<Output = ()>,
        Self: Sized,
    {
    
    
        ForEachConcurrent::new(self, limit.into(), f)
    }

    /// 创建一个新的流,该流最多包含基础流的n个项。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=10).take(3);
    ///
    /// assert_eq!(vec![1, 2, 3], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn take(self, n: usize) -> Take<Self>
    where
        Self: Sized,
    {
    
    
        Take::new(self, n)
    }

    /// 创建一个新的流,该流将跳过基础流的n个项。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(1..=10).skip(5);
    ///
    /// assert_eq!(vec![6, 7, 8, 9, 10], stream.collect::<Vec<_>>().await);
    /// # });
    /// ```
    fn skip(self, n: usize) -> Skip<Self>
    where
        Self: Sized,
    {
    
    
        Skip::new(self, n)
    }

    /// fuse一个流,使[`poll_next`](Stream::poll_next)一旦完成就再也不会被调用。此方法可用于将任何“Stream”转换为“FusedStream”。 
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::executor::block_on_stream;
    /// use futures::stream::{self, StreamExt};
    /// use futures::task::Poll;
    ///
    /// let mut x = 0;
    /// let stream = stream::poll_fn(|_| {
    
    
    ///     x += 1;
    ///     match x {
    
    
    ///         0..=2 => Poll::Ready(Some(x)),
    ///         3 => Poll::Ready(None),
    ///         _ => panic!("should not happen")
    ///     }
    /// }).fuse();
    ///
    /// let mut iter = block_on_stream(stream);
    /// assert_eq!(Some(1), iter.next());
    /// assert_eq!(Some(2), iter.next());
    /// assert_eq!(None, iter.next());
    /// assert_eq!(None, iter.next());
    /// // ...
    /// ```
    fn fuse(self) -> Fuse<Self>
    where
        Self: Sized,
    {
    
    
        Fuse::new(self)
    }

    /// 借用一个流,而不是消耗它。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let mut stream = stream::iter(1..5);
    ///
    /// let sum = stream.by_ref()
    ///                 .take(2)
    ///                 .fold(0, |a, b| async move { a + b })
    ///                 .await;
    /// assert_eq!(sum, 3);
    ///
    /// //你可以再次使用steam
    /// let sum = stream.take(2)
    ///                 .fold(0, |a, b| async move { a + b })
    ///                 .await;
    /// assert_eq!(sum, 7);
    /// # });
    /// ```
    fn by_ref(&mut self) -> &mut Self {
    
    
        self
    }

    /// 在轮询流时捕获panic。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(vec![Some(10), None, Some(11)]);
    /// // Panic on second element
    /// let stream_panicking = stream.map(|o| o.unwrap());
    /// // Collect all the results
    /// let stream = stream_panicking.catch_unwind();
    ///
    /// let results: Vec<Result<i32, _>> = stream.collect().await;
    /// match results[0] {
    
    
    ///     Ok(10) => {}
    ///     _ => panic!("unexpected result!"),
    /// }
    /// assert!(results[1].is_err());
    /// assert_eq!(results.len(), 2);
    /// # });
    /// ```
    #[cfg(feature = "std")]
    fn catch_unwind(self) -> CatchUnwind<Self>
    where
        Self: Sized + std::panic::UnwindSafe,
    {
    
    
        CatchUnwind::new(self)
    }

    /// 将流包装在Box中,将其固定。
    /// 仅仅在 `std` or `alloc` feature 启用时可用
    #[cfg(feature = "alloc")]
    fn boxed<'a>(self) -> BoxStream<'a, Self::Item>
    where
        Self: Sized + Send + 'a,
    {
    
    
        Box::pin(self)
    }

    /// 将流包装在Box中,将其固定。
    /// 类似boxed,只是没有Send
    /// 仅仅在 `std` or `alloc` feature 启用时可用
    #[cfg(feature = "alloc")]
    fn boxed_local<'a>(self) -> LocalBoxStream<'a, Self::Item>
    where
        Self: Sized + 'a,
    {
    
    
        Box::pin(self)
    }

    /// 用于创建PENDING future的缓冲列表的适配器。 
    #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))]
    #[cfg(feature = "alloc")]
    fn buffered(self, n: usize) -> Buffered<Self>
    where
        Self::Item: Future,
        Self: Sized,
    {
    
    
        Buffered::new(self, n)
    }

    /// 用于创建PENDING future的缓冲列表的适配器(无序)
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::oneshot;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let (send_one, recv_one) = oneshot::channel();
    /// let (send_two, recv_two) = oneshot::channel();
    ///
    /// let stream_of_futures = stream::iter(vec![recv_one, recv_two]);
    /// let mut buffered = stream_of_futures.buffer_unordered(10);
    ///
    /// send_two.send(2i32)?;
    /// assert_eq!(buffered.next().await, Some(Ok(2i32)));
    ///
    /// send_one.send(1i32)?;
    /// assert_eq!(buffered.next().await, Some(Ok(1i32)));
    ///
    /// assert_eq!(buffered.next().await, None);
    /// # Ok::<(), i32>(()) }).unwrap();
    /// ```
    #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))]
    #[cfg(feature = "alloc")]
    fn buffer_unordered(self, n: usize) -> BufferUnordered<Self>
    where
        Self::Item: Future,
        Self: Sized,
    {
    
    
        BufferUnordered::new(self, n)
    }

    /// 用于将两个流压缩在一起的适配器。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream1 = stream::iter(1..=3);
    /// let stream2 = stream::iter(5..=10);
    ///
    /// let vec = stream1.zip(stream2)
    ///                  .collect::<Vec<_>>()
    ///                  .await;
    /// assert_eq!(vec![(1, 5), (2, 6), (3, 7)], vec);
    /// # });
    /// ```
    ///
    fn zip<St>(self, other: St) -> Zip<Self, St>
    where
        St: Stream,
        Self: Sized,
    {
    
    
        Zip::new(self, other)
    }

    /// 用于链接两个流的适配器。
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream1 = stream::iter(vec![Ok(10), Err(false)]);
    /// let stream2 = stream::iter(vec![Err(true), Ok(20)]);
    ///
    /// let stream = stream1.chain(stream2);
    ///
    /// let result: Vec<_> = stream.collect().await;
    /// assert_eq!(result, vec![
    ///     Ok(10),
    ///     Err(false),
    ///     Err(true),
    ///     Ok(20),
    /// ]);
    /// # });
    /// ```
    fn chain<St>(self, other: St) -> Chain<Self, St>
    where
        St: Stream<Item = Self::Item>,
        Self: Sized,
    {
    
    
        Chain::new(self, other)
    }

    /// 创建一个新的流,该流公开一个`peek`方法。 
    ///
    /// 调用`peek`返回对流中下一项的引用
    fn peekable(self) -> Peekable<Self>
    where
        Self: Sized,
    {
    
    
        Peekable::new(self)
    }

    /// 一个适配器,用于对vector中的流的item进行分块。
    #[cfg(feature = "alloc")]
    fn chunks(self, capacity: usize) -> Chunks<Self>
    where
        Self: Sized,
    {
    
    
        Chunks::new(self, capacity)
    }

    /// 一个适配器,用于将vector中流的READY item分块。
    #[cfg(feature = "alloc")]
    fn ready_chunks(self, capacity: usize) -> ReadyChunks<Self>
        where
            Self: Sized,
    {
    
    
        ReadyChunks::new(self, capacity)
    }

    /// future完成后在给定流已完全处理到sink中并且刷新和关闭sink,
    #[cfg(feature = "sink")]
    fn forward<S>(self, sink: S) -> Forward<Self, S>
    where
        S: Sink<Self::Ok, Error = Self::Error>,
        Self: TryStream + Sized,
    {
    
    
        Forward::new(self, sink)
    }

    /// 将此“ Stream + Sink”对象拆分为单独的“ Sink”和“ Stream”对象。
    #[cfg(feature = "sink")]
    #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))]
    #[cfg(feature = "alloc")]
    fn split<Item>(self) -> (SplitSink<Self, Item>, SplitStream<Self>)
    where
        Self: Sink<Item> + Sized,
    {
    
    
        split::split(self)
    }

    /// 在此流的每个item上执行某些操作,然后将其传递。
    fn inspect<F>(self, f: F) -> Inspect<Self, F>
    where
        F: FnMut(&Self::Item),
        Self: Sized,
    {
    
    
        Inspect::new(self, f)
    }

    /// 将此流包装在`Either`流中,使其成为该`Either`的left-hand变体。
    fn left_stream<B>(self) -> Either<Self, B>
    where
        B: Stream<Item = Self::Item>,
        Self: Sized,
    {
    
    
        Either::Left(self)
    }

     /// 将此流包装在`Either`流中,使其成为该`Either`的right-hand变体。
    fn right_stream<B>(self) -> Either<B, Self>
    where
        B: Stream<Item = Self::Item>,
        Self: Sized,
    {
    
    
        Either::Right(self)
    }

    /// 一种方便的方法,用于在[`Unpin`]流类型上调用[`Stream::poll_next`]。 
    fn poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
    where
        Self: Unpin,
    {
    
    
        Pin::new(self).poll_next(cx)
    }

    /// 返回一个[`Future`],当此流中的下一个item准备就绪时,将进行解析。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::{future, select};
    /// use futures::stream::{StreamExt, FuturesUnordered};
    ///
    /// let mut fut = future::ready(1);
    /// let mut async_tasks = FuturesUnordered::new();
    /// let mut total = 0;
    /// loop {
    
    
    ///     select! {
    
    
    ///         num = fut => {
    
    
    ///             // First, the `ready` future completes.
    ///             total += num;
    ///             // Then we spawn a new task onto `async_tasks`,
    ///             async_tasks.push(async { 5 });
    ///         },
    ///         // On the next iteration of the loop, the task we spawned
    ///         // completes.
    ///         num = async_tasks.select_next_some() => {
    
    
    ///             total += num;
    ///         }
    ///         // Finally, both the `ready` future and `async_tasks` have
    ///         // finished, so we enter the `complete` branch.
    ///         complete => break,
    ///     }
    /// }
    /// assert_eq!(total, 6);
    /// # });
    /// ```
    fn select_next_some(&mut self) -> SelectNextSome<'_, Self>
    where
        Self: Unpin + FusedStream,
    {
    
    
        SelectNextSome::new(self)
    }
}

TryStreamExt

所有实现了TryStream都实现了TryStreamExt

impl<S: ?Sized + TryStream> TryStreamExt for S {
    
    }

/// `Result`返回类型适配器
pub trait TryStreamExt: TryStream {
    
    
    /// 将当前流包装到新流中,该新流将错误类型转换为提供的错误类型。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let mut stream =
    ///     stream::iter(vec![Ok(()), Err(5i32)])
    ///         .err_into::<i64>();
    ///
    /// assert_eq!(stream.try_next().await, Ok(Some(())));
    /// assert_eq!(stream.try_next().await, Err(5i64));
    /// # })
    /// ```
    fn err_into<E>(self) -> ErrInto<Self, E>
    where
        Self: Sized,
        Self::Error: Into<E>,
    {
    
    
        ErrInto::new(self)
    }

    /// 将当前流包装到新流中,该新流使用提供的闭包映射success值。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let mut stream =
    ///     stream::iter(vec![Ok(5), Err(0)])
    ///         .map_ok(|x| x + 2);
    ///
    /// assert_eq!(stream.try_next().await, Ok(Some(7)));
    /// assert_eq!(stream.try_next().await, Err(0));
    /// # })
    /// ```
    fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Ok) -> T,
    {
    
    
        MapOk::new(self, f)
    }

    /// 将当前流包装在新流中,该新流使用提供的闭包映射error值。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let mut stream =
    ///     stream::iter(vec![Ok(5), Err(0)])
    ///         .map_err(|x| x + 2);
    ///
    /// assert_eq!(stream.try_next().await, Ok(Some(5)));
    /// assert_eq!(stream.try_next().await, Err(2));
    /// # })
    /// ```
    fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Error) -> E,
    {
    
    
        MapErr::new(self, f)
    }

    /// 当值是ready时链接计算值,将成功的结果传递给提供的闭包“ f”。
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::channel::mpsc;
    /// use futures::future;
    /// use futures::stream::TryStreamExt;
    ///
    /// let (_tx, rx) = mpsc::channel::<Result<i32, ()>>(1);
    ///
    /// let rx = rx.and_then(|result| {
    
    
    ///     future::ok(if result % 2 == 0 {
    
    
    ///         Some(result)
    ///     } else {
    
    
    ///         None
    ///     })
    /// });
    /// ```
    fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
    where
        F: FnMut(Self::Ok) -> Fut,
        Fut: TryFuture<Error = Self::Error>,
        Self: Sized,
    {
    
    
        AndThen::new(self, f)
    }

    /// 当值是error时链接计算值,将错误的结果传递给提供的闭包“ f”。
    fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
    where
        F: FnMut(Self::Error) -> Fut,
        Fut: TryFuture<Ok = Self::Ok>,
        Self: Sized,
    {
    
    
        OrElse::new(self, f)
    }

    /// Do something with the success value of this stream, afterwards passing
    /// it on.
    ///
    /// This is similar to the `StreamExt::inspect` method where it allows
    /// easily inspecting the success value as it passes through the stream, for
    /// example to debug what's going on.
    fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
    where
        F: FnMut(&Self::Ok),
        Self: Sized,
    {
    
    
        InspectOk::new(self, f)
    }

    /// 使用此流的success值进行操作,然后将其传递。
    fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
    where
        F: FnMut(&Self::Error),
        Self: Sized,
    {
    
    
        InspectErr::new(self, f)
    }

    /// 将 [`TryStream`] 包装成 [`Stream`](futures_core::stream::Stream)
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::stream::{Stream, TryStream, TryStreamExt};
    ///
    /// # type T = i32;
    /// # type E = ();
    /// fn make_try_stream() -> impl TryStream<Ok = T, Error = E> { // ... }
    /// # futures::stream::empty()
    /// # }
    /// fn take_stream(stream: impl Stream<Item = Result<T, E>>) { /* ... */ }
    ///
    /// take_stream(make_try_stream().into_stream());
    /// ```
    fn into_stream(self) -> IntoStream<Self>
    where
        Self: Sized,
    {
    
    
        IntoStream::new(self)
    }

    /// 创建一个future,尝试解析流中的下一个item。如果在下一个item之前遇到错误,则返回错误。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let mut stream = stream::iter(vec![Ok(()), Err(())]);
    ///
    /// assert_eq!(stream.try_next().await, Ok(Some(())));
    /// assert_eq!(stream.try_next().await, Err(()));
    /// # })
    /// ```
    fn try_next(&mut self) -> TryNext<'_, Self>
    where
        Self: Unpin,
    {
    
    
        TryNext::new(self)
    }

    /// 尝试运行此流以使其完成,对流上的每个元素执行提供的异步闭包。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let mut x = 0i32;
    ///
    /// {
    
    
    ///     let fut = stream::repeat(Ok(1)).try_for_each(|item| {
    
    
    ///         x += item;
    ///         future::ready(if x == 3 { Err(()) } else { Ok(()) })
    ///     });
    ///     assert_eq!(fut.await, Err(()));
    /// }
    ///
    /// assert_eq!(x, 3);
    /// # })
    /// ```
    fn try_for_each<Fut, F>(self, f: F) -> TryForEach<Self, Fut, F>
    where
        F: FnMut(Self::Ok) -> Fut,
        Fut: TryFuture<Ok = (), Error = Self::Error>,
        Self: Sized,
    {
    
    
        TryForEach::new(self, f)
    }

    /// 在提供的过滤表达式解析为“true”时,跳过此流上的元素
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let stream = stream::iter(vec![Ok::<i32, i32>(1), Ok(3), Ok(2)]);
    /// let stream = stream.try_skip_while(|x| future::ready(Ok(*x < 3)));
    ///
    /// let output: Result<Vec<i32>, i32> = stream.try_collect().await;
    /// assert_eq!(output, Ok(vec![3, 2]));
    /// # })
    /// ```
    fn try_skip_while<Fut, F>(self, f: F) -> TrySkipWhile<Self, Fut, F>
    where
        F: FnMut(&Self::Ok) -> Fut,
        Fut: TryFuture<Ok = bool, Error = Self::Error>,
        Self: Sized,
    {
    
    
        TrySkipWhile::new(self, f)
    }

    /// 尝试运行此流以完成操作,并在元素可用时并发地为流上的每个元素执行所提供的异步闭包,并在发生错误时立即退出。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::oneshot;
    /// use futures::stream::{self, StreamExt, TryStreamExt};
    ///
    /// let (tx1, rx1) = oneshot::channel();
    /// let (tx2, rx2) = oneshot::channel();
    /// let (_tx3, rx3) = oneshot::channel();
    ///
    /// let stream = stream::iter(vec![rx1, rx2, rx3]);
    /// let fut = stream.map(Ok).try_for_each_concurrent(
    ///     /* limit */ 2,
    ///     |rx| async move {
    
    
    ///         let res: Result<(), oneshot::Canceled> = rx.await;
    ///         res
    ///     }
    /// );
    ///
    /// tx1.send(()).unwrap();
    /// // Drop the second sender so that `rx2` resolves to `Canceled`.
    /// drop(tx2);
    ///
    /// // The final result is an error because the second future
    /// // resulted in an error.
    /// assert_eq!(Err(oneshot::Canceled), fut.await);
    /// # })
    /// ```
    #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))]
    #[cfg(feature = "alloc")]
    fn try_for_each_concurrent<Fut, F>(
        self,
        limit: impl Into<Option<usize>>,
        f: F,
    ) -> TryForEachConcurrent<Self, Fut, F>
    where
        F: FnMut(Self::Ok) -> Fut,
        Fut: Future<Output = Result<(), Self::Error>>,
        Self: Sized,
    {
    
    
        TryForEachConcurrent::new(self, limit.into(), f)
    }

    /// 尝试将流转换为集合,返回表示该计算结果的Future。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::stream::TryStreamExt;
    /// use std::thread;
    ///
    /// let (tx, rx) = mpsc::unbounded();
    ///
    /// thread::spawn(move || {
    
    
    ///     for i in 1..=5 {
    
    
    ///         tx.unbounded_send(Ok(i)).unwrap();
    ///     }
    ///     tx.unbounded_send(Err(6)).unwrap();
    /// });
    ///
    /// let output: Result<Vec<i32>, i32> = rx.try_collect().await;
    /// assert_eq!(output, Err(6));
    /// # })
    /// ```
    fn try_collect<C: Default + Extend<Self::Ok>>(self) -> TryCollect<Self, C>
    where
        Self: Sized,
    {
    
    
        TryCollect::new(self)
    }

    /// 尝试根据提供的异步闭包过滤此流产生的值。
    ///
    /// # Examples
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::future;
    /// use futures::stream::{self, StreamExt, TryStreamExt};
    ///
    /// let stream = stream::iter(vec![Ok(1i32), Ok(2i32), Ok(3i32), Err("error")]);
    /// let mut evens = stream.try_filter(|x| {
    
    
    ///     future::ready(x % 2 == 0)
    /// });
    ///
    /// assert_eq!(evens.next().await, Some(Ok(2)));
    /// assert_eq!(evens.next().await, Some(Err("error")));
    /// # })
    /// ```
    fn try_filter<Fut, F>(self, f: F) -> TryFilter<Self, Fut, F>
    where
        Fut: Future<Output = bool>,
        F: FnMut(&Self::Ok) -> Fut,
        Self: Sized,
    {
    
    
        TryFilter::new(self, f)
    }

    /// 尝试过滤此流产生的值,同时根据提供的异步闭包将它们同时映射为其他类型。
    ///
    /// # Examples
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, StreamExt, TryStreamExt};
    /// use futures::pin_mut;
    ///
    /// let stream = stream::iter(vec![Ok(1i32), Ok(6i32), Err("error")]);
    /// let halves = stream.try_filter_map(|x| async move {
    
    
    ///     let ret = if x % 2 == 0 { Some(x / 2) } else { None };
    ///     Ok(ret)
    /// });
    ///
    /// pin_mut!(halves);
    /// assert_eq!(halves.next().await, Some(Ok(3)));
    /// assert_eq!(halves.next().await, Some(Err("error")));
    /// # })
    /// ```
    fn try_filter_map<Fut, F, T>(self, f: F) -> TryFilterMap<Self, Fut, F>
    where
        Fut: TryFuture<Ok = Option<T>, Error = Self::Error>,
        F: FnMut(Self::Ok) -> Fut,
        Self: Sized,
    {
    
    
        TryFilterMap::new(self, f)
    }

    /// 将流的流平整为一个连续的流。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::stream::{StreamExt, TryStreamExt};
    /// use std::thread;
    ///
    /// let (tx1, rx1) = mpsc::unbounded();
    /// let (tx2, rx2) = mpsc::unbounded();
    /// let (tx3, rx3) = mpsc::unbounded();
    ///
    /// thread::spawn(move || {
    
    
    ///     tx1.unbounded_send(Ok(1)).unwrap();
    /// });
    /// thread::spawn(move || {
    
    
    ///     tx2.unbounded_send(Ok(2)).unwrap();
    ///     tx2.unbounded_send(Err(3)).unwrap();
    /// });
    /// thread::spawn(move || {
    
    
    ///     tx3.unbounded_send(Ok(rx1)).unwrap();
    ///     tx3.unbounded_send(Ok(rx2)).unwrap();
    ///     tx3.unbounded_send(Err(4)).unwrap();
    /// });
    ///
    /// let mut stream = rx3.try_flatten();
    /// assert_eq!(stream.next().await, Some(Ok(1)));
    /// assert_eq!(stream.next().await, Some(Ok(2)));
    /// assert_eq!(stream.next().await, Some(Err(3)));
    /// # });
    /// ```
    fn try_flatten(self) -> TryFlatten<Self>
    where
        Self::Ok: TryStream,
        <Self::Ok as TryStream>::Error: From<Self::Error>,
        Self: Sized,
    {
    
    
        TryFlatten::new(self)
    }

    /// 尝试对流执行累积异步计算,将所有值收集到一个最终结果中
    ///
    /// 这个方法类似 [`fold`](crate::stream::StreamExt::fold), 但是如果在流或提供的闭包中遇到错误,则会提早退出。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, TryStreamExt};
    ///
    /// let number_stream = stream::iter(vec![Ok::<i32, i32>(1), Ok(2)]);
    /// let sum = number_stream.try_fold(0, |acc, x| async move { Ok(acc + x) });
    /// assert_eq!(sum.await, Ok(3));
    ///
    /// let number_stream_with_err = stream::iter(vec![Ok::<i32, i32>(1), Err(2), Ok(1)]);
    /// let sum = number_stream_with_err.try_fold(0, |acc, x| async move { Ok(acc + x) });
    /// assert_eq!(sum.await, Err(2));
    /// # })
    /// ```
    fn try_fold<T, Fut, F>(self, init: T, f: F) -> TryFold<Self, Fut, T, F>
    where
        F: FnMut(T, Self::Ok) -> Fut,
        Fut: TryFuture<Ok = T, Error = Self::Error>,
        Self: Sized,
    {
    
    
        TryFold::new(self, f, init)
    }

    /// 尝试将流的所有item连接到单个可扩展的目的地,并返回表示最终结果的Future。
    ///
    /// 这个方法类似 [`concat`](crate::stream::StreamExt::concat), 但如果流中遇到错误,则会提早退出。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::stream::TryStreamExt;
    /// use std::thread;
    ///
    /// let (tx, rx) = mpsc::unbounded::<Result<Vec<i32>, ()>>();
    ///
    /// thread::spawn(move || {
    
    
    ///     for i in (0..3).rev() {
    
    
    ///         let n = i * 3;
    ///         tx.unbounded_send(Ok(vec![n + 1, n + 2, n + 3])).unwrap();
    ///     }
    /// });
    ///
    /// let result = rx.try_concat().await;
    ///
    /// assert_eq!(result, Ok(vec![7, 8, 9, 4, 5, 6, 1, 2, 3]));
    /// # });
    /// ```
    fn try_concat(self) -> TryConcat<Self>
    where
        Self: Sized,
        Self::Ok: Extend<<<Self as TryStream>::Ok as IntoIterator>::Item> + IntoIterator + Default,
    {
    
    
        TryConcat::new(self)
    }

    /// 尝试同时从流中执行多个future。
    ///
    ///
    /// # Examples
    ///
    /// Results are returned in the order of completion:
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::oneshot;
    /// use futures::stream::{self, StreamExt, TryStreamExt};
    ///
    /// let (send_one, recv_one) = oneshot::channel();
    /// let (send_two, recv_two) = oneshot::channel();
    ///
    /// let stream_of_futures = stream::iter(vec![Ok(recv_one), Ok(recv_two)]);
    ///
    /// let mut buffered = stream_of_futures.try_buffer_unordered(10);
    ///
    /// send_two.send(2i32)?;
    /// assert_eq!(buffered.next().await, Some(Ok(2i32)));
    ///
    /// send_one.send(1i32)?;
    /// assert_eq!(buffered.next().await, Some(Ok(1i32)));
    ///
    /// assert_eq!(buffered.next().await, None);
    /// # Ok::<(), i32>(()) }).unwrap();
    /// ```
    ///
    /// Errors from the underlying stream itself are propagated:
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::stream::{StreamExt, TryStreamExt};
    ///
    /// let (sink, stream_of_futures) = mpsc::unbounded();
    /// let mut buffered = stream_of_futures.try_buffer_unordered(10);
    ///
    /// sink.unbounded_send(Ok(async { Ok(7i32) }))?;
    /// assert_eq!(buffered.next().await, Some(Ok(7i32)));
    ///
    /// sink.unbounded_send(Err("error in the stream"))?;
    /// assert_eq!(buffered.next().await, Some(Err("error in the stream")));
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))]
    #[cfg(feature = "alloc")]
    fn try_buffer_unordered(self, n: usize) -> TryBufferUnordered<Self>
    where
        Self::Ok: TryFuture<Error = Self::Error>,
        Self: Sized,
    {
    
    
        TryBufferUnordered::new(self, n)
    }

    // TODO: 来自rustdoc的误报。验证一次#43466定
    //
    /// 在[Unpin`]流类型上调用[`TryStream::try_poll_next`]的便捷方法。
    fn try_poll_next_unpin(
        &mut self,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Self::Ok, Self::Error>>>
    where
        Self: Unpin,
    {
    
    
        Pin::new(self).try_poll_next(cx)
    }

    /// 使用Futures 0.1`Stream`将[`TryStream`]包装到与库兼容的流中。需要启用“ compat”功能
    /// ```
    /// use futures::future::{FutureExt, TryFutureExt};
    /// # let (tx, rx) = futures::channel::oneshot::channel();
    ///
    /// let future03 = async {
    
    
    ///     println!("Running on the pool");
    ///     tx.send(42).unwrap();
    /// };
    ///
    /// let future01 = future03
    ///     .unit_error() // Make it a TryFuture
    ///     .boxed()  // Make it Unpin
    ///     .compat();
    ///
    /// tokio::run(future01);
    /// # assert_eq!(42, futures::executor::block_on(rx).unwrap());
    /// ```
    #[cfg(feature = "compat")]
    fn compat(self) -> Compat<Self>
    where
        Self: Sized + Unpin,
    {
    
    
        Compat::new(self)
    }

    /// 将该流转换为[`AsyncRead`](crate::io::AsyncRead的适配器。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::stream::{self, TryStreamExt};
    /// use futures::io::AsyncReadExt;
    ///
    /// let stream = stream::iter(vec![Ok(vec![1, 2, 3, 4, 5])]);
    /// let mut reader = stream.into_async_read();
    /// let mut buf = Vec::new();
    ///
    /// assert!(reader.read_to_end(&mut buf).await.is_ok());
    /// assert_eq!(buf, &[1, 2, 3, 4, 5]);
    /// # })
    /// ```
    #[cfg(feature = "io")]
    #[cfg(feature = "std")]
    fn into_async_read(self) -> IntoAsyncRead<Self>
    where
        Self: Sized + TryStreamExt<Error = std::io::Error> + Unpin,
        Self::Ok: AsRef<[u8]>,
    {
    
    
        IntoAsyncRead::new(self)
    }
}

SinkExt

所有实现了Sink的类型都实现了SinkExt


impl<T: ?Sized, Item> SinkExt<Item> for T where T: Sink<Item> {
    
    }

/// 一个扩展特征,它向`Sink`类型添加utility方法。
/// combinator functions.
pub trait SinkExt<Item>: Sink<Item> {
    
    
    /// 在sink的前面组装一个函数。
    /// 类似 `Iterator::map`.
    fn with<U, Fut, F, E>(self, f: F) -> With<Self, Item, U, Fut, F>
        where F: FnMut(U) -> Fut,
              Fut: Future<Output = Result<Item, E>>,
              E: From<Self::Error>,
              Self: Sized
    {
    
    
        With::new(self, f)
    }

    /// 在sink的前面组装一个函数。
    ///
    /// 类似 `Iterator::flat_map`.
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::channel::mpsc;
    /// use futures::sink::SinkExt;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let (tx, rx) = mpsc::channel(5);
    ///
    /// let mut tx = tx.with_flat_map(|x| {
    
    
    ///     stream::iter(vec![Ok(42); x])
    /// });
    ///
    /// tx.send(5).await.unwrap();
    /// drop(tx);
    /// let received: Vec<i32> = rx.collect().await;
    /// assert_eq!(received, vec![42, 42, 42, 42, 42]);
    /// # });
    /// ```
    fn with_flat_map<U, St, F>(self, f: F) -> WithFlatMap<Self, Item, U, St, F>
        where F: FnMut(U) -> St,
              St: Stream<Item = Result<Item, Self::Error>>,
              Self: Sized
    {
    
    
        WithFlatMap::new(self, f)
    }

    /*
    fn with_map<U, F>(self, f: F) -> WithMap<Self, U, F>
        where F: FnMut(U) -> Self::SinkItem,
              Self: Sized;

    fn with_filter<F>(self, f: F) -> WithFilter<Self, F>
        where F: FnMut(Self::SinkItem) -> bool,
              Self: Sized;

    fn with_filter_map<U, F>(self, f: F) -> WithFilterMap<Self, U, F>
        where F: FnMut(U) -> Option<Self::SinkItem>,
              Self: Sized;
     */

    ///转换sink返回的错误
    fn sink_map_err<E, F>(self, f: F) -> SinkMapErr<Self, F>
        where F: FnOnce(Self::Error) -> E,
              Self: Sized,
    {
    
    
        SinkMapErr::new(self, f)
    }

    /// 使用`Into`特性将此sink的错误映射到其他错误类型。
    ///
    /// 如果要映射`Sink + Stream`的错误, 请使用 `.sink_err_into().err_into()`.
    fn sink_err_into<E>(self) -> err_into::SinkErrInto<Self, Item, E>
        where Self: Sized,
              Self::Error: Into<E>,
    {
    
    
        SinkErrInto::new(self)
    }


    /// 向当前sink添加一个固定大小的缓冲区
    #[cfg(feature = "alloc")]
    fn buffer(self, capacity: usize) -> Buffer<Self, Item>
        where Self: Sized,
    {
    
    
        Buffer::new(self, capacity)
    }

    ///关闭这个sink.
    fn close(&mut self) -> Close<'_, Self, Item>
        where Self: Unpin,
    {
    
    
        Close::new(self)
    }

    /// 将项目扇出到多个sink。
    ///
    /// 此适配器克隆每个传入的item,并将其同时转发到该item和另一个sink。
    fn fanout<Si>(self, other: Si) -> Fanout<Self, Si>
        where Self: Sized,
              Item: Clone,
              Si: Sink<Item, Error=Self::Error>
    {
    
    
        Fanout::new(self, other)
    }

    /// 刷新这个sink, 处理所有pending items.
    ///
    /// 此适配器旨在在要停止发送到sink直到所有当前请求都已处理之前使用。
    fn flush(&mut self) -> Flush<'_, Self, Item>
        where Self: Unpin,
    {
    
    
        Flush::new(self)
    }

    /// future将完成在给定item已完全处理到sink中(包括flush)之后
    /// 请注意,由于具有flush功能,通常最好将所有批次的item通过“send_all”发送,而不是在每个item之间进行flush。
    fn send(&mut self, item: Item) -> Send<'_, Self, Item>
        where Self: Unpin,
    {
    
    
        Send::new(self, item)
    }

    /// 在给定流已完全处理到sink中(包括flush)之后完成的将来。
    fn send_all<'a, St>(
        &'a mut self,
        stream: &'a mut St
    ) -> SendAll<'a, Self, St>
        where St: TryStream<Ok = Item, Error = Self::Error> + Stream + Unpin + ?Sized,
              Self: Unpin,
    {
    
    
        SendAll::new(self, stream)
    }

    /// 将此sink包裹在一个“Either”sink中,使其成为该“Either”sink的left-hand。
    fn left_sink<Si2>(self) -> Either<Self, Si2>
        where Si2: Sink<Item, Error = Self::Error>,
              Self: Sized
    {
    
    
        Either::Left(self)
    }

    ///将此sink包裹在一个“Either”sink中,使其成为该“Either”sink的right-hand。
    fn right_sink<Si1>(self) -> Either<Si1, Self>
        where Si1: Sink<Item, Error = Self::Error>,
              Self: Sized
    {
    
    
        Either::Right(self)
    }

      /// 使用future 0.1`Sink`将[`Sink`]包装到与库兼容的接收器中。需要启用“ compat”功能。 
    #[cfg(feature = "compat")]
    fn compat(self) -> CompatSink<Self, Item>
        where Self: Sized + Unpin,
    {
    
    
        CompatSink::new(self)
    }
    
    ///一种方便的方法,用于在[`Unpin`] sink类型上调用[`Sink::poll_ready`]。 
    fn poll_ready_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
        where Self: Unpin
    {
    
    
        Pin::new(self).poll_ready(cx)
    }

    /// 一种方便的方法,用于在[`Unpin`]接收器类型上调用[`Sink::start_send`]。
    fn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error>
        where Self: Unpin
    {
    
    
        Pin::new(self).start_send(item)
    }

    /// 一种方便的方法,用于在[`Unpin`]接收器类型上调用[`Sink::poll_flush`]
    fn poll_flush_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
        where Self: Unpin
    {
    
    
        Pin::new(self).poll_flush(cx)
    }

    /// 一种方便的方法,用于在[`Unpin`]接收器类型上调用[`Sink::poll_close`]。 
    fn poll_close_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
        where Self: Unpin
    {
    
    
        Pin::new(self).poll_close(cx)
    }
}

AsyncReadExt

所有实现了AsyncRead的类型都实现了AsyncReadExt

impl<R: AsyncRead + ?Sized> AsyncReadExt for R {
    
    }

/// 一个扩展特征,它向`AsyncRead`类型添加utility方法。
pub trait AsyncReadExt: AsyncRead {
    
    
    /// 创建一个适配器,它将将此流与另一个流链接。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncReadExt, Cursor};
    ///
    /// let reader1 = Cursor::new([1, 2, 3, 4]);
    /// let reader2 = Cursor::new([5, 6, 7, 8]);
    ///
    /// let mut reader = reader1.chain(reader2);
    /// let mut buffer = Vec::new();
    ///
    /// // read the value into a Vec.
    /// reader.read_to_end(&mut buffer).await?;
    /// assert_eq!(buffer, [1, 2, 3, 4, 5, 6, 7, 8]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn chain<R>(self, next: R) -> Chain<Self, R>
    where
        Self: Sized,
        R: AsyncRead,
    {
    
    
        Chain::new(self, next)
    }

    /// 尝试以异步方式将某些字节直接读取到给定的“buf”中,并返回future的类型。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncReadExt, Cursor};
    ///
    /// let mut reader = Cursor::new([1, 2, 3, 4]);
    /// let mut output = [0u8; 5];
    ///
    /// let bytes = reader.read(&mut output[..]).await?;
    ///
    /// // 这只能保证为4,因为`&[u8]`是同步读取器。在真实的系统中,一次读取可能会从1到`output.len()`字节之间的任何地方。
    /// assert_eq!(bytes, 4);
    /// assert_eq!(output, [1, 2, 3, 4, 0]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>
        where Self: Unpin,
    {
    
    
        Read::new(self, buf)
    }

    /// 创建一个future,它将使用vector IO操作从“AsyncRead”中读取到“bufs”中。
    fn read_vectored<'a>(&'a mut self, bufs: &'a mut [IoSliceMut<'a>]) -> ReadVectored<'a, Self>
        where Self: Unpin,
    {
    
    
        ReadVectored::new(self, bufs)
    }

    /// 创建一个future,它将读取足够的字节以填充“buf”,如果过早命中文件尾(EOF),则会返回错误
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncReadExt, Cursor};
    ///
    /// let mut reader = Cursor::new([1, 2, 3, 4]);
    /// let mut output = [0u8; 4];
    ///
    /// reader.read_exact(&mut output).await?;
    ///
    /// assert_eq!(output, [1, 2, 3, 4]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    ///
    /// ## EOF is hit before `buf` is filled
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{self, AsyncReadExt, Cursor};
    ///
    /// let mut reader = Cursor::new([1, 2, 3, 4]);
    /// let mut output = [0u8; 5];
    ///
    /// let result = reader.read_exact(&mut output).await;
    ///
    /// assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
    /// # });
    /// ```
    fn read_exact<'a>(
        &'a mut self,
        buf: &'a mut [u8],
    ) -> ReadExact<'a, Self>
        where Self: Unpin,
    {
    
    
        ReadExact::new(self, buf)
    }

    /// 创建一个future,它将从该`AsyncRead`中读取所有字节。
    /// 成功后将返回读取的字节总数。
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncReadExt, Cursor};
    ///
    /// let mut reader = Cursor::new([1, 2, 3, 4]);
    /// let mut output = Vec::with_capacity(4);
    ///
    /// let bytes = reader.read_to_end(&mut output).await?;
    ///
    /// assert_eq!(bytes, 4);
    /// assert_eq!(output, vec![1, 2, 3, 4]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn read_to_end<'a>(
        &'a mut self,
        buf: &'a mut Vec<u8>,
    ) -> ReadToEnd<'a, Self>
        where Self: Unpin,
    {
    
    
        ReadToEnd::new(self, buf)
    }

    /// 创建一个future,它将从此`AsyncRead`中读取所有字节。
    ///
    /// 成功后,将返回读取的字节总数
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncReadExt, Cursor};
    ///
    /// let mut reader = Cursor::new(&b"1234"[..]);
    /// let mut buffer = String::with_capacity(4);
    ///
    /// let bytes = reader.read_to_string(&mut buffer).await?;
    ///
    /// assert_eq!(bytes, 4);
    /// assert_eq!(buffer, String::from("1234"));
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn read_to_string<'a>(
        &'a mut self,
        buf: &'a mut String,
    ) -> ReadToString<'a, Self>
        where Self: Unpin,
    {
    
    
        ReadToString::new(self, buf)
    }

    /// 将此读/写对象分为两半的Helper方法。
    ///
    /// 返回的两半分别实现了`AsyncRead`和`AsyncWrite` trait。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{self, AsyncReadExt, Cursor};
    ///
    /// // 注意,对于“ Cursor”,读和写两半共享一个寻找位置。对于同时实现AsyncRead和AsyncWrite的其他类型,这可能是正确的,也可能不是。
    ///
    /// let reader = Cursor::new([1, 2, 3, 4]);
    /// let mut buffer = Cursor::new(vec![0, 0, 0, 0, 5, 6, 7, 8]);
    /// let mut writer = Cursor::new(vec![0u8; 5]);
    ///
    /// {
    
    
    ///     let (buffer_reader, mut buffer_writer) = (&mut buffer).split();
    ///     io::copy(reader, &mut buffer_writer).await?;
    ///     io::copy(buffer_reader, &mut writer).await?;
    /// }
    ///
    /// assert_eq!(buffer.into_inner(), [1, 2, 3, 4, 5, 6, 7, 8]);
    /// assert_eq!(writer.into_inner(), [5, 6, 7, 8, 0]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn split(self) -> (ReadHalf<Self>, WriteHalf<Self>)
        where Self: AsyncWrite + Sized,
    {
    
    
        split::split(self)
    }

    /// 创建一个AsyncRead适配器,该适配器将从基础reader中读取最多`limit`字节。
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncReadExt, Cursor};
    ///
    /// let reader = Cursor::new(&b"12345678"[..]);
    /// let mut buffer = [0; 5];
    ///
    /// let mut take = reader.take(4);
    /// let n = take.read(&mut buffer).await?;
    ///
    /// assert_eq!(n, 4);
    /// assert_eq!(&buffer, b"1234\0");
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn take(self, limit: u64) -> Take<Self>
        where Self: Sized
    {
    
    
        Take::new(self, limit)
    }

    /// 在兼容性包装器中包装[AsyncRead`],使其可以用作future 0.1/tokio-io 0.1`AsyncRead`。如果包装类型也实现[`AsyncWrite`],则结果还将实现Future 0.1 /tokio 0.1 `AsyncWrite`特征。
    #[cfg(feature = "io-compat")]
    fn compat(self) -> Compat<Self>
        where Self: Sized + Unpin,
    {
    
    
        Compat::new(self)
    }
}

AsyncWriteExt

所有实现了AsyncWrite的类型都实现了AsyncWriteExt

impl<W: AsyncWrite + ?Sized> AsyncWriteExt for W {
    
    }

/// 一个扩展特征,它向`AsyncWrite`类型添加utility方法。
pub trait AsyncWriteExt: AsyncWrite {
    
    
    /// 创建一个Future,它将完全刷新此`AsyncWrite`
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AllowStdIo, AsyncWriteExt};
    /// use std::io::{BufWriter, Cursor};
    ///
    /// let mut output = vec![0u8; 5];
    ///
    /// {
    
    
    ///     let writer = Cursor::new(&mut output);
    ///     let mut buffered = AllowStdIo::new(BufWriter::new(writer));
    ///     buffered.write_all(&[1, 2]).await?;
    ///     buffered.write_all(&[3, 4]).await?;
    ///     buffered.flush().await?;
    /// }
    ///
    /// assert_eq!(output, [1, 2, 3, 4, 0]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn flush(&mut self) -> Flush<'_, Self>
        where Self: Unpin,
    {
    
    
        Flush::new(self)
    }

    /// 创建一个Future将完全关闭此`AsyncWrite`的状态。
    fn close(&mut self) -> Close<'_, Self>
        where Self: Unpin,
    {
    
    
        Close::new(self)
    }

    /// 创建一个future,它将来自`buf`的字节写入对象。
    ///
    /// 返回的future将解析为写入操作完成后写入的字节数。
    fn write<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self>
        where Self: Unpin,
    {
    
    
        Write::new(self, buf)
    }

    /// 创建一个future,它将使用vecotor IO操作将`bufs`中的字节写入对象
    fn write_vectored<'a>(&'a mut self, bufs: &'a [IoSlice<'a>]) -> WriteVectored<'a, Self>
        where Self: Unpin,
    {
    
    
        WriteVectored::new(self, bufs)
    }

    /// 将数据写入此对象
    ///
    /// 创建一个Future,它将把缓冲区`buf`的全部内容写入该`AsyncWrite`中。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncWriteExt, Cursor};
    ///
    /// let mut writer = Cursor::new(vec![0u8; 5]);
    ///
    /// writer.write_all(&[1, 2, 3, 4]).await?;
    ///
    /// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> WriteAll<'a, Self>
        where Self: Unpin,
    {
    
    
        WriteAll::new(self, buf)
    }

    /// 尝试将多个缓冲区写入此writer。
    ///
    /// 创建一个Future,它将使用[vectored writes]将`bufs`的全部内容写入此`AsyncWrite`中。 
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::AsyncWriteExt;
    /// use std::io::{Cursor, IoSlice};
    ///
    /// let mut writer = Cursor::new([0u8; 7]);
    /// let bufs = &mut [
    ///     IoSlice::new(&[1]),
    ///     IoSlice::new(&[2, 3]),
    ///     IoSlice::new(&[4, 5, 6]),
    /// ];
    ///
    /// writer.write_all_vectored(bufs).await?;
    /// // Note: the contents of `bufs` is now undefined, see the Notes section.
    ///
    /// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 5, 6, 0]);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    #[cfg(feature = "write_all_vectored")]
    fn write_all_vectored<'a>(
        &'a mut self,
        bufs: &'a mut [IoSlice<'a>],
    ) -> WriteAllVectored<'a, Self>
    where
        Self: Unpin,
    {
    
    
        WriteAllVectored::new(self, bufs)
    }

    /// 在兼容性包装器中包装[AsyncWrite`],使其可以用作future 0.1/tokio-io 0.1的`AsyncWrite`。需要启用io-compat功能。 
    #[cfg(feature = "io-compat")]
    fn compat_write(self) -> Compat<Self>
        where Self: Sized + Unpin,
    {
    
    
        Compat::new(self)
    }

    /// 允许将[`AsyncWrite`] 用作 [`Sink`](futures_sink::Sink)`<Item: AsRef<[u8]>>`.
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::AsyncWriteExt;
    /// use futures::stream::{self, StreamExt};
    ///
    /// let stream = stream::iter(vec![Ok([1, 2, 3]), Ok([4, 5, 6])]);
    ///
    /// let mut writer = vec![];
    ///
    /// stream.forward((&mut writer).into_sink()).await?;
    ///
    /// assert_eq!(writer, vec![1, 2, 3, 4, 5, 6]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// # })?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "sink")]
    fn into_sink<Item: AsRef<[u8]>>(self) -> IntoSink<Self, Item>
        where Self: Sized,
    {
    
    
        IntoSink::new(self)
    }
}

AsyncSeekExt

所有实现了AsyncSeek的类型都实现了AsyncSeekExt

impl<S: AsyncSeek + ?Sized> AsyncSeekExt for S {
    
    }

/// 一个扩展特征,它向`AsyncSeek`类型添加utility方法。
pub trait AsyncSeekExt: AsyncSeek {
    
    
    /// 创建一个Future,它将寻找一个IO对象,然后在该对象和对象本身中产生新的位置
    fn seek(&mut self, pos: SeekFrom) -> Seek<'_, Self>
        where Self: Unpin,
    {
    
    
        Seek::new(self, pos)
    }
}

AsyncBufReadExt

所有实现了AsyncBufRead都实现了AsyncBufReadExt

impl<R: AsyncBufRead + ?Sized> AsyncBufReadExt for R {
    
    }

/// 扩展特性,它向`AsyncBufRead`类型添加utility方法。
pub trait AsyncBufReadExt: AsyncBufRead {
    
    
    /// 创建一个future,它将与该I/O对象关联的所有字节读入“buf”,直到达到边界符“byte”或EOF。此方法与[`BufRead::read_until`](std::io::BufRead::read_until)类似,只不过是异步。
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncBufReadExt, Cursor};
    ///
    /// let mut cursor = Cursor::new(b"lorem-ipsum");
    /// let mut buf = vec![];
    ///
    /// // cursor is at 'l'
    /// let num_bytes = cursor.read_until(b'-', &mut buf).await?;
    /// assert_eq!(num_bytes, 6);
    /// assert_eq!(buf, b"lorem-");
    /// buf.clear();
    ///
    /// // cursor is at 'i'
    /// let num_bytes = cursor.read_until(b'-', &mut buf).await?;
    /// assert_eq!(num_bytes, 5);
    /// assert_eq!(buf, b"ipsum");
    /// buf.clear();
    ///
    /// // cursor is at EOF
    /// let num_bytes = cursor.read_until(b'-', &mut buf).await?;
    /// assert_eq!(num_bytes, 0);
    /// assert_eq!(buf, b"");
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn read_until<'a>(
        &'a mut self,
        byte: u8,
        buf: &'a mut Vec<u8>,
    ) -> ReadUntil<'a, Self>
        where Self: Unpin,
    {
    
    
        ReadUntil::new(self, byte, buf)
    }

    /// 创建一个future,它将与该I /O对象关联的所有字节读入“ buf”,直到到达换行符(0xA byte)或EOF,该方法类似[`BufRead::read_line` ](std::io::BufRead::read_line)
    ///
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncBufReadExt, Cursor};
    ///
    /// let mut cursor = Cursor::new(b"foo\nbar");
    /// let mut buf = String::new();
    ///
    /// // cursor is at 'f'
    /// let num_bytes = cursor.read_line(&mut buf).await?;
    /// assert_eq!(num_bytes, 4);
    /// assert_eq!(buf, "foo\n");
    /// buf.clear();
    ///
    /// // cursor is at 'b'
    /// let num_bytes = cursor.read_line(&mut buf).await?;
    /// assert_eq!(num_bytes, 3);
    /// assert_eq!(buf, "bar");
    /// buf.clear();
    ///
    /// // cursor is at EOF
    /// let num_bytes = cursor.read_line(&mut buf).await?;
    /// assert_eq!(num_bytes, 0);
    /// assert_eq!(buf, "");
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn read_line<'a>(&'a mut self, buf: &'a mut String) -> ReadLine<'a, Self>
        where Self: Unpin,
    {
    
    
        ReadLine::new(self, buf)
    }

    /// 返回此reader各行的stream,类似[`BufRead::lines`](std::io::BufRead::lines)
    /// # Examples
    ///
    /// ```
    /// # futures::executor::block_on(async {
    
    
    /// use futures::io::{AsyncBufReadExt, Cursor};
    /// use futures::stream::StreamExt;
    ///
    /// let cursor = Cursor::new(b"lorem\nipsum\r\ndolor");
    ///
    /// let mut lines_stream = cursor.lines().map(|l| l.unwrap());
    /// assert_eq!(lines_stream.next().await, Some(String::from("lorem")));
    /// assert_eq!(lines_stream.next().await, Some(String::from("ipsum")));
    /// assert_eq!(lines_stream.next().await, Some(String::from("dolor")));
    /// assert_eq!(lines_stream.next().await, None);
    /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
    /// ```
    fn lines(self) -> Lines<Self>
        where Self: Sized,
    {
    
    
        Lines::new(self)
    }
}

猜你喜欢

转载自blog.csdn.net/kk3909/article/details/108176871