1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use std::{future::IntoFuture, pin::Pin};

use futures::FutureExt;

/// A future will polling a wrapped future once within the current async context.
pub struct PollOnce<Fut> {
    fut: Pin<Box<Fut>>,
}

impl<T> From<T> for PollOnce<T::IntoFuture>
where
    T: IntoFuture,
{
    fn from(value: T) -> Self {
        Self::new(value.into_future())
    }
}

impl<Fut> PollOnce<Fut> {
    pub fn new(fut: Fut) -> Self {
        Self { fut: Box::pin(fut) }
    }
}

impl<Fut, R> std::future::Future for PollOnce<Fut>
where
    Fut: std::future::Future<Output = R>,
{
    type Output = std::task::Poll<R>;
    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        std::task::Poll::Ready(self.fut.poll_unpin(cx))
    }
}

#[macro_export]
macro_rules! poll_once {
    ($fut: expr) => {
        $crate::poll::PollOnce::new($fut).await
    };
}