Skip to main content

core/iter/sources/
successors.rs

1use crate::fmt;
2use crate::iter::FusedIterator;
3
4/// Creates an iterator which, starting from an initial item,
5/// computes each successive item from the preceding one.
6///
7/// This iterator stores an optional item (`Option<T>`) and a successor closure (`impl FnMut(&T) -> Option<T>`).
8/// Its `next` method returns the stored optional item and
9/// if it is `Some(val)` calls the stored closure on `&val` to compute and store its successor.
10/// The iterator will apply the closure successively to the stored option's value until the option is `None`.
11/// This also means that once the stored option is `None` it will remain `None`,
12/// as the closure will not be called again, so the created iterator is a [`FusedIterator`].
13/// The iterator's items will be the initial item and all of its successors as calculated by the successor closure.
14///
15/// ```
16/// use std::iter::successors;
17///
18/// let powers_of_10 = successors(Some(1_u16), |n| n.checked_mul(10));
19/// assert_eq!(powers_of_10.collect::<Vec<_>>(), &[1, 10, 100, 1_000, 10_000]);
20/// ```
21#[ferrocene::prevalidated]
22#[stable(feature = "iter_successors", since = "1.34.0")]
23#[rustc_diagnostic_item = "iter_successors"]
24pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F>
25where
26    F: FnMut(&T) -> Option<T>,
27{
28    // If this function returned `impl Iterator<Item=T>`
29    // it could be based on `from_fn` and not need a dedicated type.
30    // However having a named `Successors<T, F>` type allows it to be `Clone` when `T` and `F` are.
31    Successors { next: first, succ }
32}
33
34/// An iterator which, starting from an initial item,
35/// computes each successive item from the preceding one.
36///
37/// This `struct` is created by the [`iter::successors()`] function.
38/// See its documentation for more.
39///
40/// [`iter::successors()`]: successors
41#[derive(Clone)]
42#[stable(feature = "iter_successors", since = "1.34.0")]
43pub struct Successors<T, F> {
44    next: Option<T>,
45    succ: F,
46}
47
48#[ferrocene::prevalidated]
49#[stable(feature = "iter_successors", since = "1.34.0")]
50impl<T, F> Iterator for Successors<T, F>
51where
52    F: FnMut(&T) -> Option<T>,
53{
54    type Item = T;
55
56    #[inline]
57    fn next(&mut self) -> Option<Self::Item> {
58        let item = self.next.take()?;
59        self.next = (self.succ)(&item);
60        Some(item)
61    }
62
63    #[inline]
64    fn size_hint(&self) -> (usize, Option<usize>) {
65        if self.next.is_some() { (1, None) } else { (0, Some(0)) }
66    }
67}
68
69#[stable(feature = "iter_successors", since = "1.34.0")]
70impl<T, F> FusedIterator for Successors<T, F> where F: FnMut(&T) -> Option<T> {}
71
72#[stable(feature = "iter_successors", since = "1.34.0")]
73impl<T: fmt::Debug, F> fmt::Debug for Successors<T, F> {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("Successors").field("next", &self.next).finish()
76    }
77}