non_empty_iter/
successors.rs

1//! Non-empty iterators that compute each successive item from the preceding one.
2
3use core::iter;
4
5use crate::non_empty::NonEmptyIterator;
6
7/// Creates [`Successors<T, S>`] non-empty iterator which, starting from the initial item,
8/// computes each successive item from the preceding one.
9pub const fn successors<T, S: FnMut(&T) -> Option<T>>(
10    initial: T,
11    successor: S,
12) -> Successors<T, S> {
13    Successors::new(initial, successor)
14}
15
16/// Represents non-empty iterators which, starting from the initial item,
17/// compute each successive item from preceding one.
18///
19/// This `struct` is created by the [`successors`] function. See its documentation for more.
20#[derive(Debug, Clone)]
21#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
22pub struct Successors<T, S: FnMut(&T) -> Option<T>> {
23    initial: T,
24    successor: S,
25}
26
27impl<T, S: FnMut(&T) -> Option<T>> Successors<T, S> {
28    /// Constructs [`Self`].
29    pub const fn new(initial: T, successor: S) -> Self {
30        Self { initial, successor }
31    }
32}
33
34impl<T, S: FnMut(&T) -> Option<T>> IntoIterator for Successors<T, S> {
35    type Item = T;
36
37    type IntoIter = iter::Successors<T, S>;
38
39    fn into_iter(self) -> Self::IntoIter {
40        iter::successors(Some(self.initial), self.successor)
41    }
42}
43
44unsafe impl<T, S: FnMut(&T) -> Option<T>> NonEmptyIterator for Successors<T, S> {}