core/iter/sources/from_fn.rs
1use crate::fmt;
2
3/// Creates an iterator with the provided closure
4/// `F: FnMut() -> Option<T>` as its [`next`](Iterator::next) method.
5///
6/// The iterator will yield the `T`s returned from the closure.
7///
8/// This allows creating a custom iterator with any behavior
9/// without using the more verbose syntax of creating a dedicated type
10/// and implementing the [`Iterator`] trait for it.
11///
12/// Note that the `FromFn` iterator doesn’t make assumptions about the behavior of the closure,
13/// and therefore conservatively does not implement [`FusedIterator`],
14/// or override [`Iterator::size_hint()`] from its default `(0, None)`.
15///
16/// The closure can use captures and its environment to track state across iterations. Depending on
17/// how the iterator is used, this may require specifying the [`move`] keyword on the closure.
18///
19/// [`move`]: ../../std/keyword.move.html
20/// [`FusedIterator`]: crate::iter::FusedIterator
21///
22/// # Examples
23///
24/// Let’s re-implement the counter iterator from [module-level documentation]:
25///
26/// [module-level documentation]: crate::iter
27///
28/// ```
29/// let mut count = 0;
30/// let counter = std::iter::from_fn(move || {
31/// // Increment our count. This is why we started at zero.
32/// count += 1;
33///
34/// // Check to see if we've finished counting or not.
35/// if count < 6 {
36/// Some(count)
37/// } else {
38/// None
39/// }
40/// });
41/// assert_eq!(counter.collect::<Vec<_>>(), &[1, 2, 3, 4, 5]);
42/// ```
43#[ferrocene::prevalidated]
44#[inline]
45#[stable(feature = "iter_from_fn", since = "1.34.0")]
46#[rustc_diagnostic_item = "iter_from_fn"]
47pub fn from_fn<T, F>(f: F) -> FromFn<F>
48where
49 F: FnMut() -> Option<T>,
50{
51 FromFn(f)
52}
53
54/// An iterator where each iteration calls the provided closure `F: FnMut() -> Option<T>`.
55///
56/// This `struct` is created by the [`iter::from_fn()`] function.
57/// See its documentation for more.
58///
59/// [`iter::from_fn()`]: from_fn
60#[derive(Clone)]
61#[stable(feature = "iter_from_fn", since = "1.34.0")]
62#[ferrocene::prevalidated]
63pub struct FromFn<F>(F);
64
65#[stable(feature = "iter_from_fn", since = "1.34.0")]
66impl<T, F> Iterator for FromFn<F>
67where
68 F: FnMut() -> Option<T>,
69{
70 type Item = T;
71
72 #[inline]
73 #[ferrocene::prevalidated]
74 fn next(&mut self) -> Option<Self::Item> {
75 (self.0)()
76 }
77}
78
79#[stable(feature = "iter_from_fn", since = "1.34.0")]
80impl<F> fmt::Debug for FromFn<F> {
81 #[ferrocene::prevalidated]
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.debug_struct("FromFn").finish()
84 }
85}