use crate::{fmt, iter::FusedIterator};
#[stable(feature = "iter_successors", since = "1.34.0")]
pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F>
where
F: FnMut(&T) -> Option<T>,
{
Successors { next: first, succ }
}
#[derive(Clone)]
#[stable(feature = "iter_successors", since = "1.34.0")]
pub struct Successors<T, F> {
next: Option<T>,
succ: F,
}
#[stable(feature = "iter_successors", since = "1.34.0")]
impl<T, F> Iterator for Successors<T, F>
where
F: FnMut(&T) -> Option<T>,
{
type Item = T;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let item = self.next.take()?;
self.next = (self.succ)(&item);
Some(item)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
if self.next.is_some() { (1, None) } else { (0, Some(0)) }
}
}
#[stable(feature = "iter_successors", since = "1.34.0")]
impl<T, F> FusedIterator for Successors<T, F> where F: FnMut(&T) -> Option<T> {}
#[stable(feature = "iter_successors", since = "1.34.0")]
impl<T: fmt::Debug, F> fmt::Debug for Successors<T, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Successors").field("next", &self.next).finish()
}
}