I'm trying to implement AsyncRead for a UdpSocket that have an async recv function and I have some difficulties calling poll on my future:
use async_std::{
io::Read as AsyncRead,
net::UdpSocket,
};
struct MyUdpWrapper {
socket: Arc<UdpSocket>,
fut: Option<Box<dyn Future<Output = Result<usize>>>>,
}
impl AsyncRead for MyUdpWrapper {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>> {
let this = Pin::into_inner(self);
let fut = this.fut.unwrap_or(Box::new(this.socket.recv(buf)));
let fut = unsafe { Pin::new_unchecked(&mut *fut) };
fut.poll(cx)
}
}
I was thinking storing the future in an option so it continues to live after the 1st poll but I'm not clear about how to do that exactly.
The async recv() returns a Result so I guess I should store an Option<Box<dyn Future<Output=Result<size>>>>
but that seems a bit cumbersome?
Is there a good way to call an async function in poll_read
(or poll_*
in general)?