Skip to content
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

Constrain Future::Output in supertrait of TryFuture #2763

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 5 additions & 26 deletions futures-core/src/future.rs
Expand Up @@ -2,7 +2,6 @@

use core::ops::DerefMut;
use core::pin::Pin;
use core::task::{Context, Poll};

#[doc(no_inline)]
pub use core::future::Future;
Expand All @@ -20,10 +19,10 @@ pub type LocalBoxFuture<'a, T> = Pin<alloc::boxed::Box<dyn Future<Output = T> +
/// should no longer be polled.
///
/// `is_terminated` will return `true` if a future should no longer be polled.
/// Usually, this state occurs after `poll` (or `try_poll`) returned
/// `Poll::Ready`. However, `is_terminated` may also return `true` if a future
/// has become inactive and can no longer make progress and should be ignored
/// or dropped rather than being `poll`ed again.
/// Usually, this state occurs after `poll` returned `Poll::Ready`. However,
/// `is_terminated` may also return `true` if a future has become inactive
/// and can no longer make progress and should be ignored or dropped rather
/// than being `poll`ed again.
pub trait FusedFuture: Future {
/// Returns `true` if the underlying future should no longer be polled.
fn is_terminated(&self) -> bool;
Expand All @@ -45,29 +44,14 @@ where
}
}

mod private_try_future {
use super::Future;

pub trait Sealed {}

impl<F, T, E> Sealed for F where F: ?Sized + Future<Output = Result<T, E>> {}
}

/// A convenience for futures that return `Result` values that includes
/// a variety of adapters tailored to such futures.
pub trait TryFuture: Future + private_try_future::Sealed {
pub trait TryFuture: Future<Output = Result<Self::Ok, Self::Error>> {
/// The type of successful values yielded by this future
type Ok;

/// The type of failures yielded by this future
type Error;

/// Poll this `TryFuture` as if it were a `Future`.
///
/// This method is a stopgap for a compiler limitation that prevents us from
/// directly inheriting from the `Future` trait; in the future it won't be
/// needed.
fn try_poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<Self::Ok, Self::Error>>;
}

impl<F, T, E> TryFuture for F
Expand All @@ -76,11 +60,6 @@ where
{
type Ok = T;
type Error = E;

#[inline]
fn try_poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.poll(cx)
}
}

#[cfg(feature = "alloc")]
Expand Down
2 changes: 1 addition & 1 deletion futures-util/src/compat/compat03as01.rs
Expand Up @@ -102,7 +102,7 @@ where
type Error = Fut::Error;

fn poll(&mut self) -> Poll01<Self::Item, Self::Error> {
with_context(self, |inner, cx| poll_03_to_01(inner.try_poll(cx)))
with_context(self, |inner, cx| poll_03_to_01(inner.poll(cx)))
}
}

Expand Down
4 changes: 2 additions & 2 deletions futures-util/src/future/mod.rs
Expand Up @@ -40,8 +40,8 @@ pub use self::future::{Shared, WeakShared};

mod try_future;
pub use self::try_future::{
AndThen, ErrInto, InspectErr, InspectOk, IntoFuture, MapErr, MapOk, MapOkOrElse, OkInto,
OrElse, TryFlatten, TryFlattenStream, TryFutureExt, UnwrapOrElse,
AndThen, ErrInto, InspectErr, InspectOk, MapErr, MapOk, MapOkOrElse, OkInto, OrElse,
TryFlatten, TryFlattenStream, TryFutureExt, UnwrapOrElse,
};

