-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Add Future::map
#111347
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Future::map
#111347
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
#![allow(unused)] | ||
|
||
use crate::future::Future; | ||
use crate::pin::Pin; | ||
use crate::task::{Context, Poll}; | ||
use crate::{fmt, mem, ptr}; | ||
|
||
/// A [`Future`] that maps the output of a wrapped [`Future`]. | ||
/// | ||
/// Returned by [`Future::map`]. | ||
#[unstable(feature = "future_map", issue = "none")] | ||
pub struct Map<Fut, F> { | ||
inner: Option<(Fut, F)>, | ||
} | ||
|
||
impl<Fut, F> Map<Fut, F> { | ||
pub(crate) fn new(future: Fut, f: F) -> Self { | ||
Self { inner: Some((future, f)) } | ||
} | ||
} | ||
|
||
#[unstable(feature = "future_map", issue = "none")] | ||
impl<Fut: fmt::Debug, F> fmt::Debug for Map<Fut, F> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
f.debug_struct("Map").field("future", &self.inner.as_ref().map(|(fut, _)| fut)).finish() | ||
} | ||
} | ||
|
||
#[unstable(feature = "future_map", issue = "none")] | ||
impl<Fut: Future, F: FnOnce(Fut::Output) -> U, U> Future for Map<Fut, F> { | ||
type Output = U; | ||
|
||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | ||
// SAFETY: we make sure to not move the inner future | ||
unsafe { | ||
let this = Pin::into_inner_unchecked(self); | ||
match &mut this.inner { | ||
Some((future, _)) => { | ||
let pin = Pin::new_unchecked(&mut *future); | ||
match pin.poll(cx) { | ||
Poll::Ready(value) => { | ||
// The future must be dropped in-place since it is pinned. | ||
ptr::drop_in_place(future); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If the future panics here, Polling the future after panic is a bit of an odd case, but since The efficient, correct, and safe pattern here is using If adding dependencies to core is difficult, I personally recommend vendoring |
||
|
||
let (future, map) = this.inner.take().unwrap_unchecked(); | ||
mem::forget(future); | ||
|
||
Poll::Ready(map(value)) | ||
} | ||
Poll::Pending => Poll::Pending, | ||
} | ||
} | ||
None => panic!("Map must not be polled after it returned `Poll::Ready`"), | ||
} | ||
} | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.