Skip to main content

externally_driven_async_rt/
select.rs

1use core::{
2    future::{Future, poll_fn},
3    pin::pin,
4    task::Poll,
5};
6
7/// An output of [`select2`](crate::select2).
8#[derive(Debug, PartialEq, Eq)]
9pub enum Either2<L, R> {
10    /// The left future has completed first.
11    Left(L),
12    /// The right future has completed first.
13    Right(R),
14}
15
16/// Polls two futures concurrently, resolves the one that completes first.
17///
18/// If both complete at the same time, the left one wins, the other one is dropped.
19///
20/// # Cancel safety
21///
22/// This function is cancel safe if both `left` and `right` are.
23pub async fn select2<L: Future, R: Future>(left: L, right: R) -> Either2<L::Output, R::Output> {
24    let mut left = pin!(left);
25    let mut right = pin!(right);
26    poll_fn(|cx| {
27        if let Poll::Ready(output) = left.as_mut().poll(cx) {
28            return Poll::Ready(Either2::Left(output));
29        }
30        if let Poll::Ready(output) = right.as_mut().poll(cx) {
31            return Poll::Ready(Either2::Right(output));
32        }
33        Poll::Pending
34    })
35    .await
36}
37
38/// An output of [`select3`](crate::select3).
39#[derive(Debug, PartialEq, Eq)]
40pub enum Either3<A, B, C> {
41    /// The first future has completed first.
42    First(A),
43    /// The second future has completed first.
44    Second(B),
45    /// The third future has completed first.
46    Third(C),
47}
48
49/// Polls three futures concurrently, resolves the one that completes first.
50///
51/// If several complete at the same time, the earliest one in the argument list wins,
52/// the others are dropped.
53///
54/// # Cancel safety
55///
56/// This function is cancel safe if `first`, `second` and `third` are.
57pub async fn select3<A: Future, B: Future, C: Future>(
58    first: A,
59    second: B,
60    third: C,
61) -> Either3<A::Output, B::Output, C::Output> {
62    let mut first = pin!(first);
63    let mut second = pin!(second);
64    let mut third = pin!(third);
65    poll_fn(|cx| {
66        if let Poll::Ready(output) = first.as_mut().poll(cx) {
67            return Poll::Ready(Either3::First(output));
68        }
69        if let Poll::Ready(output) = second.as_mut().poll(cx) {
70            return Poll::Ready(Either3::Second(output));
71        }
72        if let Poll::Ready(output) = third.as_mut().poll(cx) {
73            return Poll::Ready(Either3::Third(output));
74        }
75        Poll::Pending
76    })
77    .await
78}
79
80#[cfg(test)]
81mod tests {
82    use super::{Either2, Either3, select2, select3};
83    use core::{
84        future::{Future, pending, ready},
85        pin::pin,
86        task::{Context, Poll, Waker},
87    };
88
89    fn poll_once<F: Future>(future: F) -> Poll<F::Output> {
90        pin!(future).poll(&mut Context::from_waker(Waker::noop()))
91    }
92
93    #[test]
94    fn test_left() {
95        assert_eq!(
96            poll_once(select2(ready(1), pending::<()>())),
97            Poll::Ready(Either2::Left(1))
98        );
99    }
100
101    #[test]
102    fn test_right() {
103        assert_eq!(
104            poll_once(select2(pending::<()>(), ready(2))),
105            Poll::Ready(Either2::Right(2))
106        );
107    }
108
109    #[test]
110    fn test_left_wins_when_both_ready() {
111        assert_eq!(
112            poll_once(select2(ready(1), ready(2))),
113            Poll::Ready(Either2::Left(1))
114        );
115    }
116
117    #[test]
118    fn test_pending() {
119        assert_eq!(
120            poll_once(select2(pending::<()>(), pending::<()>())),
121            Poll::Pending
122        );
123    }
124
125    #[test]
126    fn test3_first() {
127        assert_eq!(
128            poll_once(select3(ready(1), pending::<()>(), pending::<()>())),
129            Poll::Ready(Either3::First(1))
130        );
131    }
132
133    #[test]
134    fn test3_second() {
135        assert_eq!(
136            poll_once(select3(pending::<()>(), ready(2), pending::<()>())),
137            Poll::Ready(Either3::Second(2))
138        );
139    }
140
141    #[test]
142    fn test3_third() {
143        assert_eq!(
144            poll_once(select3(pending::<()>(), pending::<()>(), ready(3))),
145            Poll::Ready(Either3::Third(3))
146        );
147    }
148
149    #[test]
150    fn test3_first_wins_when_all_ready() {
151        assert_eq!(
152            poll_once(select3(ready(1), ready(2), ready(3))),
153            Poll::Ready(Either3::First(1))
154        );
155    }
156
157    #[test]
158    fn test3_pending() {
159        assert_eq!(
160            poll_once(select3(pending::<()>(), pending::<()>(), pending::<()>())),
161            Poll::Pending
162        );
163    }
164}