#[cfg(feature = "sink")]
Expand Down
4 changes: 2 additions & 2 deletions futures-util/src/future/select_ok.rs
@@ -1,5 +1,5 @@
use super::assert_future;
use crate::future::TryFutureExt;
use crate::future::FutureExt;
use alloc::vec::Vec;
use core::iter::FromIterator;
use core::mem;
Expand Down Expand Up @@ -49,7 +49,7 @@ impl<Fut: TryFuture + Unpin> Future for SelectOk<Fut> {
// loop until we've either exhausted all errors, a success was hit, or nothing is ready
loop {
let item =
self.inner.iter_mut().enumerate().find_map(|(i, f)| match f.try_poll_unpin(cx) {
self.inner.iter_mut().enumerate().find_map(|(i, f)| match f.poll_unpin(cx) {
Poll::Pending => None,
Poll::Ready(e) => Some((i, e)),
});
Expand Down
36 changes: 0 additions & 36 deletions futures-util/src/future/try_future/into_future.rs

This file was deleted.

72 changes: 13 additions & 59 deletions futures-util/src/future/try_future/mod.rs
Expand Up @@ -5,12 +5,7 @@

#[cfg(feature = "compat")]
use crate::compat::Compat;
use core::pin::Pin;
use futures_core::{
future::TryFuture,
stream::TryStream,
task::{Context, Poll},
};
use futures_core::{future::TryFuture, stream::TryStream};
#[cfg(feature = "sink")]
use futures_sink::Sink;

Expand All @@ -23,7 +18,6 @@ use crate::future::{assert_future, Inspect, Map};
use crate::stream::assert_stream;

// Combinators
mod into_future;
mod try_flatten;
mod try_flatten_err;

Expand Down Expand Up @@ -89,46 +83,43 @@ delegate_all!(
delegate_all!(
/// Future for the [`inspect_ok`](super::TryFutureExt::inspect_ok) method.
InspectOk<Fut, F>(
Inspect<IntoFuture<Fut>, InspectOkFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Inspect::new(IntoFuture::new(x), inspect_ok_fn(f))]
Inspect<Fut, InspectOkFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Inspect::new(x, inspect_ok_fn(f))]
);

delegate_all!(
/// Future for the [`inspect_err`](super::TryFutureExt::inspect_err) method.
InspectErr<Fut, F>(
Inspect<IntoFuture<Fut>, InspectErrFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Inspect::new(IntoFuture::new(x), inspect_err_fn(f))]
Inspect<Fut, InspectErrFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Inspect::new(x, inspect_err_fn(f))]
);

#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
pub use self::into_future::IntoFuture;

delegate_all!(
/// Future for the [`map_ok`](TryFutureExt::map_ok) method.
MapOk<Fut, F>(
Map<IntoFuture<Fut>, MapOkFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Map::new(IntoFuture::new(x), map_ok_fn(f))]
Map<Fut, MapOkFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Map::new(x, map_ok_fn(f))]
);

delegate_all!(
/// Future for the [`map_err`](TryFutureExt::map_err) method.
MapErr<Fut, F>(
Map<IntoFuture<Fut>, MapErrFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Map::new(IntoFuture::new(x), map_err_fn(f))]
Map<Fut, MapErrFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Map::new(x, map_err_fn(f))]
);

delegate_all!(
/// Future for the [`map_ok_or_else`](TryFutureExt::map_ok_or_else) method.
MapOkOrElse<Fut, F, G>(
Map<IntoFuture<Fut>, MapOkOrElseFn<F, G>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F, g: G| Map::new(IntoFuture::new(x), map_ok_or_else_fn(f, g))]
Map<Fut, MapOkOrElseFn<F, G>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F, g: G| Map::new(x, map_ok_or_else_fn(f, g))]
);

delegate_all!(
/// Future for the [`unwrap_or_else`](TryFutureExt::unwrap_or_else) method.
UnwrapOrElse<Fut, F>(
Map<IntoFuture<Fut>, UnwrapOrElseFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Map::new(IntoFuture::new(x), unwrap_or_else_fn(f))]
Map<Fut, UnwrapOrElseFn<F>>
): Debug + Future + FusedFuture + New[|x: Fut, f: F| Map::new(x, unwrap_or_else_fn(f))]
);

