1 use crate::iter::{FusedIterator, TrustedLen};
3 /// Creates a new iterator that repeats elements of type `A` endlessly by
4 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
6 /// The `repeat_with()` function calls the repeater over and over again.
8 /// Infinite iterators like `repeat_with()` are often used with adapters like
9 /// [`Iterator::take()`], in order to make them finite.
11 /// If the element type of the iterator you need implements [`Clone`], and
12 /// it is OK to keep the source element in memory, you should instead use
13 /// the [`repeat()`] function.
15 /// An iterator produced by `repeat_with()` is not a [`DoubleEndedIterator`].
16 /// If you need `repeat_with()` to return a [`DoubleEndedIterator`],
17 /// please open a GitHub issue explaining your use case.
19 /// [`repeat()`]: crate::iter::repeat
20 /// [`DoubleEndedIterator`]: crate::iter::DoubleEndedIterator
29 /// // let's assume we have some value of a type that is not `Clone`
30 /// // or which we don't want to have in memory just yet because it is expensive:
31 /// #[derive(PartialEq, Debug)]
34 /// // a particular value forever:
35 /// let mut things = iter::repeat_with(|| Expensive);
37 /// assert_eq!(Some(Expensive), things.next());
38 /// assert_eq!(Some(Expensive), things.next());
39 /// assert_eq!(Some(Expensive), things.next());
40 /// assert_eq!(Some(Expensive), things.next());
41 /// assert_eq!(Some(Expensive), things.next());
44 /// Using mutation and going finite:
49 /// // From the zeroth to the third power of two:
51 /// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
54 /// assert_eq!(Some(1), pow2.next());
55 /// assert_eq!(Some(2), pow2.next());
56 /// assert_eq!(Some(4), pow2.next());
57 /// assert_eq!(Some(8), pow2.next());
59 /// // ... and now we're done
60 /// assert_eq!(None, pow2.next());
63 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
64 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
65 RepeatWith { repeater }
68 /// An iterator that repeats elements of type `A` endlessly by
69 /// applying the provided closure `F: FnMut() -> A`.
71 /// This `struct` is created by the [`repeat_with()`] function.
72 /// See its documentation for more.
73 #[derive(Copy, Clone, Debug)]
74 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
75 pub struct RepeatWith<F> {
79 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
80 impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
84 fn next(&mut self) -> Option<A> {
85 Some((self.repeater)())
89 fn size_hint(&self) -> (usize, Option<usize>) {
94 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
95 impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}
97 #[unstable(feature = "trusted_len", issue = "37572")]
98 unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}