跳到主要内容

AsyncRead

搜索

trait AsyncRead 

源代码
pub trait AsyncRead {
    // Required method
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<Result<()>>;
}
展开描述

从源读取字节。

此 trait 类似于 std::io::Read trait,但与异步任务系统集成。特别地,与 Read::read 不同,poll_read 方法将在数据尚未可用时自动将当前任务排队等待唤醒并返回,而不是阻塞调用线程。

具体来说,这意味着 poll_read 函数将返回以下之一:

  • Poll::Ready(Ok(())) 表示已立即读取数据并将其放入输出缓冲区中。读取的数据量可以通过 ReadBuf::filled 返回的切片长度的增加来确定。如果差值为 0,则表示已到达 EOF,或者输出缓冲区的容量为零(即 buf.remaining() == 0)。

  • Poll::Pending 表示没有数据被读入所提供的缓冲区。I/O 对象当前不可读,但将来可能变为可读。最重要的是,当前 future 的任务被安排在对象可读时获得 unpark。这意味着与 Future::poll 一样,当 I/O 对象再次可读时,你将收到通知。

  • Poll::Ready(Err(e)) 表示其他错误,这些是来自底层对象的标准 I/O 错误。

此 trait 重要的是意味着 read 方法只能在 future 任务的上下文中工作。如果在任务外使用,该对象可能会发生 panic。

用于处理 AsyncRead 值的实用工具由 AsyncReadExt 提供。

必需方法§

源代码

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>>

尝试从 AsyncRead 读取到 buf 中。

成功时,返回 Poll::Ready(Ok(())) 并将数据放入 buf 的未填充部分。如果没有读取数据(buf.filled().len() 未变化),则表示已到达 EOF,或者输出缓冲区的容量为零(即 buf.remaining() == 0)。

如果没有可读取的数据,该方法将返回 Poll::Pending,并安排当前任务(通过 cx.waker())在对象变为可读或关闭时接收通知。

外部类型的实现§

源代码§

impl AsyncRead for &[u8]

源代码§

fn poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>>

源代码§

impl<P> AsyncRead for Pin<P>
where P: DerefMut, P::Target: AsyncRead,

源代码§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>>

源代码§

impl<T: AsRef<[u8]> + Unpin> AsyncRead for Cursor<T>

源代码§

fn poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>>

源代码§

impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for &mut T

源代码§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>>

源代码§

impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for Box<T>

源代码§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>>

实现者§