impl<Fut: ?Sized + TryFuture> TryFutureExt for Fut {}
Expand Down Expand Up @@ -585,41 +576,4 @@ pub trait TryFutureExt: TryFuture {
{
Compat::new(self)
}

/// Wraps a [`TryFuture`] into a type that implements
/// [`Future`](std::future::Future).
///
/// [`TryFuture`]s currently do not implement the
/// [`Future`](std::future::Future) trait due to limitations of the
/// compiler.
///
/// # Examples
///
/// ```
/// use futures::future::{Future, TryFuture, TryFutureExt};
///
/// # type T = i32;
/// # type E = ();
/// fn make_try_future() -> impl TryFuture<Ok = T, Error = E> { // ... }
/// # async { Ok::<i32, ()>(1) }
/// # }
/// fn take_future(future: impl Future<Output = Result<T, E>>) { /* ... */ }
///
/// take_future(make_try_future().into_future());
/// ```
fn into_future(self) -> IntoFuture<Self>
where
Self: Sized,
{
assert_future::<Result<Self::Ok, Self::Error>, _>(IntoFuture::new(self))
}

/// A convenience method for calling [`TryFuture::try_poll`] on [`Unpin`]
/// future types.
fn try_poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<Self::Ok, Self::Error>>
where
Self: Unpin,
{
Pin::new(self).try_poll(cx)
}
}
8 changes: 4 additions & 4 deletions futures-util/src/future/try_future/try_flatten.rs
Expand Up @@ -43,15 +43,15 @@ where
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(loop {
match self.as_mut().project() {
TryFlattenProj::First { f } => match ready!(f.try_poll(cx)) {
TryFlattenProj::First { f } => match ready!(f.poll(cx)) {
Ok(f) => self.set(Self::Second { f }),
Err(e) => {
self.set(Self::Empty);
break Err(e);
}
},
TryFlattenProj::Second { f } => {
let output = ready!(f.try_poll(cx));
let output = ready!(f.poll(cx));
self.set(Self::Empty);
break output;
}
Expand Down Expand Up @@ -81,7 +81,7 @@ where
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Poll::Ready(loop {
match self.as_mut().project() {
TryFlattenProj::First { f } => match ready!(f.try_poll(cx)) {
TryFlattenProj::First { f } => match ready!(f.poll(cx)) {
Ok(f) => self.set(Self::Second { f }),
Err(e) => {
self.set(Self::Empty);
Expand Down Expand Up @@ -112,7 +112,7 @@ where
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(loop {
match self.as_mut().project() {
TryFlattenProj::First { f } => match ready!(f.try_poll(cx)) {
TryFlattenProj::First { f } => match ready!(f.poll(cx)) {
Ok(f) => self.set(Self::Second { f }),
Err(e) => {
self.set(Self::Empty);
Expand Down
4 changes: 2 additions & 2 deletions futures-util/src/future/try_future/try_flatten_err.rs
Expand Up @@ -40,15 +40,15 @@ where
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(loop {
match self.as_mut().project() {
TryFlattenErrProj::First { f } => match ready!(f.try_poll(cx)) {
TryFlattenErrProj::First { f } => match ready!(f.poll(cx)) {
Err(f) => self.set(Self::Second { f }),
Ok(e) => {
self.set(Self::Empty);
break Ok(e);
}
},
TryFlattenErrProj::Second { f } => {
let output = ready!(f.try_poll(cx));
let output = ready!(f.poll(cx));
self.set(Self::Empty);
break output;
}
Expand Down
11 changes: 5 additions & 6 deletions futures-util/src/future/try_join_all.rs
Expand Up @@ -10,11 +10,10 @@ use core::mem;
use core::pin::Pin;
use core::task::{Context, Poll};

use super::{assert_future, join_all, IntoFuture, TryFuture, TryMaybeDone};
use super::{assert_future, join_all, TryFuture, TryMaybeDone};

#[cfg(not(futures_no_atomic_cas))]
use crate::stream::{FuturesOrdered, TryCollect, TryStreamExt};
use crate::TryFutureExt;

enum FinalState<E = ()> {
Pending,
Expand All @@ -36,11 +35,11 @@ where
F: TryFuture,
{
Small {
elems: Pin<Box<[TryMaybeDone<IntoFuture<F>>]>>,
elems: Pin<Box<[TryMaybeDone<F>]>>,
},
#[cfg(not(futures_no_atomic_cas))]
Big {
fut: TryCollect<FuturesOrdered<IntoFuture<F>>, Vec<F::Ok>>,
fut: TryCollect<FuturesOrdered<F>, Vec<F::Ok>>,
},
}

Expand Down Expand Up @@ -119,7 +118,7 @@ where
I: IntoIterator,
I::Item: TryFuture,
{
let iter = iter.into_iter().map(TryFutureExt::into_future);
let iter = iter.into_iter();

#[cfg(futures_no_atomic_cas)]
{
Expand Down Expand Up @@ -159,7 +158,7 @@ where
let mut state = FinalState::AllDone;

for elem in join_all::iter_pin_mut(elems.as_mut()) {
match elem.try_poll(cx) {
match elem.poll(cx) {
Poll::Pending => state = FinalState::Pending,
Poll::Ready(Ok(())) => {}
Poll::Ready(Err(e)) => {
Expand Down
2 changes: 1 addition & 1 deletion futures-util/src/future/try_maybe_done.rs
Expand Up @@ -76,7 +76,7 @@ impl<Fut: TryFuture> Future for TryMaybeDone<Fut> {
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
unsafe {
match self.as_mut().get_unchecked_mut() {
TryMaybeDone::Future(f) => match ready!(Pin::new_unchecked(f).try_poll(cx)) {
TryMaybeDone::Future(f) => match ready!(Pin::new_unchecked(f).poll(cx)) {
Ok(res) => self.set(Self::Done(res)),
Err(e) => {
self.set(Self::Gone);
Expand Down
6 changes: 3 additions & 3 deletions futures-util/src/future/try_select.rs
@@ -1,4 +1,4 @@
use crate::future::{Either, TryFutureExt};
use crate::future::{Either, FutureExt};
use core::pin::Pin;
use futures_core::future::{Future, TryFuture};
use futures_core::task::{Context, Poll};
Expand Down Expand Up @@ -69,10 +69,10 @@ where

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let (mut a, mut b) = self.inner.take().expect("cannot poll Select twice");
match a.try_poll_unpin(cx) {
match a.poll_unpin(cx) {
Poll::Ready(Err(x)) => Poll::Ready(Err(Either::Left((x, b)))),
Poll::Ready(Ok(x)) => Poll::Ready(Ok(Either::Left((x, b)))),
Poll::Pending => match b.try_poll_unpin(cx) {
Poll::Pending => match b.poll_unpin(cx) {
Poll::Ready(Err(x)) => Poll::Ready(Err(Either::Right((x, a)))),
Poll::Ready(Ok(x)) => Poll::Ready(Ok(Either::Right((x, a)))),
Poll::Pending => {
Expand Down
2 changes: 1 addition & 1 deletion futures-util/src/stream/stream/try_fold.rs
Expand Up @@ -70,7 +70,7 @@ where
Poll::Ready(loop {
if let Some(fut) = this.future.as_mut().as_pin_mut() {
// we're currently processing a future to produce a new accum value
let res = ready!(fut.try_poll(cx));
let res = ready!(fut.poll(cx));
this.future.set(None);
match res {
Ok(a) => *this.accum = Some(a),
Expand Down