rust - 当poll_read的缓冲区大小不足以容纳我的缓冲区时该怎么办?

标签 rust

Rust的 future 使用poll_read(poll_read)轮询可用数据:

fn poll_read(
    &mut self, 
    cx: &mut Context, 
    buf: &mut [u8]
) -> Result<Async<usize>, Error>
显然,当被调用时,poll_read函数用数据填充buf并返回Poll::Ready(n),其中n是写入缓冲区的数量。如果目前没有可用数据,则返回Poll::Pending。将来的调用者可以再次poll_read或不。在不再轮询的情况下,它将为poll_read函数提供机会告知何时必须对其进行轮询。它通过在有可用数据时调用cx.waker().wake()来实现。
因此,例如,我可以为我的结构实现poll_read:
fn poll_read(
    &mut self, 
    cx: &mut Context, 
    buf: &mut [u8]
) -> Result<Async<usize>, Error> {
    let my_buffer = get_buffer_from_internet();
    if my_buffer.len() <= buf.capacity() {
        buf.put_slice(my_buffer);
        return Poll::Ready(my_buffer.len());
    } else {
        //we can only fill buf partially
        buf.put_slice(my_buffer);
        //let's store the remaining in our struct
        self.remaining.store(&my_buffer[buf.len()..]);
        //How can I make the future caller know it needs to call poll_read again to read the remaining data? Can I call cx.waker().wake() while inside the poll_read?
        return Poll::Ready(buf.len());
    }
}
您会看到在buf上没有足够空间的情况下,我只复制了所需的数据,然后将剩余的数据存储在我们的结构中。因此,我们可以在从互联网上获取新数据之前,通过检查是否还有剩余数据要写入来增强poll_read。但正如您在我的评论中看到的:How can I make the future caller know it needs to call poll_read again to read the remaining data? Can I call cx.waker().wake() while inside the poll_read?

最佳答案

您无需执行任何操作。该文档的内容如下:

If no data is available for reading, the method returns Poll::Pending and arranges for the current task to receive a notification when the object becomes readable or is closed.


如果它返回数据,则无需安排唤醒。例如,implementation for Cursor<T> 仅遵从io::Read,而完全忽略Context,而不管缓冲区是否足够大。
轮询程序应该知道在poll_read返回Poll::Ready(Ok(0))之前,仍有可能要读取数据。

关于rust - 当poll_read的缓冲区大小不足以容纳我的缓冲区时该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66502695/

相关文章:

rust - 可变借用以解决结构持有引用问题

rust - 更新注册表 `https://example.com/`

rust - 克隆&[u32]至[u32]

rust - 如何在 Rust 中 for_each 然后对它们进行计数?

types - 了解类型归属问题

rust - Malloc 一个带有 Rust 布局的数组

rust - 是否可以以普通绑定(bind)的方式定义(递归)函数?

rust - 如何在 Substrate 中实现后台线程?

rust - 在 Rust 中反转字符串

rust - 将选项或结果向量转换为仅成功值时,如何避免展开?