1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use pin_project_lite::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
pub fn biased_race<T, A, B>(future1: A, future2: B) -> BiasedRace<A, B>
where
A: Future<Output = T>,
B: Future<Output = T>,
{
BiasedRace { future1, future2 }
}
pin_project! {
#[derive(Debug)]
pub struct BiasedRace<A, B> {
#[pin]
future1: A,
#[pin]
future2: B,
}
}
impl<T, A, B> Future for BiasedRace<A, B>
where
A: Future<Output = T>,
B: Future<Output = T>,
{
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
if let Poll::Ready(t) = this.future1.poll(cx) {
return Poll::Ready(t);
}
if let Poll::Ready(t) = this.future2.poll(cx) {
return Poll::Ready(t);
}
Poll::Pending
}
}