| 1 |
//! Definition of the [`MaybeDone`] combinator. |
| 2 |
|
| 3 |
use pin_project_lite::pin_project; |
| 4 |
use std::future::{Future, IntoFuture}; |
| 5 |
use std::pin::Pin; |
| 6 |
use std::task::{Context, Poll}; |
| 7 |
|
| 8 |
pin_project! { |
| 9 |
/// A future that may have completed. |
| 10 |
#[derive(Debug)] |
| 11 |
#[project = MaybeDoneProj] |
| 12 |
#[project_replace = MaybeDoneProjReplace] |
| 13 |
pub enum MaybeDone<Fut: Future> { |
| 14 |
/// A not-yet-completed future. |
| 15 |
Future { #[pin] future: Fut }, |
| 16 |
/// The output of the completed future. |
| 17 |
Done { output: Fut::Output }, |
| 18 |
/// The empty variant after the result of a [`MaybeDone`] has been |
| 19 |
/// taken using the [`take_output`](MaybeDone::take_output) method. |
| 20 |
Gone, |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
/// Wraps a future into a `MaybeDone`. |
| 25 |
pub fn maybe_done<F: IntoFuture>(future: F) -> MaybeDone<F::IntoFuture> { |
| 26 |
MaybeDone::Future { |
| 27 |
future: future.into_future(), |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
impl<Fut: Future> MaybeDone<Fut> { |
| 32 |
/// Returns an [`Option`] containing a mutable reference to the output of the future. |
| 33 |
/// The output of this method will be [`Some`] if and only if the inner |
| 34 |
/// future has been completed and [`take_output`](MaybeDone::take_output) |
| 35 |
/// has not yet been called. |
| 36 |
pub fn output_mut(self: Pin<&mut Self>) -> Option<&mut Fut::Output> { |
| 37 |
match self.project() { |
| 38 |
MaybeDoneProj::Done { output } => Some(output), |
| 39 |
_ => None, |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
/// Attempts to take the output of a `MaybeDone` without driving it |
| 44 |
/// towards completion. |
| 45 |
#[inline] |
| 46 |
pub fn take_output(self: Pin<&mut Self>) -> Option<Fut::Output> { |
| 47 |
match *self { |
| 48 |
MaybeDone::Done { .. } => {} |
| 49 |
MaybeDone::Future { .. } | MaybeDone::Gone => return None, |
| 50 |
}; |
| 51 |
if let MaybeDoneProjReplace::Done { output } = self.project_replace(MaybeDone::Gone) { |
| 52 |
Some(output) |
| 53 |
} else { |
| 54 |
unreachable!() |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
impl<Fut: Future> Future for MaybeDone<Fut> { |
| 60 |
type Output = (); |
| 61 |
|
| 62 |
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 63 |
let output = match self.as_mut().project() { |
| 64 |
MaybeDoneProj::Future { future } => ready!(future.poll(cx)), |
| 65 |
MaybeDoneProj::Done { .. } => return Poll::Ready(()), |
| 66 |
MaybeDoneProj::Gone => panic!("MaybeDone polled after value taken"), |
| 67 |
}; |
| 68 |
self.set(MaybeDone::Done { output }); |
| 69 |
Poll::Ready(()) |
| 70 |
} |
| 71 |
} |