1//! Parallel iterator types for [inclusive ranges][std::range],
2//! the type for values created by `a..=b` expressions
3//!
4//! You will rarely need to interact with this module directly unless you have
5//! need to name one of the iterator types.
6//!
7//! ```
8//! use rayon::prelude::*;
9//!
10//! let r = (0..=100u64).into_par_iter()
11//! .sum();
12//!
13//! // compare result with sequential calculation
14//! assert_eq!((0..=100).sum::<u64>(), r);
15//! ```
16//!
17//! [std::range]: https://doc.rust-lang.org/core/ops/struct.RangeInclusive.html
1819use crate::iter::plumbing::*;
20use crate::iter::*;
21use std::ops::RangeInclusive;
2223/// Parallel iterator over an inclusive range, implemented for all integer types and `char`.
24///
25/// **Note:** The `zip` operation requires `IndexedParallelIterator`
26/// which is only implemented for `u8`, `i8`, `u16`, `i16`, and `char`.
27///
28/// ```
29/// use rayon::prelude::*;
30///
31/// let p = (0..=25u16).into_par_iter()
32/// .zip(0..=25u16)
33/// .filter(|&(x, y)| x % 5 == 0 || y % 5 == 0)
34/// .map(|(x, y)| x * y)
35/// .sum::<u16>();
36///
37/// let s = (0..=25u16).zip(0..=25u16)
38/// .filter(|&(x, y)| x % 5 == 0 || y % 5 == 0)
39/// .map(|(x, y)| x * y)
40/// .sum();
41///
42/// assert_eq!(p, s);
43/// ```
44#[derive(Debug, Clone)]
45pub struct Iter<T> {
46 range: RangeInclusive<T>,
47}
4849impl<T> Iter<T>
50where
51RangeInclusive<T>: Eq,
52 T: Ord + Copy,
53{
54/// Returns `Some((start, end))` for `start..=end`, or `None` if it is exhausted.
55 ///
56 /// Note that `RangeInclusive` does not specify the bounds of an exhausted iterator,
57 /// so this is a way for us to figure out what we've got. Thankfully, all of the
58 /// integer types we care about can be trivially cloned.
59fn bounds(&self) -> Option<(T, T)> {
60let start = *self.range.start();
61let end = *self.range.end();
62if start <= end && self.range == (start..=end) {
63// If the range is still nonempty, this is obviously true
64 // If the range is exhausted, either start > end or
65 // the range does not equal start..=end.
66Some((start, end))
67 } else {
68None
69}
70 }
71}
7273/// Implemented for ranges of all primitive integer types and `char`.
74impl<T> IntoParallelIterator for RangeInclusive<T>
75where
76Iter<T>: ParallelIterator,
77{
78type Item = <Iter<T> as ParallelIterator>::Item;
79type Iter = Iter<T>;
8081fn into_par_iter(self) -> Self::Iter {
82 Iter { range: self }
83 }
84}
8586/// These traits help drive integer type inference. Without them, an unknown `{integer}` type only
87/// has constraints on `Iter<{integer}>`, which will probably give up and use `i32`. By adding
88/// these traits on the item type, the compiler can see a more direct constraint to infer like
89/// `{integer}: RangeInteger`, which works better. See `test_issue_833` for an example.
90///
91/// They have to be `pub` since they're seen in the public `impl ParallelIterator` constraints, but
92/// we put them in a private modules so they're not actually reachable in our public API.
93mod private {
94use super::*;
9596/// Implementation details of `ParallelIterator for Iter<Self>`
97pub trait RangeInteger: Sized + Send {
98private_decl! {}
99100fn drive_unindexed<C>(iter: Iter<Self>, consumer: C) -> C::Result
101where
102C: UnindexedConsumer<Self>;
103104fn opt_len(iter: &Iter<Self>) -> Option<usize>;
105 }
106107/// Implementation details of `IndexedParallelIterator for Iter<Self>`
108pub trait IndexedRangeInteger: RangeInteger {
109private_decl! {}
110111fn drive<C>(iter: Iter<Self>, consumer: C) -> C::Result
112where
113C: Consumer<Self>;
114115fn len(iter: &Iter<Self>) -> usize;
116117fn with_producer<CB>(iter: Iter<Self>, callback: CB) -> CB::Output
118where
119CB: ProducerCallback<Self>;
120 }
121}
122use private::{IndexedRangeInteger, RangeInteger};
123124impl<T: RangeInteger> ParallelIterator for Iter<T> {
125type Item = T;
126127fn drive_unindexed<C>(self, consumer: C) -> C::Result
128where
129C: UnindexedConsumer<T>,
130 {
131 T::drive_unindexed(self, consumer)
132 }
133134#[inline]
135fn opt_len(&self) -> Option<usize> {
136 T::opt_len(self)
137 }
138}
139140impl<T: IndexedRangeInteger> IndexedParallelIterator for Iter<T> {
141fn drive<C>(self, consumer: C) -> C::Result
142where
143C: Consumer<T>,
144 {
145 T::drive(self, consumer)
146 }
147148#[inline]
149fn len(&self) -> usize {
150 T::len(self)
151 }
152153fn with_producer<CB>(self, callback: CB) -> CB::Output
154where
155CB: ProducerCallback<T>,
156 {
157 T::with_producer(self, callback)
158 }
159}
160161macro_rules! convert {
162 ( $iter:ident . $method:ident ( $( $arg:expr ),* ) ) => {
163if let Some((start, end)) = $iter.bounds() {
164if let Some(end) = end.checked_add(1) {
165 (start..end).into_par_iter().$method($( $arg ),*)
166 } else {
167 (start..end).into_par_iter().chain(once(end)).$method($( $arg ),*)
168 }
169 } else {
170 empty::<Self>().$method($( $arg ),*)
171 }
172 };
173}
174175macro_rules! parallel_range_impl {
176 ( $t:ty ) => {
177impl RangeInteger for $t {
178private_impl! {}
179180fn drive_unindexed<C>(iter: Iter<$t>, consumer: C) -> C::Result
181where
182C: UnindexedConsumer<$t>,
183 {
184convert!(iter.drive_unindexed(consumer))
185 }
186187fn opt_len(iter: &Iter<$t>) -> Option<usize> {
188convert!(iter.opt_len())
189 }
190 }
191 };
192}
193194macro_rules! indexed_range_impl {
195 ( $t:ty ) => {
196parallel_range_impl! { $t }
197198impl IndexedRangeInteger for $t {
199private_impl! {}
200201fn drive<C>(iter: Iter<$t>, consumer: C) -> C::Result
202where
203C: Consumer<$t>,
204 {
205convert!(iter.drive(consumer))
206 }
207208fn len(iter: &Iter<$t>) -> usize {
209 iter.range.len()
210 }
211212fn with_producer<CB>(iter: Iter<$t>, callback: CB) -> CB::Output
213where
214CB: ProducerCallback<$t>,
215 {
216convert!(iter.with_producer(callback))
217 }
218 }
219 };
220}
221222// all RangeInclusive<T> with ExactSizeIterator
223indexed_range_impl! {u8}
224indexed_range_impl! {u16}
225indexed_range_impl! {i8}
226indexed_range_impl! {i16}
227228// other RangeInclusive<T> with just Iterator
229parallel_range_impl! {usize}
230parallel_range_impl! {isize}
231parallel_range_impl! {u32}
232parallel_range_impl! {i32}
233parallel_range_impl! {u64}
234parallel_range_impl! {i64}
235parallel_range_impl! {u128}
236parallel_range_impl! {i128}
237238// char is special
239macro_rules! convert_char {
240 ( $self:ident . $method:ident ( $( $arg:expr ),* ) ) => {
241if let Some((start, end)) = $self.bounds() {
242let start = start as u32;
243let end = end as u32;
244if start < 0xD800 && 0xE000 <= end {
245// chain the before and after surrogate range fragments
246(start..0xD800)
247 .into_par_iter()
248 .chain(0xE000..end + 1) // cannot use RangeInclusive, so add one to end
249.map(|codepoint| unsafe { char::from_u32_unchecked(codepoint) })
250 .$method($( $arg ),*)
251 } else {
252// no surrogate range to worry about
253(start..end + 1) // cannot use RangeInclusive, so add one to end
254.into_par_iter()
255 .map(|codepoint| unsafe { char::from_u32_unchecked(codepoint) })
256 .$method($( $arg ),*)
257 }
258 } else {
259 empty::<char>().$method($( $arg ),*)
260 }
261 };
262}
263264impl ParallelIterator for Iter<char> {
265type Item = char;
266267fn drive_unindexed<C>(self, consumer: C) -> C::Result
268where
269C: UnindexedConsumer<Self::Item>,
270 {
271convert_char!(self.drive(consumer))
272 }
273274fn opt_len(&self) -> Option<usize> {
275Some(self.len())
276 }
277}
278279// Range<u32> is broken on 16 bit platforms, may as well benefit from it
280impl IndexedParallelIterator for Iter<char> {
281// Split at the surrogate range first if we're allowed to
282fn drive<C>(self, consumer: C) -> C::Result
283where
284C: Consumer<Self::Item>,
285 {
286convert_char!(self.drive(consumer))
287 }
288289fn len(&self) -> usize {
290if let Some((start, end)) = self.bounds() {
291// Taken from <char as Step>::steps_between
292let start = start as u32;
293let end = end as u32;
294let mut count = end - start;
295if start < 0xD800 && 0xE000 <= end {
296 count -= 0x800
297}
298 (count + 1) as usize // add one for inclusive
299} else {
3000
301}
302 }
303304fn with_producer<CB>(self, callback: CB) -> CB::Output
305where
306CB: ProducerCallback<Self::Item>,
307 {
308convert_char!(self.with_producer(callback))
309 }
310}
311312#[test]
313#[cfg(target_pointer_width = "64")]
314fn test_u32_opt_len() {
315assert_eq!(Some(101), (0..=100u32).into_par_iter().opt_len());
316assert_eq!(
317Some(u32::MAX as usize),
318 (0..=u32::MAX - 1).into_par_iter().opt_len()
319 );
320assert_eq!(
321Some(u32::MAX as usize + 1),
322 (0..=u32::MAX).into_par_iter().opt_len()
323 );
324}
325326#[test]
327fn test_u64_opt_len() {
328assert_eq!(Some(101), (0..=100u64).into_par_iter().opt_len());
329assert_eq!(
330Some(usize::MAX),
331 (0..=usize::MAX as u64 - 1).into_par_iter().opt_len()
332 );
333assert_eq!(None, (0..=usize::MAX as u64).into_par_iter().opt_len());
334assert_eq!(None, (0..=u64::MAX).into_par_iter().opt_len());
335}
336337#[test]
338fn test_u128_opt_len() {
339assert_eq!(Some(101), (0..=100u128).into_par_iter().opt_len());
340assert_eq!(
341Some(usize::MAX),
342 (0..=usize::MAX as u128 - 1).into_par_iter().opt_len()
343 );
344assert_eq!(None, (0..=usize::MAX as u128).into_par_iter().opt_len());
345assert_eq!(None, (0..=u128::MAX).into_par_iter().opt_len());
346}
347348// `usize as i64` can overflow, so make sure to wrap it appropriately
349// when using the `opt_len` "indexed" mode.
350#[test]
351#[cfg(target_pointer_width = "64")]
352fn test_usize_i64_overflow() {
353use crate::ThreadPoolBuilder;
354355let iter = (-2..=i64::MAX).into_par_iter();
356assert_eq!(iter.opt_len(), Some(i64::MAX as usize + 3));
357358// always run with multiple threads to split into, or this will take forever...
359let pool = ThreadPoolBuilder::new().num_threads(8).build().unwrap();
360 pool.install(|| assert_eq!(iter.find_last(|_| true), Some(i64::MAX)));
361}
362363#[test]
364fn test_issue_833() {
365fn is_even(n: i64) -> bool {
366 n % 2 == 0
367}
368369// The integer type should be inferred from `is_even`
370let v: Vec<_> = (1..=100).into_par_iter().filter(|&x| is_even(x)).collect();
371assert!(v.into_iter().eq((2..=100).step_by(2)));
372373// Try examples with indexed iterators too
374let pos = (0..=100).into_par_iter().position_any(|x| x == 50i16);
375assert_eq!(pos, Some(50usize));
376377assert!((0..=100)
378 .into_par_iter()
379 .zip(0..=100)
380 .all(|(a, b)| i16::eq(&a, &b)));
381}