use core::pin::Pin; use core::task::Poll; #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] /// Adapter from `tokio::io` traits. pub struct FromTokio { inner: T, } impl FromTokio { /// Create a new adapter. pub fn new(inner: T) -> Self { Self { inner } } /// Consume the adapter, returning the inner object. pub fn into_inner(self) -> T { self.inner } } impl FromTokio { /// Borrow the inner object. pub fn inner(&self) -> &T { &self.inner } /// Mutably borrow the inner object. pub fn inner_mut(&mut self) -> &mut T { &mut self.inner } } impl crate::Io for FromTokio { type Error = std::io::Error; } impl crate::asynch::Read for FromTokio { async fn read(&mut self, buf: &mut [u8]) -> Result { poll_fn::poll_fn(|cx| { let mut buf = tokio::io::ReadBuf::new(buf); match Pin::new(&mut self.inner).poll_read(cx, &mut buf) { Poll::Ready(r) => match r { Ok(()) => Poll::Ready(Ok(buf.filled().len())), Err(e) => Poll::Ready(Err(e)), }, Poll::Pending => Poll::Pending, } }) .await } } impl crate::asynch::Write for FromTokio { async fn write(&mut self, buf: &[u8]) -> Result { poll_fn::poll_fn(|cx| Pin::new(&mut self.inner).poll_write(cx, buf)).await } async fn flush(&mut self) -> Result<(), Self::Error> { poll_fn::poll_fn(|cx| Pin::new(&mut self.inner).poll_flush(cx)).await } } impl crate::asynch::Seek for FromTokio { async fn seek(&mut self, pos: crate::SeekFrom) -> Result { // Note: `start_seek` can return an error if there is another seek in progress. // Therefor it is recommended to call `poll_complete` before any call to `start_seek`. poll_fn::poll_fn(|cx| Pin::new(&mut self.inner).poll_complete(cx)).await?; Pin::new(&mut self.inner).start_seek(pos.into())?; poll_fn::poll_fn(|cx| Pin::new(&mut self.inner).poll_complete(cx)).await } } // TODO: ToTokio. // It's a bit tricky because tokio::io is "stateless", while we're "stateful" (we // return futures that borrow Self and get polled for the duration of the operation.) // It can probably done by storing the futures in Self, with unsafe Pin hacks because // we're a self-referential struct mod poll_fn { use core::future::Future; use core::pin::Pin; use core::task::{Context, Poll}; struct PollFn { f: F, } impl Unpin for PollFn {} pub fn poll_fn(f: F) -> impl Future where F: FnMut(&mut Context<'_>) -> Poll, { PollFn { f } } impl Future for PollFn where F: FnMut(&mut Context<'_>) -> Poll, { type Output = T; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { (&mut self.f)(cx) } } }