-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fdb9dc2
commit fa59f74
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(()))) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters