use core::mem;
use core::pin::Pin;
use crate::stream::Stream;
use crate::task::{Context, Poll};
use pin_project_lite::pin_project;
#[cfg(feature = "unstable")]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
pub fn successors<F, T>(first: Option<T>, succ: F) -> Successors<F, T>
where
F: FnMut(&T) -> Option<T>,
{
Successors { succ, slot: first }
}
pin_project! {
#[cfg(feature = "unstable")]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
#[derive(Debug)]
pub struct Successors<F, T>
where
F: FnMut(&T) -> Option<T>
{
succ: F,
slot: Option<T>,
}
}
impl<F, T> Stream for Successors<F, T>
where
F: FnMut(&T) -> Option<T>,
{
type Item = T;
fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
if this.slot.is_none() {
return Poll::Ready(None);
}
let mut next = (this.succ)(&this.slot.as_ref().unwrap());
mem::swap(this.slot, &mut next);
Poll::Ready(next)
}
}