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
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

pin_project_lite::pin_project! {
    pub struct MaybeFuture<O, F: Future<Output=O>> {
        #[pin]
        inner: Option<F>,
    }
}

impl<O, F: Future<Output = O>> MaybeFuture<O, F> {
    pub fn new(inner: Option<F>) -> Self {
        Self { inner }
    }

    pub fn into_inner(self) -> Option<F> {
        self.inner
    }

    pub fn inner(&self) -> &Option<F> {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut Option<F> {
        &mut self.inner
    }
}

impl<O, F: Future<Output = O>> Future for MaybeFuture<O, F> {
    type Output = O;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        match this.inner.as_pin_mut() {
            Some(inner) => inner.poll(cx),
            None => Poll::Pending,
        }
    }
}