5 use super::{FusedIterator, TrustedLen};
7 /// An iterator that repeats an element endlessly.
9 /// This `struct` is created by the [`repeat`] function. See its documentation for more.
11 /// [`repeat`]: fn.repeat.html
12 #[derive(Clone, Debug)]
13 #[stable(feature = "rust1", since = "1.0.0")]
14 pub struct Repeat<A> {
18 #[stable(feature = "rust1", since = "1.0.0")]
19 impl<A: Clone> Iterator for Repeat<A> {
23 fn next(&mut self) -> Option<A> {
24 Some(self.element.clone())
27 fn size_hint(&self) -> (usize, Option<usize>) {
32 #[stable(feature = "rust1", since = "1.0.0")]
33 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
35 fn next_back(&mut self) -> Option<A> {
36 Some(self.element.clone())
40 #[stable(feature = "fused", since = "1.26.0")]
41 impl<A: Clone> FusedIterator for Repeat<A> {}
43 #[unstable(feature = "trusted_len", issue = "37572")]
44 unsafe impl<A: Clone> TrustedLen for Repeat<A> {}
46 /// Creates a new iterator that endlessly repeats a single element.
48 /// The `repeat()` function repeats a single value over and over again.
50 /// Infinite iterators like `repeat()` are often used with adapters like
51 /// [`take`], in order to make them finite.
53 /// [`take`]: trait.Iterator.html#method.take
55 /// If the element type of the iterator you need does not implement `Clone`,
56 /// or if you do not want to keep the repeated element in memory, you can
57 /// instead use the [`repeat_with`] function.
59 /// [`repeat_with`]: fn.repeat_with.html
68 /// // the number four 4ever:
69 /// let mut fours = iter::repeat(4);
71 /// assert_eq!(Some(4), fours.next());
72 /// assert_eq!(Some(4), fours.next());
73 /// assert_eq!(Some(4), fours.next());
74 /// assert_eq!(Some(4), fours.next());
75 /// assert_eq!(Some(4), fours.next());
77 /// // yup, still four
78 /// assert_eq!(Some(4), fours.next());
81 /// Going finite with [`take`]:
86 /// // that last example was too many fours. Let's only have four fours.
87 /// let mut four_fours = iter::repeat(4).take(4);
89 /// assert_eq!(Some(4), four_fours.next());
90 /// assert_eq!(Some(4), four_fours.next());
91 /// assert_eq!(Some(4), four_fours.next());
92 /// assert_eq!(Some(4), four_fours.next());
94 /// // ... and now we're done
95 /// assert_eq!(None, four_fours.next());
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
100 Repeat { element: elt }
103 /// An iterator that repeats elements of type `A` endlessly by
104 /// applying the provided closure `F: FnMut() -> A`.
106 /// This `struct` is created by the [`repeat_with`] function.
107 /// See its documentation for more.
109 /// [`repeat_with`]: fn.repeat_with.html
110 #[derive(Copy, Clone, Debug)]
111 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
112 pub struct RepeatWith<F> {
116 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
117 impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
121 fn next(&mut self) -> Option<A> {
122 Some((self.repeater)())
126 fn size_hint(&self) -> (usize, Option<usize>) {
131 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
132 impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}
134 #[unstable(feature = "trusted_len", issue = "37572")]
135 unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}
137 /// Creates a new iterator that repeats elements of type `A` endlessly by
138 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
140 /// The `repeat_with()` function calls the repeater over and over again.
142 /// Infinite iterators like `repeat_with()` are often used with adapters like
143 /// [`take`], in order to make them finite.
145 /// [`take`]: trait.Iterator.html#method.take
147 /// If the element type of the iterator you need implements `Clone`, and
148 /// it is OK to keep the source element in memory, you should instead use
149 /// the [`repeat`] function.
151 /// [`repeat`]: fn.repeat.html
153 /// An iterator produced by `repeat_with()` is not a `DoubleEndedIterator`.
154 /// If you need `repeat_with()` to return a `DoubleEndedIterator`,
155 /// please open a GitHub issue explaining your use case.
164 /// // let's assume we have some value of a type that is not `Clone`
165 /// // or which don't want to have in memory just yet because it is expensive:
166 /// #[derive(PartialEq, Debug)]
167 /// struct Expensive;
169 /// // a particular value forever:
170 /// let mut things = iter::repeat_with(|| Expensive);
172 /// assert_eq!(Some(Expensive), things.next());
173 /// assert_eq!(Some(Expensive), things.next());
174 /// assert_eq!(Some(Expensive), things.next());
175 /// assert_eq!(Some(Expensive), things.next());
176 /// assert_eq!(Some(Expensive), things.next());
179 /// Using mutation and going finite:
184 /// // From the zeroth to the third power of two:
185 /// let mut curr = 1;
186 /// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
189 /// assert_eq!(Some(1), pow2.next());
190 /// assert_eq!(Some(2), pow2.next());
191 /// assert_eq!(Some(4), pow2.next());
192 /// assert_eq!(Some(8), pow2.next());
194 /// // ... and now we're done
195 /// assert_eq!(None, pow2.next());
198 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
199 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
200 RepeatWith { repeater }
203 /// An iterator that yields nothing.
205 /// This `struct` is created by the [`empty`] function. See its documentation for more.
207 /// [`empty`]: fn.empty.html
208 #[stable(feature = "iter_empty", since = "1.2.0")]
209 pub struct Empty<T>(marker::PhantomData<T>);
211 #[stable(feature = "core_impl_debug", since = "1.9.0")]
212 impl<T> fmt::Debug for Empty<T> {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 #[stable(feature = "iter_empty", since = "1.2.0")]
219 impl<T> Iterator for Empty<T> {
222 fn next(&mut self) -> Option<T> {
226 fn size_hint(&self) -> (usize, Option<usize>) {
231 #[stable(feature = "iter_empty", since = "1.2.0")]
232 impl<T> DoubleEndedIterator for Empty<T> {
233 fn next_back(&mut self) -> Option<T> {
238 #[stable(feature = "iter_empty", since = "1.2.0")]
239 impl<T> ExactSizeIterator for Empty<T> {
240 fn len(&self) -> usize {
245 #[unstable(feature = "trusted_len", issue = "37572")]
246 unsafe impl<T> TrustedLen for Empty<T> {}
248 #[stable(feature = "fused", since = "1.26.0")]
249 impl<T> FusedIterator for Empty<T> {}
251 // not #[derive] because that adds a Clone bound on T,
252 // which isn't necessary.
253 #[stable(feature = "iter_empty", since = "1.2.0")]
254 impl<T> Clone for Empty<T> {
255 fn clone(&self) -> Empty<T> {
256 Empty(marker::PhantomData)
260 // not #[derive] because that adds a Default bound on T,
261 // which isn't necessary.
262 #[stable(feature = "iter_empty", since = "1.2.0")]
263 impl<T> Default for Empty<T> {
264 fn default() -> Empty<T> {
265 Empty(marker::PhantomData)
269 /// Creates an iterator that yields nothing.
278 /// // this could have been an iterator over i32, but alas, it's just not.
279 /// let mut nope = iter::empty::<i32>();
281 /// assert_eq!(None, nope.next());
283 #[stable(feature = "iter_empty", since = "1.2.0")]
284 #[rustc_const_stable(feature = "const_iter_empty", since = "1.32.0")]
285 pub const fn empty<T>() -> Empty<T> {
286 Empty(marker::PhantomData)
289 /// An iterator that yields an element exactly once.
291 /// This `struct` is created by the [`once`] function. See its documentation for more.
293 /// [`once`]: fn.once.html
294 #[derive(Clone, Debug)]
295 #[stable(feature = "iter_once", since = "1.2.0")]
297 inner: crate::option::IntoIter<T>,
300 #[stable(feature = "iter_once", since = "1.2.0")]
301 impl<T> Iterator for Once<T> {
304 fn next(&mut self) -> Option<T> {
308 fn size_hint(&self) -> (usize, Option<usize>) {
309 self.inner.size_hint()
313 #[stable(feature = "iter_once", since = "1.2.0")]
314 impl<T> DoubleEndedIterator for Once<T> {
315 fn next_back(&mut self) -> Option<T> {
316 self.inner.next_back()
320 #[stable(feature = "iter_once", since = "1.2.0")]
321 impl<T> ExactSizeIterator for Once<T> {
322 fn len(&self) -> usize {
327 #[unstable(feature = "trusted_len", issue = "37572")]
328 unsafe impl<T> TrustedLen for Once<T> {}
330 #[stable(feature = "fused", since = "1.26.0")]
331 impl<T> FusedIterator for Once<T> {}
333 /// Creates an iterator that yields an element exactly once.
335 /// This is commonly used to adapt a single value into a [`chain`] of other
336 /// kinds of iteration. Maybe you have an iterator that covers almost
337 /// everything, but you need an extra special case. Maybe you have a function
338 /// which works on iterators, but you only need to process one value.
340 /// [`chain`]: trait.Iterator.html#method.chain
349 /// // one is the loneliest number
350 /// let mut one = iter::once(1);
352 /// assert_eq!(Some(1), one.next());
354 /// // just one, that's all we get
355 /// assert_eq!(None, one.next());
358 /// Chaining together with another iterator. Let's say that we want to iterate
359 /// over each file of the `.foo` directory, but also a configuration file,
365 /// use std::path::PathBuf;
367 /// let dirs = fs::read_dir(".foo").unwrap();
369 /// // we need to convert from an iterator of DirEntry-s to an iterator of
370 /// // PathBufs, so we use map
371 /// let dirs = dirs.map(|file| file.unwrap().path());
373 /// // now, our iterator just for our config file
374 /// let config = iter::once(PathBuf::from(".foorc"));
376 /// // chain the two iterators together into one big iterator
377 /// let files = dirs.chain(config);
379 /// // this will give us all of the files in .foo as well as .foorc
381 /// println!("{:?}", f);
384 #[stable(feature = "iter_once", since = "1.2.0")]
385 pub fn once<T>(value: T) -> Once<T> {
386 Once { inner: Some(value).into_iter() }
389 /// An iterator that yields a single element of type `A` by
390 /// applying the provided closure `F: FnOnce() -> A`.
392 /// This `struct` is created by the [`once_with`] function.
393 /// See its documentation for more.
395 /// [`once_with`]: fn.once_with.html
396 #[derive(Copy, Clone, Debug)]
397 #[unstable(feature = "iter_once_with", issue = "57581")]
398 pub struct OnceWith<F> {
402 #[unstable(feature = "iter_once_with", issue = "57581")]
403 impl<A, F: FnOnce() -> A> Iterator for OnceWith<F> {
407 fn next(&mut self) -> Option<A> {
408 let f = self.gen.take()?;
413 fn size_hint(&self) -> (usize, Option<usize>) {
414 self.gen.iter().size_hint()
418 #[unstable(feature = "iter_once_with", issue = "57581")]
419 impl<A, F: FnOnce() -> A> DoubleEndedIterator for OnceWith<F> {
420 fn next_back(&mut self) -> Option<A> {
425 #[unstable(feature = "iter_once_with", issue = "57581")]
426 impl<A, F: FnOnce() -> A> ExactSizeIterator for OnceWith<F> {
427 fn len(&self) -> usize {
428 self.gen.iter().len()
432 #[unstable(feature = "iter_once_with", issue = "57581")]
433 impl<A, F: FnOnce() -> A> FusedIterator for OnceWith<F> {}
435 #[unstable(feature = "iter_once_with", issue = "57581")]
436 unsafe impl<A, F: FnOnce() -> A> TrustedLen for OnceWith<F> {}
438 /// Creates an iterator that lazily generates a value exactly once by invoking
439 /// the provided closure.
441 /// This is commonly used to adapt a single value generator into a [`chain`] of
442 /// other kinds of iteration. Maybe you have an iterator that covers almost
443 /// everything, but you need an extra special case. Maybe you have a function
444 /// which works on iterators, but you only need to process one value.
446 /// Unlike [`once`], this function will lazily generate the value on request.
448 /// [`once`]: fn.once.html
449 /// [`chain`]: trait.Iterator.html#method.chain
456 /// #![feature(iter_once_with)]
460 /// // one is the loneliest number
461 /// let mut one = iter::once_with(|| 1);
463 /// assert_eq!(Some(1), one.next());
465 /// // just one, that's all we get
466 /// assert_eq!(None, one.next());
469 /// Chaining together with another iterator. Let's say that we want to iterate
470 /// over each file of the `.foo` directory, but also a configuration file,
474 /// #![feature(iter_once_with)]
478 /// use std::path::PathBuf;
480 /// let dirs = fs::read_dir(".foo").unwrap();
482 /// // we need to convert from an iterator of DirEntry-s to an iterator of
483 /// // PathBufs, so we use map
484 /// let dirs = dirs.map(|file| file.unwrap().path());
486 /// // now, our iterator just for our config file
487 /// let config = iter::once_with(|| PathBuf::from(".foorc"));
489 /// // chain the two iterators together into one big iterator
490 /// let files = dirs.chain(config);
492 /// // this will give us all of the files in .foo as well as .foorc
494 /// println!("{:?}", f);
498 #[unstable(feature = "iter_once_with", issue = "57581")]
499 pub fn once_with<A, F: FnOnce() -> A>(gen: F) -> OnceWith<F> {
500 OnceWith { gen: Some(gen) }
503 /// Creates a new iterator where each iteration calls the provided closure
504 /// `F: FnMut() -> Option<T>`.
506 /// This allows creating a custom iterator with any behavior
507 /// without using the more verbose syntax of creating a dedicated type
508 /// and implementing the `Iterator` trait for it.
510 /// Note that the `FromFn` iterator doesn’t make assumptions about the behavior of the closure,
511 /// and therefore conservatively does not implement [`FusedIterator`],
512 /// or override [`Iterator::size_hint`] from its default `(0, None)`.
514 /// [`FusedIterator`]: trait.FusedIterator.html
515 /// [`Iterator::size_hint`]: trait.Iterator.html#method.size_hint
517 /// The closure can use captures and its environment to track state across iterations. Depending on
518 /// how the iterator is used, this may require specifying the `move` keyword on the closure.
522 /// Let’s re-implement the counter iterator from [module-level documentation]:
524 /// [module-level documentation]: index.html
527 /// let mut count = 0;
528 /// let counter = std::iter::from_fn(move || {
529 /// // Increment our count. This is why we started at zero.
532 /// // Check to see if we've finished counting or not.
539 /// assert_eq!(counter.collect::<Vec<_>>(), &[1, 2, 3, 4, 5]);
542 #[stable(feature = "iter_from_fn", since = "1.34.0")]
543 pub fn from_fn<T, F>(f: F) -> FromFn<F>
545 F: FnMut() -> Option<T>,
550 /// An iterator where each iteration calls the provided closure `F: FnMut() -> Option<T>`.
552 /// This `struct` is created by the [`iter::from_fn`] function.
553 /// See its documentation for more.
555 /// [`iter::from_fn`]: fn.from_fn.html
557 #[stable(feature = "iter_from_fn", since = "1.34.0")]
558 pub struct FromFn<F>(F);
560 #[stable(feature = "iter_from_fn", since = "1.34.0")]
561 impl<T, F> Iterator for FromFn<F>
563 F: FnMut() -> Option<T>,
568 fn next(&mut self) -> Option<Self::Item> {
573 #[stable(feature = "iter_from_fn", since = "1.34.0")]
574 impl<F> fmt::Debug for FromFn<F> {
575 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
576 f.debug_struct("FromFn").finish()
580 /// Creates a new iterator where each successive item is computed based on the preceding one.
582 /// The iterator starts with the given first item (if any)
583 /// and calls the given `FnMut(&T) -> Option<T>` closure to compute each item’s successor.
586 /// use std::iter::successors;
588 /// let powers_of_10 = successors(Some(1_u16), |n| n.checked_mul(10));
589 /// assert_eq!(powers_of_10.collect::<Vec<_>>(), &[1, 10, 100, 1_000, 10_000]);
591 #[stable(feature = "iter_successors", since = "1.34.0")]
592 pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F>
594 F: FnMut(&T) -> Option<T>,
596 // If this function returned `impl Iterator<Item=T>`
597 // it could be based on `unfold` and not need a dedicated type.
598 // However having a named `Successors<T, F>` type allows it to be `Clone` when `T` and `F` are.
599 Successors { next: first, succ }
602 /// An new iterator where each successive item is computed based on the preceding one.
604 /// This `struct` is created by the [`successors`] function.
605 /// See its documentation for more.
607 /// [`successors`]: fn.successors.html
609 #[stable(feature = "iter_successors", since = "1.34.0")]
610 pub struct Successors<T, F> {
615 #[stable(feature = "iter_successors", since = "1.34.0")]
616 impl<T, F> Iterator for Successors<T, F>
618 F: FnMut(&T) -> Option<T>,
623 fn next(&mut self) -> Option<Self::Item> {
624 let item = self.next.take()?;
625 self.next = (self.succ)(&item);
630 fn size_hint(&self) -> (usize, Option<usize>) {
631 if self.next.is_some() { (1, None) } else { (0, Some(0)) }
635 #[stable(feature = "iter_successors", since = "1.34.0")]
636 impl<T, F> FusedIterator for Successors<T, F> where F: FnMut(&T) -> Option<T> {}
638 #[stable(feature = "iter_successors", since = "1.34.0")]
639 impl<T: fmt::Debug, F> fmt::Debug for Successors<T, F> {
640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641 f.debug_struct("Successors").field("next", &self.next).finish()