use super::plumbing::*; use super::*; use std::num::NonZeroUsize; use std::{fmt, iter, mem}; /// Iterator adaptor for [the `repeat()` function]. /// /// [the `repeat()` function]: repeat() #[derive(Debug, Clone)] pub struct Repeat { element: T, } /// Creates a parallel iterator that endlessly repeats `element` (by /// cloning it). Note that this iterator has "infinite" length, so /// typically you would want to use `zip` or `take` or some other /// means to shorten it, or consider using /// [the `repeat_n()` function] instead. /// /// [the `repeat_n()` function]: repeat_n() /// /// # Examples /// /// ``` /// use rayon::prelude::*; /// use rayon::iter::repeat; /// let x: Vec<(i32, i32)> = repeat(22).zip(0..3).collect(); /// assert_eq!(x, vec![(22, 0), (22, 1), (22, 2)]); /// ``` pub fn repeat(element: T) -> Repeat { Repeat { element } } impl Repeat where T: Clone + Send, { /// Takes only `n` repeats of the element, similar to the general /// [`take()`]. /// /// The resulting `RepeatN` is an `IndexedParallelIterator`, allowing /// more functionality than `Repeat` alone. /// /// [`take()`]: IndexedParallelIterator::take() pub fn take(self, n: usize) -> RepeatN { repeat_n(self.element, n) } /// Iterates tuples, repeating the element with items from another /// iterator, similar to the general [`zip()`]. /// /// [`zip()`]: IndexedParallelIterator::zip() pub fn zip(self, zip_op: Z) -> Zip, Z::Iter> where Z: IntoParallelIterator, { let z = zip_op.into_par_iter(); let n = z.len(); self.take(n).zip(z) } } impl ParallelIterator for Repeat where T: Clone + Send, { type Item = T; fn drive_unindexed(self, consumer: C) -> C::Result where C: UnindexedConsumer, { let producer = RepeatProducer { element: self.element, }; bridge_unindexed(producer, consumer) } } /// Unindexed producer for `Repeat`. struct RepeatProducer { element: T, } impl UnindexedProducer for RepeatProducer { type Item = T; fn split(self) -> (Self, Option) { ( RepeatProducer { element: self.element.clone(), }, Some(RepeatProducer { element: self.element, }), ) } fn fold_with(self, folder: F) -> F where F: Folder, { folder.consume_iter(iter::repeat(self.element)) } } /// Iterator adaptor for [the `repeat_n()` function]. /// /// [the `repeat_n()` function]: repeat_n() #[derive(Clone)] pub struct RepeatN { inner: RepeatNProducer, } /// Creates a parallel iterator that produces `n` repeats of `element` /// (by cloning it). /// /// # Examples /// /// ``` /// use rayon::prelude::*; /// use rayon::iter::repeat_n; /// let x: Vec<(i32, i32)> = repeat_n(22, 3).zip(0..3).collect(); /// assert_eq!(x, vec![(22, 0), (22, 1), (22, 2)]); /// ``` pub fn repeat_n(element: T, n: usize) -> RepeatN { let inner = match NonZeroUsize::new(n) { Some(count) => RepeatNProducer::Repeats(element, count), None => RepeatNProducer::Empty, }; RepeatN { inner } } /// Creates a parallel iterator that produces `n` repeats of `element` /// (by cloning it). /// /// Deprecated in favor of [`repeat_n`] for consistency with the standard library. #[deprecated(note = "use `repeat_n`")] pub fn repeatn(element: T, n: usize) -> RepeatN { repeat_n(element, n) } impl fmt::Debug for RepeatN { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut dbg = f.debug_struct("RepeatN"); if let RepeatNProducer::Repeats(element, count) = &self.inner { dbg.field("count", &count.get()) .field("element", element) .finish() } else { dbg.field("count", &0usize).finish_non_exhaustive() } } } impl ParallelIterator for RepeatN where T: Clone + Send, { type Item = T; fn drive_unindexed(self, consumer: C) -> C::Result where C: UnindexedConsumer, { bridge(self, consumer) } fn opt_len(&self) -> Option { Some(self.inner.len()) } } impl IndexedParallelIterator for RepeatN where T: Clone + Send, { fn drive(self, consumer: C) -> C::Result where C: Consumer, { bridge(self, consumer) } fn with_producer(self, callback: CB) -> CB::Output where CB: ProducerCallback, { callback.callback(self.inner) } fn len(&self) -> usize { self.inner.len() } } /// Producer for `RepeatN`. #[derive(Clone)] enum RepeatNProducer { Repeats(T, NonZeroUsize), Empty, } impl Producer for RepeatNProducer { type Item = T; type IntoIter = Self; fn into_iter(self) -> Self::IntoIter { // We could potentially use `std::iter::RepeatN` with MSRV 1.82, but we have no way to // create an empty instance without a value in hand, like `repeat_n(value, 0)`. self } fn split_at(self, index: usize) -> (Self, Self) { if let Self::Repeats(element, count) = self { assert!(index <= count.get()); match ( NonZeroUsize::new(index), NonZeroUsize::new(count.get() - index), ) { (Some(left), Some(right)) => ( Self::Repeats(element.clone(), left), Self::Repeats(element, right), ), (Some(left), None) => (Self::Repeats(element, left), Self::Empty), (None, Some(right)) => (Self::Empty, Self::Repeats(element, right)), (None, None) => unreachable!(), } } else { assert!(index == 0); (Self::Empty, Self::Empty) } } } impl Iterator for RepeatNProducer { type Item = T; #[inline] fn next(&mut self) -> Option { if let Self::Repeats(element, count) = self { if let Some(rem) = NonZeroUsize::new(count.get() - 1) { *count = rem; Some(element.clone()) } else { match mem::replace(self, Self::Empty) { Self::Repeats(element, _) => Some(element), Self::Empty => unreachable!(), } } } else { None } } #[inline] fn nth(&mut self, n: usize) -> Option { if let Self::Repeats(_, count) = self { if let Some(rem) = NonZeroUsize::new(count.get().saturating_sub(n)) { *count = rem; return self.next(); } *self = Self::Empty; } None } #[inline] fn size_hint(&self) -> (usize, Option) { let len = self.len(); (len, Some(len)) } } impl DoubleEndedIterator for RepeatNProducer { #[inline] fn next_back(&mut self) -> Option { self.next() } #[inline] fn nth_back(&mut self, n: usize) -> Option { self.nth(n) } } impl ExactSizeIterator for RepeatNProducer { #[inline] fn len(&self) -> usize { match self { Self::Repeats(_, count) => count.get(), Self::Empty => 0, } } }