1 use crate::iter::{FusedIterator, TrustedLen};
3 /// Creates a new iterator that endlessly repeats a single element.
5 /// The `repeat()` function repeats a single value over and over again.
7 /// Infinite iterators like `repeat()` are often used with adapters like
8 /// [`Iterator::take()`], in order to make them finite.
10 /// If the element type of the iterator you need does not implement `Clone`,
11 /// or if you do not want to keep the repeated element in memory, you can
12 /// instead use the [`repeat_with()`] function.
14 /// [`repeat_with()`]: crate::iter::repeat_with
23 /// // the number four 4ever:
24 /// let mut fours = iter::repeat(4);
26 /// assert_eq!(Some(4), fours.next());
27 /// assert_eq!(Some(4), fours.next());
28 /// assert_eq!(Some(4), fours.next());
29 /// assert_eq!(Some(4), fours.next());
30 /// assert_eq!(Some(4), fours.next());
32 /// // yup, still four
33 /// assert_eq!(Some(4), fours.next());
36 /// Going finite with [`Iterator::take()`]:
41 /// // that last example was too many fours. Let's only have four fours.
42 /// let mut four_fours = iter::repeat(4).take(4);
44 /// assert_eq!(Some(4), four_fours.next());
45 /// assert_eq!(Some(4), four_fours.next());
46 /// assert_eq!(Some(4), four_fours.next());
47 /// assert_eq!(Some(4), four_fours.next());
49 /// // ... and now we're done
50 /// assert_eq!(None, four_fours.next());
53 #[stable(feature = "rust1", since = "1.0.0")]
54 #[cfg_attr(not(test), rustc_diagnostic_item = "iter_repeat")]
55 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
56 Repeat { element: elt }
59 /// An iterator that repeats an element endlessly.
61 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
62 #[derive(Clone, Debug)]
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub struct Repeat<A> {
68 #[stable(feature = "rust1", since = "1.0.0")]
69 impl<A: Clone> Iterator for Repeat<A> {
73 fn next(&mut self) -> Option<A> {
74 Some(self.element.clone())
78 fn size_hint(&self) -> (usize, Option<usize>) {
83 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
84 // Advancing an infinite iterator of a single element is a no-op.
90 fn nth(&mut self, n: usize) -> Option<A> {
92 Some(self.element.clone())
95 fn last(self) -> Option<A> {
99 fn count(self) -> usize {
104 #[stable(feature = "rust1", since = "1.0.0")]
105 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
107 fn next_back(&mut self) -> Option<A> {
108 Some(self.element.clone())
112 fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
113 // Advancing an infinite iterator of a single element is a no-op.
119 fn nth_back(&mut self, n: usize) -> Option<A> {
121 Some(self.element.clone())
125 #[stable(feature = "fused", since = "1.26.0")]
126 impl<A: Clone> FusedIterator for Repeat<A> {}
128 #[unstable(feature = "trusted_len", issue = "37572")]
129 unsafe impl<A: Clone> TrustedLen for Repeat<A> {}