use std::marker::PhantomData;
use std::pin::Pin;
use crate::future::Future;
use crate::stream::Stream;
use crate::task::{Context, Poll};
#[derive(Debug)]
pub struct RepeatWith<F, Fut, A> {
f: F,
future: Option<Fut>,
__a: PhantomData<A>,
}
pub fn repeat_with<F, Fut, A>(repeater: F) -> RepeatWith<F, Fut, A>
where
F: FnMut() -> Fut,
Fut: Future<Output = A>,
{
RepeatWith {
f: repeater,
future: None,
__a: PhantomData,
}
}
impl<F, Fut, A> RepeatWith<F, Fut, A> {
pin_utils::unsafe_unpinned!(f: F);
pin_utils::unsafe_pinned!(future: Option<Fut>);
}
impl<F, Fut, A> Stream for RepeatWith<F, Fut, A>
where
F: FnMut() -> Fut,
Fut: Future<Output = A>,
{
type Item = A;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match &self.future {
Some(_) => {
let res =
futures_core::ready!(self.as_mut().future().as_pin_mut().unwrap().poll(cx));
self.as_mut().future().set(None);
return Poll::Ready(Some(res));
}
None => {
let fut = (self.as_mut().f())();
self.as_mut().future().set(Some(fut));
}
}
}
}
}