Skip to content

Commit

Permalink
MaybeFuture
Browse files Browse the repository at this point in the history
  • Loading branch information
andyleiserson committed Mar 11, 2024
1 parent fdb9dc2 commit fa59f74
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
44 changes: 44 additions & 0 deletions ipa-core/src/helpers/futures.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};

use pin_project::pin_project;

#[pin_project(project = MaybeFutureProj)]
pub enum MaybeFuture<Fut: Future> {
Future(#[pin] Fut),
Value(Option<Fut::Output>),
}

impl<Fut: Future> Future for MaybeFuture<Fut> {
type Output = Fut::Output;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.project() {
MaybeFutureProj::Future(fut) => fut.poll(cx),
MaybeFutureProj::Value(val) => Poll::Ready(val.take().unwrap()),
}
}
}

impl<Fut: Future> MaybeFuture<Fut> {
pub fn future(fut: Fut) -> Self {
MaybeFuture::Future(fut)
}

pub fn value(val: Fut::Output) -> Self {
MaybeFuture::Value(Some(val))
}
}

impl<Fut: Future<Output = Result<(), E>>, E> MaybeFuture<Fut> {
pub fn future_or_ok<F: FnOnce() -> Fut>(condition: bool, f: F) -> Self {
if condition {
MaybeFuture::Future(f())
} else {
MaybeFuture::Value(Some(Ok(())))
}
}
}
2 changes: 2 additions & 0 deletions ipa-core/src/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use generic_array::GenericArray;

mod buffers;
mod error;
mod futures;
mod gateway;
pub(crate) mod prss_protocol;
mod transport;
Expand All @@ -18,6 +19,7 @@ use std::ops::{Index, IndexMut};
#[cfg(test)]
pub use buffers::OrderingSender;
pub use error::{Error, Result};
pub use futures::MaybeFuture;

#[cfg(feature = "stall-detection")]
mod gateway_exports {
Expand Down

0 comments on commit fa59f74

Please sign in to comment.