use super::assert_future;
use crate::future::{Either, FutureExt};
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::task::{Context, Poll};
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
pub struct Select<A, B> {
inner: Option<(A, B)>,
}
impl<A: Unpin, B: Unpin> Unpin for Select<A, B> {}
pub fn select<A, B>(future1: A, future2: B) -> Select<A, B>
where
A: Future + Unpin,
B: Future + Unpin,
{
assert_future::<Either<(A::Output, B), (B::Output, A)>, _>(Select {
inner: Some((future1, future2)),
})
}
impl<A, B> Future for Select<A, B>
where
A: Future + Unpin,
B: Future + Unpin,
{
type Output = Either<(A::Output, B), (B::Output, A)>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[inline(always)]
fn unwrap_option<T>(value: Option<T>) -> T {
match value {
None => unreachable!(),
Some(value) => value,
}
}
let (a, b) = self.inner.as_mut().expect("cannot poll Select twice");
if let Poll::Ready(val) = a.poll_unpin(cx) {
return Poll::Ready(Either::Left((val, unwrap_option(self.inner.take()).1)));
}
if let Poll::Ready(val) = b.poll_unpin(cx) {
return Poll::Ready(Either::Right((val, unwrap_option(self.inner.take()).0)));
}
Poll::Pending
}
}
impl<A, B> FusedFuture for Select<A, B>
where
A: Future + Unpin,
B: Future + Unpin,
{
fn is_terminated(&self) -> bool {
self.inner.is_none()
}
}