Skip to content

Commit a496d51

Browse files
taiki-ecramertj
authored andcommitted
Add future::try_select
1 parent 1dccf75 commit a496d51

File tree

3 files changed

+83
-47
lines changed

3 files changed

+83
-47
lines changed

futures-util/src/try_future/mod.rs

Lines changed: 2 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@ mod try_join_all;
2121
#[cfg(feature = "alloc")]
2222
pub use self::try_join_all::{try_join_all, TryJoinAll};
2323

24-
// TODO
25-
// mod try_select;
26-
// pub use self::try_select::{try_select, TrySelect};
24+
mod try_select;
25+
pub use self::try_select::{try_select, TrySelect};
2726

2827
#[cfg(feature = "alloc")]
2928
mod select_ok;
@@ -319,50 +318,6 @@ pub trait TryFutureExt: TryFuture {
319318
OrElse::new(self, f)
320319
}
321320

322-
/* TODO
323-
/// Waits for either one of two differently-typed futures to complete.
324-
///
325-
/// This function will return a new future which awaits for either this or
326-
/// the `other` future to complete. The returned future will finish with
327-
/// both the value resolved and a future representing the completion of the
328-
/// other work.
329-
///
330-
/// Note that this function consumes the receiving futures and returns a
331-
/// wrapped version of them.
332-
///
333-
/// Also note that if both this and the second future have the same
334-
/// success/error type you can use the `Either::split` method to
335-
/// conveniently extract out the value at the end.
336-
///
337-
/// # Examples
338-
///
339-
/// ```
340-
/// use futures::future::{self, Either};
341-
///
342-
/// // A poor-man's join implemented on top of select
343-
///
344-
/// fn join<A, B, E>(a: A, b: B) -> Box<Future<Item=(A::Item, B::Item), Error=E>>
345-
/// where A: Future<Error = E> + 'static,
346-
/// B: Future<Error = E> + 'static,
347-
/// E: 'static,
348-
/// {
349-
/// Box::new(a.select(b).then(|res| -> Box<Future<Item=_, Error=_>> {
350-
/// match res {
351-
/// Ok(Either::Left((x, b))) => Box::new(b.map(move |y| (x, y))),
352-
/// Ok(Either::Right((y, a))) => Box::new(a.map(move |x| (x, y))),
353-
/// Err(Either::Left((e, _))) => Box::new(future::err(e)),
354-
/// Err(Either::Right((e, _))) => Box::new(future::err(e)),
355-
/// }
356-
/// }))
357-
/// }}
358-
/// ```
359-
fn select<B>(self, other: B) -> Select<Self, B::Future>
360-
where B: IntoFuture, Self: Sized
361-
{
362-
select::new(self, other.into_future())
363-
}
364-
*/
365-
366321
/// Unwraps this future's ouput, producing a future with this future's
367322
/// [`Ok`](TryFuture::Ok) type as its
368323
/// [`Output`](std::future::Future::Output) type.
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
use core::pin::Pin;
2+
use futures_core::future::{Future, TryFuture};
3+
use futures_core::task::{Context, Poll};
4+
use crate::future::Either;
5+
6+
/// Future for the [`try_select()`] function.
7+
#[must_use = "futures do nothing unless you `.await` or poll them"]
8+
#[derive(Debug)]
9+
pub struct TrySelect<A: Unpin, B: Unpin> {
10+
inner: Option<(A, B)>,
11+
}
12+
13+
impl<A: Unpin, B: Unpin> Unpin for TrySelect<A, B> {}
14+
15+
/// Waits for either one of two differently-typed futures to complete.
16+
///
17+
/// This function will return a new future which awaits for either one of both
18+
/// futures to complete. The returned future will finish with both the value
19+
/// resolved and a future representing the completion of the other work.
20+
///
21+
/// Note that this function consumes the receiving futures and returns a
22+
/// wrapped version of them.
23+
///
24+
/// Also note that if both this and the second future have the same
25+
/// success/error type you can use the `Either::factor_first` method to
26+
/// conveniently extract out the value at the end.
27+
///
28+
/// # Examples
29+
///
30+
/// ```
31+
/// use futures::future::{self, Either, Future, FutureExt, TryFuture, TryFutureExt};
32+
///
33+
/// // A poor-man's try_join implemented on top of select
34+
///
35+
/// fn try_join<A, B, E>(a: A, b: B) -> impl TryFuture<Ok=(A::Ok, B::Ok), Error=E>
36+
/// where A: TryFuture<Error = E> + Unpin + 'static,
37+
/// B: TryFuture<Error = E> + Unpin + 'static,
38+
/// E: 'static,
39+
/// {
40+
/// future::try_select(a, b).then(|res| -> Box<dyn Future<Output = Result<_, _>> + Unpin> {
41+
/// match res {
42+
/// Ok(Either::Left((x, b))) => Box::new(b.map_ok(move |y| (x, y))),
43+
/// Ok(Either::Right((y, a))) => Box::new(a.map_ok(move |x| (x, y))),
44+
/// Err(Either::Left((e, _))) => Box::new(future::err(e)),
45+
/// Err(Either::Right((e, _))) => Box::new(future::err(e)),
46+
/// }
47+
/// })
48+
/// }
49+
/// ```
50+
pub fn try_select<A, B>(future1: A, future2: B) -> TrySelect<A, B>
51+
where A: TryFuture + Unpin, B: TryFuture + Unpin
52+
{
53+
TrySelect { inner: Some((future1, future2)) }
54+
}
55+
56+
impl<A: Unpin, B: Unpin> Future for TrySelect<A, B>
57+
where A: TryFuture, B: TryFuture
58+
{
59+
#[allow(clippy::type_complexity)]
60+
type Output = Result<
61+
Either<(A::Ok, B), (B::Ok, A)>,
62+
Either<(A::Error, B), (B::Error, A)>,
63+
>;
64+
65+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
66+
let (mut a, mut b) = self.inner.take().expect("cannot poll Select twice");
67+
match Pin::new(&mut a).try_poll(cx) {
68+
Poll::Ready(Err(x)) => Poll::Ready(Err(Either::Left((x, b)))),
69+
Poll::Ready(Ok(x)) => Poll::Ready(Ok(Either::Left((x, b)))),
70+
Poll::Pending => match Pin::new(&mut b).try_poll(cx) {
71+
Poll::Ready(Err(x)) => Poll::Ready(Err(Either::Right((x, a)))),
72+
Poll::Ready(Ok(x)) => Poll::Ready(Ok(Either::Right((x, a)))),
73+
Poll::Pending => {
74+
self.inner = Some((a, b));
75+
Poll::Pending
76+
}
77+
}
78+
}
79+
}
80+
}

futures/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ pub mod future {
247247
pub use futures_util::try_future::{
248248
try_join, try_join3, try_join4, try_join5,
249249
TryJoin, TryJoin3, TryJoin4, TryJoin5,
250+
try_select, TrySelect,
250251

251252
TryFutureExt,
252253
AndThen, ErrInto, FlattenSink, IntoFuture, MapErr, MapOk, OrElse,

0 commit comments

Comments
 (0)