Coverage Report

Created: 2026-03-31 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/futures-util-0.3.32/src/future/select.rs
Line
Count
Source
1
use super::assert_future;
2
use crate::future::{Either, FutureExt};
3
use core::pin::Pin;
4
use futures_core::future::{FusedFuture, Future};
5
use futures_core::task::{Context, Poll};
6
7
/// Future for the [`select()`] function.
8
#[must_use = "futures do nothing unless you `.await` or poll them"]
9
#[derive(Debug)]
10
pub struct Select<A, B> {
11
    inner: Option<(A, B)>,
12
}
13
14
impl<A: Unpin, B: Unpin> Unpin for Select<A, B> {}
15
16
/// Waits for either one of two differently-typed futures to complete.
17
///
18
/// This function will return a new future which awaits for either one of both
19
/// futures to complete. The returned future will finish with both the value
20
/// resolved and a future representing the completion of the other work.
21
///
22
/// Note that this function consumes the receiving futures and returns a
23
/// wrapped version of them.
24
///
25
/// Also note that if both this and the second future have the same
26
/// output type you can use the `Either::factor_first` method to
27
/// conveniently extract out the value at the end.
28
///
29
/// # Examples
30
///
31
/// A simple example
32
///
33
/// ```
34
/// # futures::executor::block_on(async {
35
/// use core::pin::pin;
36
///
37
/// use futures::future;
38
/// use futures::future::Either;
39
///
40
/// // These two futures have different types even though their outputs have the same type.
41
/// let future1 = async {
42
///     future::pending::<()>().await; // will never finish
43
///     1
44
/// };
45
/// let future2 = async {
46
///     future::ready(2).await
47
/// };
48
///
49
/// // 'select' requires Future + Unpin bounds
50
/// let future1 = pin!(future1);
51
/// let future2 = pin!(future2);
52
///
53
/// let value = match future::select(future1, future2).await {
54
///     Either::Left((value1, _)) => value1,  // `value1` is resolved from `future1`
55
///                                           // `_` represents `future2`
56
///     Either::Right((value2, _)) => value2, // `value2` is resolved from `future2`
57
///                                           // `_` represents `future1`
58
/// };
59
///
60
/// assert!(value == 2);
61
/// # });
62
/// ```
63
///
64
/// A more complex example
65
///
66
/// ```
67
/// use futures::future::{self, Either, Future, FutureExt};
68
///
69
/// // A poor-man's join implemented on top of select
70
///
71
/// fn join<A, B>(a: A, b: B) -> impl Future<Output=(A::Output, B::Output)>
72
///     where A: Future + Unpin,
73
///           B: Future + Unpin,
74
/// {
75
///     future::select(a, b).then(|either| {
76
///         match either {
77
///             Either::Left((x, b)) => b.map(move |y| (x, y)).left_future(),
78
///             Either::Right((y, a)) => a.map(move |x| (x, y)).right_future(),
79
///         }
80
///     })
81
/// }
82
/// ```
83
0
pub fn select<A, B>(future1: A, future2: B) -> Select<A, B>
84
0
where
85
0
    A: Future + Unpin,
86
0
    B: Future + Unpin,
87
{
88
0
    assert_future::<Either<(A::Output, B), (B::Output, A)>, _>(Select {
89
0
        inner: Some((future1, future2)),
90
0
    })
91
0
}
Unexecuted instantiation: futures_util::future::select::select::<core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>, core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>>
Unexecuted instantiation: futures_util::future::select::select::<core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>, core::pin::Pin<&mut tokio::time::sleep::Sleep>>
Unexecuted instantiation: futures_util::future::select::select::<hyper_util::client::legacy::pool::Checkout<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::common::lazy::Lazy<<hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}, futures_util::future::either::Either<futures_util::future::try_future::AndThen<futures_util::future::try_future::MapErr<hyper_util::service::oneshot::Oneshot<reqwest::connect::Connector, http::uri::Uri>, <hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#0}>, futures_util::future::either::Either<core::pin::Pin<alloc::boxed::Box<<hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#1}::{closure#0}>>, futures_util::future::ready::Ready<core::result::Result<hyper_util::client::legacy::pool::Pooled<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::client::legacy::client::Error>>>, <hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#1}>, futures_util::future::ready::Ready<core::result::Result<hyper_util::client::legacy::pool::Pooled<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::client::legacy::client::Error>>>>>
Unexecuted instantiation: futures_util::future::select::select::<&mut futures_channel::oneshot::Receiver<core::convert::Infallible>, &mut core::pin::Pin<alloc::boxed::Box<dyn hyper::rt::timer::Sleep<Output = ()>>>>
Unexecuted instantiation: futures_util::future::select::select::<_, _>
92
93
impl<A, B> Future for Select<A, B>
94
where
95
    A: Future + Unpin,
96
    B: Future + Unpin,
