Skip to main content

conc_util/future/
select.rs

1use core::{
2    pin::Pin,
3    task::{Context, Poll},
4};
5
6use crate::Either;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct Select<A: Future, B: Future>(pub A, pub B);
10
11impl<A: Future, B: Future> Future for Select<A, B> {
12    type Output = Either<A::Output, B::Output>;
13
14    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
15        // SAFETY: doing projections, fields of pinned are pinned
16        let (a, b) = unsafe {
17            let ptr = self.get_unchecked_mut() as *mut Self;
18            (
19                Pin::new_unchecked(&mut (*ptr).0),
20                Pin::new_unchecked(&mut (*ptr).1),
21            )
22        };
23
24        if let Poll::Ready(a) = a.poll(cx) {
25            Poll::Ready(Either::A(a))
26        } else if let Poll::Ready(b) = b.poll(cx) {
27            Poll::Ready(Either::B(b))
28        } else {
29            Poll::Pending
30        }
31    }
32}