use core::pin::Pin;
use futures::future::{FusedFuture, Future};
use futures::stream::{FusedStream, StreamExt};
use futures::task::{Context, Poll};
pub trait SelectNextAnyExt {
fn select_next_any(&mut self) -> SelectNextAny<'_, Self>
where
Self: Unpin + FusedStream;
}
impl<T> SelectNextAnyExt for T
where
T: Unpin + FusedStream,
{
fn select_next_any(&mut self) -> SelectNextAny<'_, Self> {
SelectNextAny::new(self)
}
}
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct SelectNextAny<'a, St: ?Sized> {
stream: &'a mut St,
}
impl<'a, St: ?Sized> SelectNextAny<'a, St> {
fn new(stream: &'a mut St) -> Self {
SelectNextAny { stream }
}
}
impl<St: ?Sized + FusedStream + Unpin> FusedFuture for SelectNextAny<'_, St> {
fn is_terminated(&self) -> bool {
self.stream.is_terminated()
}
}
impl<St: ?Sized + FusedStream + Unpin> Future for SelectNextAny<'_, St> {
type Output = Option<St::Item>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
assert!(
!self.stream.is_terminated(),
"SelectNextAny polled after terminated"
);
self.stream.poll_next_unpin(cx)
}
}