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/