maybe_future/
lib.rs

1use std::{
2    future::Future,
3    pin::Pin,
4    task::{Context, Poll},
5};
6
7pin_project_lite::pin_project! {
8    pub struct MaybeFuture<O, F: Future<Output=O>> {
9        #[pin]
10        inner: Option<F>,
11    }
12}
13
14impl<O, F: Future<Output = O>> MaybeFuture<O, F> {
15    pub fn new(inner: Option<F>) -> Self {
16        Self { inner }
17    }
18
19    pub fn into_inner(self) -> Option<F> {
20        self.inner
21    }
22
23    pub fn inner(&self) -> &Option<F> {
24        &self.inner
25    }
26
27    pub fn inner_mut(&mut self) -> &mut Option<F> {
28        &mut self.inner
29    }
30
31    pub fn reset(self: Pin<&mut Self>, value: Option<F>) {
32        let mut this = self.project();
33        this.inner.set(value);
34    }
35}
36
37impl<O, F: Future<Output = O>> Future for MaybeFuture<O, F> {
38    type Output = O;
39
40    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
41        let this = self.project();
42        match this.inner.as_pin_mut() {
43            Some(inner) => inner.poll(cx),
44            None => Poll::Pending,
45        }
46    }
47}