use std::{pin::Pin, sync::Arc};
use crate::engineio::error::Result;
use std::sync::{Mutex, PoisonError};
use futures_util::{Stream, StreamExt};
pub(crate) type Generator<T> = Pin<Box<dyn Stream<Item = T> + 'static + Send>>;
#[derive(Clone)]
pub(crate) struct StreamGenerator<T> {
inner: Arc<Mutex<Generator<Result<T>>>>,
}
impl<T> Stream for StreamGenerator<T> {
type Item = Result<T>;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.inner
.lock()
.unwrap_or_else(PoisonError::into_inner)
.poll_next_unpin(cx)
}
}
impl<T> StreamGenerator<T> {
pub(crate) fn new(generator_stream: Generator<Result<T>>) -> Self {
StreamGenerator {
inner: Arc::new(Mutex::new(generator_stream)),
}
}
}
pub(crate) fn end_after_error<T, S>(stream: S) -> impl Stream<Item = Result<T>> + Send
where
S: Stream<Item = Result<T>> + Send + Unpin,
T: Send,
{
futures_util::stream::unfold((stream, false), |(mut stream, failed)| async move {
if failed {
return None;
}
let item = stream.next().await?;
let failed = item.is_err();
Some((item, (stream, failed)))
})
}