97
{
98
    type Output = Either<(A::Output, B), (B::Output, A)>;
99
100
0
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
101
        /// When compiled with `-C opt-level=z`, this function will help the compiler eliminate the `None` branch, where
102
        /// `Option::unwrap` does not.
103
        #[inline(always)]
104
0
        fn unwrap_option<T>(value: Option<T>) -> T {
105
0
            match value {
106
0
                None => unreachable!(),
107
0
                Some(value) => value,
108
            }
109
0
        }
Unexecuted instantiation: <futures_util::future::select::Select<_, _> as core::future::future::Future>::poll::unwrap_option::<(core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>, core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>)>
Unexecuted instantiation: <futures_util::future::select::Select<_, _> as core::future::future::Future>::poll::unwrap_option::<(core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>, core::pin::Pin<&mut tokio::time::sleep::Sleep>)>
Unexecuted instantiation: <futures_util::future::select::Select<_, _> as core::future::future::Future>::poll::unwrap_option::<(hyper_util::client::legacy::pool::Checkout<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::common::lazy::Lazy<<hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}, futures_util::future::either::Either<futures_util::future::try_future::AndThen<futures_util::future::try_future::MapErr<hyper_util::service::oneshot::Oneshot<reqwest::connect::Connector, http::uri::Uri>, <hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#0}>, futures_util::future::either::Either<core::pin::Pin<alloc::boxed::Box<<hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#1}::{closure#0}>>, futures_util::future::ready::Ready<core::result::Result<hyper_util::client::legacy::pool::Pooled<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::client::legacy::client::Error>>>, <hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#1}>, futures_util::future::ready::Ready<core::result::Result<hyper_util::client::legacy::pool::Pooled<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::client::legacy::client::Error>>>>)>
Unexecuted instantiation: <futures_util::future::select::Select<_, _> as core::future::future::Future>::poll::unwrap_option::<(&mut futures_channel::oneshot::Receiver<core::convert::Infallible>, &mut core::pin::Pin<alloc::boxed::Box<dyn hyper::rt::timer::Sleep<Output = ()>>>)>
Unexecuted instantiation: <futures_util::future::select::Select<_, _> as core::future::future::Future>::poll::unwrap_option::<_>
110
111
0
        let (a, b) = self.inner.as_mut().expect("cannot poll Select twice");
112
113
0
        if let Poll::Ready(val) = a.poll_unpin(cx) {
114
0
            return Poll::Ready(Either::Left((val, unwrap_option(self.inner.take()).1)));
115
0
        }
116
117
0
        if let Poll::Ready(val) = b.poll_unpin(cx) {
118
0
            return Poll::Ready(Either::Right((val, unwrap_option(self.inner.take()).0)));
119
0
        }
120
121
0
        Poll::Pending
122
0
    }
Unexecuted instantiation: <futures_util::future::select::Select<core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>, core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>> as core::future::future::Future>::poll
Unexecuted instantiation: <futures_util::future::select::Select<core::pin::Pin<&mut <hyper_util::client::legacy::connect::http::ConnectingTcpRemote>::connect::{closure#0}>, core::pin::Pin<&mut tokio::time::sleep::Sleep>> as core::future::future::Future>::poll
Unexecuted instantiation: <futures_util::future::select::Select<hyper_util::client::legacy::pool::Checkout<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::common::lazy::Lazy<<hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}, futures_util::future::either::Either<futures_util::future::try_future::AndThen<futures_util::future::try_future::MapErr<hyper_util::service::oneshot::Oneshot<reqwest::connect::Connector, http::uri::Uri>, <hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#0}>, futures_util::future::either::Either<core::pin::Pin<alloc::boxed::Box<<hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#1}::{closure#0}>>, futures_util::future::ready::Ready<core::result::Result<hyper_util::client::legacy::pool::Pooled<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::client::legacy::client::Error>>>, <hyper_util::client::legacy::client::Client<reqwest::connect::Connector, reqwest::async_impl::body::Body>>::connect_to::{closure#0}::{closure#1}>, futures_util::future::ready::Ready<core::result::Result<hyper_util::client::legacy::pool::Pooled<hyper_util::client::legacy::client::PoolClient<reqwest::async_impl::body::Body>, (http::uri::scheme::Scheme, http::uri::authority::Authority)>, hyper_util::client::legacy::client::Error>>>>> as core::future::future::Future>::poll
Unexecuted instantiation: <futures_util::future::select::Select<&mut futures_channel::oneshot::Receiver<core::convert::Infallible>, &mut core::pin::Pin<alloc::boxed::Box<dyn hyper::rt::timer::Sleep<Output = ()>>>> as core::future::future::Future>::poll
Unexecuted instantiation: <futures_util::future::select::Select<_, _> as core::future::future::Future>::poll
123
}
124
125
impl<A, B> FusedFuture for Select<A, B>
126
where
127
    A: Future + Unpin,
128
    B: Future + Unpin,
129
{
130
0
    fn is_terminated(&self) -> bool {
131
0
        self.inner.is_none()
132
0
    }
133
}