async_std/future/future/
race.rs1use std::future::Future;
2use std::pin::Pin;
3
4use crate::future::MaybeDone;
5use pin_project_lite::pin_project;
6
7use crate::task::{Context, Poll};
8
9pin_project! {
10 #[allow(missing_docs)]
11 #[allow(missing_debug_implementations)]
12 pub struct Race<L, R>
13 where
14 L: Future,
15 R: Future<Output = L::Output>
16 {
17 #[pin] left: MaybeDone<L>,
18 #[pin] right: MaybeDone<R>,
19 }
20}
21
22impl<L, R> Race<L, R>
23where
24 L: Future,
25 R: Future<Output = L::Output>,
26{
27 pub(crate) fn new(left: L, right: R) -> Self {
28 Self {
29 left: MaybeDone::new(left),
30 right: MaybeDone::new(right),
31 }
32 }
33}
34
35impl<L, R> Future for Race<L, R>
36where
37 L: Future,
38 R: Future<Output = L::Output>,
39{
40 type Output = L::Output;
41
42 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
43 let this = self.project();
44
45 let mut left = this.left;
46 if Future::poll(Pin::new(&mut left), cx).is_ready() {
47 return Poll::Ready(left.take().unwrap());
48 }
49
50 let mut right = this.right;
51 if Future::poll(Pin::new(&mut right), cx).is_ready() {
52 return Poll::Ready(right.take().unwrap());
53 }
54
55 Poll::Pending
56 }
57}