repeat.rs - source
Description: Source of the Rust file `library/core/src/iter/sources/repeat.rs`.

#
core/iter/sources/
repeat.rs

    1use crate::iter::{FusedIterator, TrustedLen};
    2use crate::num::NonZero;
    3
    4/// Creates a new iterator that endlessly repeats a single element.
    5///
    6/// The `repeat()` function repeats a single value over and over again.
    7///
    8/// Infinite iterators like `repeat()` are often used with adapters like
    9/// [`Iterator::take()`], in order to make them finite.
    10///
    11/// If you know the number of repetitions in advance, consider using [`repeat_n()`]
    12/// instead, as it is more efficient and conveys the intent more clearly.
    13///
    14/// Use [`str::repeat()`] instead of this function if you just want to repeat
    15/// a char/string `n` times.
    16///
    17/// If the element type of the iterator you need does not implement `Clone`,
    18/// or if you do not want to keep the repeated element in memory, you can
    19/// instead use the [`repeat_with()`] function.
    20///
    21/// [`repeat_n()`]: crate::iter::repeat_n
    22/// [`repeat_with()`]: crate::iter::repeat_with
    23/// [`str::repeat()`]: ../../std/primitive.str.html#method.repeat
    24///
    25/// # Examples
    26///
    27/// Basic usage:
    28///
    29/// ```
    30/// use std::iter;
    31///
    32/// // the number four 4ever:
    33/// let mut fours = iter::repeat(4);
    34///
    35/// assert_eq!(Some(4), fours.next());
    36/// assert_eq!(Some(4), fours.next());
    37/// assert_eq!(Some(4), fours.next());
    38/// assert_eq!(Some(4), fours.next());
    39/// assert_eq!(Some(4), fours.next());
    40///
    41/// // yup, still four
    42/// assert_eq!(Some(4), fours.next());
    43/// ```
    44///
    45/// Going finite with [`Iterator::take()`]:
    46///
    47/// ```
    48/// use std::iter;
    49///
    50/// // that last example was too many fours. Let's only have four fours.
    51/// let mut four_fours = iter::repeat(4).take(4);
    52///
    53/// assert_eq!(Some(4), four_fours.next());
    54/// assert_eq!(Some(4), four_fours.next());
    55/// assert_eq!(Some(4), four_fours.next());
    56/// assert_eq!(Some(4), four_fours.next());
    57///
    58/// // ... and now we're done
    59/// assert_eq!(None, four_fours.next());
    60/// ```
    61#[inline]
    62#[stable(feature = "rust1", since = "1.0.0")]
    63#[rustc_diagnostic_item = "iter_repeat"]
    64pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
    65    Repeat { element: elt }
    66}
    67
    68/// An iterator that repeats an element endlessly.
    69///
    70/// This `struct` is created by the [`repeat()`] function. See its documentation for more.
    71#[derive(Clone, Debug)]
    72#[stable(feature = "rust1", since = "1.0.0")]
    73pub struct Repeat<A> {
    74    element: A,
    75}
    76
    77#[stable(feature = "rust1", since = "1.0.0")]
    78impl<A: Clone> Iterator for Repeat<A> {
    79    type Item = A;
    80
    81    #[inline]
    82    fn next(&mut self) -> Option<A> {
    83        Some(self.element.clone())
    84    }
    85
    86    #[inline]
    87    fn size_hint(&self) -> (usize, Option<usize>) {
    88        (usize::MAX, None)
    89    }
    90
    91    #[inline]
    92    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
    93        // Advancing an infinite iterator of a single element is a no-op.
    94        let _ = n;
    95        Ok(())
    96    }
    97
    98    #[inline]
    99    fn nth(&mut self, n: usize) -> Option<A> {
    100        let _ = n;
    101        Some(self.element.clone())
    102    }
    103
    104    #[track_caller]
    105    fn last(self) -> Option<A> {
    106        panic!("iterator is infinite");
    107    }
    108
    109    #[track_caller]
    110    fn count(self) -> usize {
    111        panic!("iterator is infinite");
    112    }
    113}
    114
    115#[stable(feature = "rust1", since = "1.0.0")]
    116impl<A: Clone> DoubleEndedIterator for Repeat<A> {
    117    #[inline]
    118    fn next_back(&mut self) -> Option<A> {
    119        Some(self.element.clone())
    120    }
    121
    122    #[inline]
    123    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
    124        // Advancing an infinite iterator of a single element is a no-op.
    125        let _ = n;
    126        Ok(())
    127    }
    128
    129    #[inline]
    130    fn nth_back(&mut self, n: usize) -> Option<A> {
    131        let _ = n;
    132        Some(self.element.clone())
    133    }
    134}
    135
    136#[stable(feature = "fused", since = "1.26.0")]
    137impl<A: Clone> FusedIterator for Repeat<A> {}
    138
    139#[unstable(feature = "trusted_len", issue = "37572")]
    140unsafe impl<A: Clone> TrustedLen for Repeat<A> {}