Skip to main content

reth_concurrency/sync/
iter.rs

1//! Rayon iterator APIs, evaluated serially under the deterministic scheduler.
2//!
3//! With `fuzz` plus `--cfg dst`, adapter construction remains lazy and terminal operations drive
4//! Rayon's producers and consumers on the caller. Serial partitions do not reproduce
5//! worker schedules, parallel callback ordering, cancellation races, or partition
6//! counts. Compute callbacks must not depend on concurrent execution.
7
8#[cfg(all(feature = "fuzz", dst))]
9pub use deterministic::*;
10#[cfg(not(all(feature = "fuzz", dst)))]
11pub use rayon::iter::*;
12#[cfg(not(all(feature = "fuzz", dst)))]
13pub use rayon::slice::ParallelSliceMut;
14
15#[cfg(all(feature = "fuzz", dst))]
16mod deterministic {
17    use rayon::iter::plumbing::{
18        Consumer, Folder, Producer, ProducerCallback, Reducer, UnindexedConsumer,
19    };
20    use std::{
21        cmp::Ordering,
22        collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque},
23        iter::Sum,
24        ops::{Range, RangeInclusive},
25        panic::{catch_unwind, resume_unwind, AssertUnwindSafe},
26    };
27
28    // Only constructors in this module mark adapter trees whose drive paths never schedule workers.
29    trait SerialDriver: rayon::iter::ParallelIterator {}
30
31    /// A Rayon adapter whose drive delegates to serial source drivers.
32    #[derive(Debug, Clone)]
33    pub struct Delegated<TIterator>(TIterator);
34    impl<TIterator: rayon::iter::ParallelIterator> rayon::iter::ParallelIterator
35        for Delegated<TIterator>
36    {
37        type Item = TIterator::Item;
38        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
39            self.0.drive_unindexed(consumer)
40        }
41        fn opt_len(&self) -> Option<usize> {
42            rayon::iter::ParallelIterator::opt_len(&self.0)
43        }
44    }
45    impl<TIterator: rayon::iter::IndexedParallelIterator> rayon::iter::IndexedParallelIterator
46        for Delegated<TIterator>
47    {
48        fn len(&self) -> usize {
49            rayon::iter::IndexedParallelIterator::len(&self.0)
50        }
51        fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
52            drive_serial(self.0, consumer)
53        }
54        fn with_producer<CB: ProducerCallback<Self::Item>>(self, callback: CB) -> CB::Output {
55            self.0.with_producer(callback)
56        }
57    }
58    impl<TIterator: rayon::iter::ParallelIterator> SerialDriver for Delegated<TIterator> {}
59    impl<TIterator: rayon::iter::IndexedParallelIterator> SerialDriver for Serial<TIterator> {}
60    impl<TIterator: Iterator + Send> SerialDriver for Unindexed<TIterator> where TIterator::Item: Send {}
61    impl<TIterator: rayon::iter::IndexedParallelIterator> SerialDriver for Skip<TIterator> {}
62    impl<
63            TLeft: rayon::iter::ParallelIterator,
64            TRight: rayon::iter::ParallelIterator<Item = TLeft::Item>,
65        > SerialDriver for Chain<TLeft, TRight>
66    {
67    }
68    impl<TLeft: SerialDriver, TRight: SerialDriver<Item = TLeft::Item>> SerialDriver
69        for either::Either<TLeft, TRight>
70    {
71    }
72
73    /// A lazy indexed iterator driven on the caller without Rayon worker scheduling.
74    #[derive(Debug, Clone)]
75    pub struct Serial<TIterator>(TIterator);
76
77    impl<TIterator: rayon::iter::IndexedParallelIterator> rayon::iter::ParallelIterator
78        for Serial<TIterator>
79    {
80        type Item = TIterator::Item;
81
82        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
83            drive_serial(self.0, consumer)
84        }
85
86        fn opt_len(&self) -> Option<usize> {
87            Some(rayon::iter::IndexedParallelIterator::len(&self.0))
88        }
89    }
90
91    impl<TIterator: rayon::iter::IndexedParallelIterator> rayon::iter::IndexedParallelIterator
92        for Serial<TIterator>
93    {
94        fn len(&self) -> usize {
95            rayon::iter::IndexedParallelIterator::len(&self.0)
96        }
97
98        fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
99            drive_serial(self.0, consumer)
100        }
101
102        fn with_producer<CB: ProducerCallback<Self::Item>>(self, callback: CB) -> CB::Output {
103            self.0.with_producer(callback)
104        }
105    }
106
107    fn drive_serial<I: rayon::iter::IndexedParallelIterator, C: Consumer<I::Item>>(
108        iter: I,
109        consumer: C,
110    ) -> C::Result {
111        struct Callback<C> {
112            consumer: C,
113            len: usize,
114        }
115        impl<T, C: Consumer<T>> ProducerCallback<T> for Callback<C> {
116            type Output = C::Result;
117            fn callback<P: Producer<Item = T>>(self, producer: P) -> Self::Output {
118                let (producer, _) = producer.split_at(self.len);
119                if self.consumer.full() {
120                    self.consumer.into_folder().complete()
121                } else {
122                    producer.fold_with(self.consumer.into_folder()).complete()
123                }
124            }
125        }
126        let len = rayon::iter::IndexedParallelIterator::len(&iter);
127        iter.with_producer(Callback { consumer, len })
128    }
129
130    /// A serial source with no indexed splitting contract, including `par_bridge` inputs.
131    #[derive(Debug, Clone)]
132    pub struct Unindexed<TIterator> {
133        iter: TIterator,
134        len: Option<usize>,
135    }
136
137    impl<TIterator: Iterator + Send> rayon::iter::ParallelIterator for Unindexed<TIterator>
138    where
139        TIterator::Item: Send,
140    {
141        type Item = TIterator::Item;
142        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
143            if consumer.full() {
144                consumer.into_folder().complete()
145            } else {
146                consumer.into_folder().consume_iter(self.iter).complete()
147            }
148        }
149        fn opt_len(&self) -> Option<usize> {
150            self.len
151        }
152    }
153
154    /// Converts a collection or serial iterator into a deterministic compute iterator.
155    pub trait IntoParallelIterator {
156        /// The values yielded by this iterator.
157        type Item: Send;
158        /// The resulting deterministic iterator.
159        type Iter: ParallelIterator<Item = Self::Item>;
160        /// Converts this value without executing its lazy operations.
161        fn into_par_iter(self) -> Self::Iter;
162    }
163    impl<T: ParallelIterator> IntoParallelIterator for T {
164        type Item = T::Item;
165        type Iter = Self;
166        fn into_par_iter(self) -> Self {
167            self
168        }
169    }
170
171    macro_rules! into_parallel {
172        ([$($generics:tt)*] $source:ty) => {
173            impl<$($generics)*> IntoParallelIterator for $source
174            where Self: rayon::iter::IntoParallelIterator,
175                  <Self as rayon::iter::IntoParallelIterator>::Iter: rayon::iter::IndexedParallelIterator {
176                type Item = <Self as rayon::iter::IntoParallelIterator>::Item;
177                type Iter = Serial<<Self as rayon::iter::IntoParallelIterator>::Iter>;
178                fn into_par_iter(self) -> Self::Iter {
179                    Serial(rayon::iter::IntoParallelIterator::into_par_iter(self))
180                }
181            }
182        };
183    }
184    into_parallel!([T] Vec<T>);
185    into_parallel!([T] Option<T>);
186    into_parallel!([T, E] Result<T, E>);
187    into_parallel!(['a, T] &'a Option<T>);
188    into_parallel!(['a, T] &'a mut Option<T>);
189    into_parallel!(['a, T, E] &'a Result<T, E>);
190    into_parallel!(['a, T, E] &'a mut Result<T, E>);
191    into_parallel!([T, const N: usize] [T; N]);
192    into_parallel!(['a, T] &'a [T]);
193    into_parallel!(['a, T] &'a mut [T]);
194    into_parallel!(['a, T, const N: usize] &'a [T; N]);
195    into_parallel!(['a, T, const N: usize] &'a mut [T; N]);
196    into_parallel!(['a, T] &'a Vec<T>);
197    into_parallel!(['a, T] &'a mut Vec<T>);
198
199    macro_rules! into_unindexed {
200        ([$($generics:tt)*] $source:ty) => {
201            impl<$($generics)*> IntoParallelIterator for $source
202            where Self: IntoIterator, <Self as IntoIterator>::IntoIter: Send,
203                  <Self as IntoIterator>::Item: Send {
204                type Item = <Self as IntoIterator>::Item;
205                type Iter = Unindexed<<Self as IntoIterator>::IntoIter>;
206                fn into_par_iter(self) -> Self::Iter {
207                    let iter = self.into_iter();
208                    let (lower, upper) = iter.size_hint();
209                    Unindexed { iter, len: upper.filter(|&upper| upper == lower) }
210                }
211            }
212        };
213    }
214    into_unindexed!([K, V] BTreeMap<K, V>);
215    into_unindexed!([T] BTreeSet<T>);
216    into_unindexed!([K, V, S] HashMap<K, V, S>);
217    into_unindexed!([T, S] HashSet<T, S>);
218    into_parallel!([T] VecDeque<T>);
219    into_parallel!(['a, T] &'a VecDeque<T>);
220    into_parallel!(['a, T] &'a mut VecDeque<T>);
221    into_unindexed!([T] LinkedList<T>);
222    into_parallel!([T] BinaryHeap<T>);
223    into_parallel!(['a, T] &'a BinaryHeap<T>);
224    into_unindexed!(['a, K, V] &'a BTreeMap<K, V>);
225    into_unindexed!(['a, K, V] &'a mut BTreeMap<K, V>);
226    into_unindexed!(['a, T] &'a BTreeSet<T>);
227    into_unindexed!(['a, K, V, S] &'a HashMap<K, V, S>);
228    into_unindexed!(['a, K, V, S] &'a mut HashMap<K, V, S>);
229    into_unindexed!(['a, T, S] &'a HashSet<T, S>);
230    into_unindexed!(['a, T] &'a LinkedList<T>);
231    into_unindexed!(['a, T] &'a mut LinkedList<T>);
232
233    /// A numeric range source with serial iteration and Rayon's indexed producer, when available.
234    #[derive(Debug, Clone)]
235    pub struct RangeSource<TIterator>(TIterator);
236    impl<TIterator> rayon::iter::ParallelIterator for RangeSource<TIterator>
237    where
238        TIterator: Iterator
239            + Clone
240            + Send
241            + rayon::iter::IntoParallelIterator<Item = <TIterator as Iterator>::Item>,
242        <TIterator as Iterator>::Item: Send,
243    {
244        type Item = <TIterator as Iterator>::Item;
245        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
246            if consumer.full() {
247                consumer.into_folder().complete()
248            } else {
249                consumer.into_folder().consume_iter(self.0).complete()
250            }
251        }
252        fn opt_len(&self) -> Option<usize> {
253            rayon::iter::ParallelIterator::opt_len(
254                &rayon::iter::IntoParallelIterator::into_par_iter(self.0.clone()),
255            )
256        }
257    }
258    impl<TIterator> rayon::iter::IndexedParallelIterator for RangeSource<TIterator>
259    where
260        TIterator: Iterator
261            + Clone
262            + Send
263            + rayon::iter::IntoParallelIterator<Item = <TIterator as Iterator>::Item>,
264        <TIterator as Iterator>::Item: Send,
265        <TIterator as rayon::iter::IntoParallelIterator>::Iter:
266            rayon::iter::IndexedParallelIterator,
267    {
268        fn len(&self) -> usize {
269            rayon::iter::IndexedParallelIterator::len(
270                &rayon::iter::IntoParallelIterator::into_par_iter(self.0.clone()),
271            )
272        }
273        fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
274            drive_serial(self, consumer)
275        }
276        fn with_producer<CB: ProducerCallback<Self::Item>>(self, callback: CB) -> CB::Output {
277            rayon::iter::IndexedParallelIterator::with_producer(
278                rayon::iter::IntoParallelIterator::into_par_iter(self.0),
279                callback,
280            )
281        }
282    }
283    impl<TIterator> SerialDriver for RangeSource<TIterator>
284    where
285        TIterator: Iterator
286            + Clone
287            + Send
288            + rayon::iter::IntoParallelIterator<Item = <TIterator as Iterator>::Item>,
289        <TIterator as Iterator>::Item: Send,
290    {
291    }
292    macro_rules! into_range {
293        ($range:ident) => {
294            impl<T> IntoParallelIterator for $range<T>
295            where
296                Self: Iterator
297                    + Clone
298                    + Send
299                    + rayon::iter::IntoParallelIterator<Item = <Self as Iterator>::Item>,
300                <Self as Iterator>::Item: Send,
301            {
302                type Item = <Self as Iterator>::Item;
303                type Iter = RangeSource<Self>;
304                fn into_par_iter(self) -> Self::Iter {
305                    RangeSource(self)
306                }
307            }
308        };
309    }
310    into_range!(Range);
311    into_range!(RangeInclusive);
312
313    /// A lazy map adapter retaining the source compute iterator's indexed guarantees.
314    pub type Map<TIterator, TMap> =
315        Delegated<rayon::iter::Map<<TIterator as ParallelIterator>::Inner, TMap>>;
316
317    /// Borrows a collection as a deterministic compute iterator.
318    pub trait IntoParallelRefIterator<'a> {
319        /// The borrowed item type.
320        type Item: Send + 'a;
321        /// The resulting iterator over shared references.
322        type Iter: ParallelIterator<Item = Self::Item>;
323        /// Iterates over shared references in collection order.
324        fn par_iter(&'a self) -> Self::Iter;
325    }
326    impl<'a, T: ?Sized + 'a> IntoParallelRefIterator<'a> for T
327    where
328        &'a T: IntoParallelIterator,
329        <&'a T as IntoParallelIterator>::Item: 'a,
330    {
331        type Item = <&'a T as IntoParallelIterator>::Item;
332        type Iter = <&'a T as IntoParallelIterator>::Iter;
333        fn par_iter(&'a self) -> Self::Iter {
334            self.into_par_iter()
335        }
336    }
337
338    /// Mutably borrows a collection as a deterministic compute iterator.
339    pub trait IntoParallelRefMutIterator<'a> {
340        /// The mutably borrowed item type.
341        type Item: Send + 'a;
342        /// The resulting iterator over mutable references.
343        type Iter: ParallelIterator<Item = Self::Item>;
344        /// Iterates over mutable references in collection order.
345        fn par_iter_mut(&'a mut self) -> Self::Iter;
346    }
347    impl<'a, T: ?Sized + 'a> IntoParallelRefMutIterator<'a> for T
348    where
349        &'a mut T: IntoParallelIterator,
350        <&'a mut T as IntoParallelIterator>::Item: 'a,
351    {
352        type Item = <&'a mut T as IntoParallelIterator>::Item;
353        type Iter = <&'a mut T as IntoParallelIterator>::Iter;
354        fn par_iter_mut(&'a mut self) -> Self::Iter {
355            self.into_par_iter()
356        }
357    }
358
359    /// Adapts a serial iterator without introducing native worker threads.
360    pub trait ParallelBridge: Iterator + Sized + Send
361    where
362        Self::Item: Send,
363    {
364        /// Preserves source order and laziness without promising an indexed length.
365        fn par_bridge(self) -> Unindexed<Self> {
366            Unindexed { iter: self, len: None }
367        }
368    }
369    impl<T: Iterator + Send> ParallelBridge for T where T::Item: Send {}
370
371    /// Builds a collection from deterministic compute results.
372    pub trait FromParallelIterator<TItem>: Sized
373    where
374        TItem: Send,
375    {
376        /// Collects all results in deterministic iterator order.
377        fn from_par_iter<T: IntoParallelIterator<Item = TItem>>(iter: T) -> Self;
378    }
379    macro_rules! from_parallel {
380        ([$($generics:tt)*] $item:ty => $collection:ty) => {
381            impl<$($generics)*> FromParallelIterator<$item> for $collection
382            where Self: FromIterator<$item>, $item: Send {
383                fn from_par_iter<T: IntoParallelIterator<Item = $item>>(iter: T) -> Self {
384                    let items = rayon::iter::ParallelIterator::collect::<Vec<_>>(iter.into_par_iter().into_rayon());
385                    items.into_iter().collect()
386                }
387            }
388        };
389    }
390    from_parallel!([TItem] TItem => Vec<TItem>);
391    from_parallel!([TItem] TItem => BTreeSet<TItem>);
392    from_parallel!([TKey, TValue] (TKey, TValue) => BTreeMap<TKey, TValue>);
393    from_parallel!([TItem, THasher] TItem => HashSet<TItem, THasher>);
394    from_parallel!([TKey, TValue, THasher] (TKey, TValue) => HashMap<TKey, TValue, THasher>);
395    struct Collected<TCollection>(TCollection);
396
397    impl<TItem: Send, TCollection: FromParallelIterator<TItem>>
398        rayon::iter::FromParallelIterator<TItem> for Collected<TCollection>
399    {
400        fn from_par_iter<T: rayon::iter::IntoParallelIterator<Item = TItem>>(iter: T) -> Self {
401            // Only our Result collector constructs this bridge; Rayon retains its serial source
402            // drivers while adding the lazy error adapter passed to the destination collection.
403            Self(TCollection::from_par_iter(Delegated(
404                rayon::iter::IntoParallelIterator::into_par_iter(iter),
405            )))
406        }
407    }
408
409    impl<TItem: Send, TError: Send, TCollection: FromParallelIterator<TItem>>
410        FromParallelIterator<Result<TItem, TError>> for Result<TCollection, TError>
411    {
412        fn from_par_iter<T: IntoParallelIterator<Item = Result<TItem, TError>>>(iter: T) -> Self {
413            rayon::iter::ParallelIterator::collect::<Result<Collected<TCollection>, TError>>(
414                iter.into_par_iter().into_rayon(),
415            )
416            .map(|Collected(collection)| collection)
417        }
418    }
419
420    /// A lazy compute iterator; deterministic builds drive producers on the caller.
421    pub trait ParallelIterator: Sized + Send {
422        /// The yielded value type.
423        type Item: Send;
424        /// The lazy Rayon adapter tree, with serial drivers at its scheduling boundaries.
425        type Inner: rayon::iter::ParallelIterator<Item = Self::Item>;
426        /// Returns the lazy adapter tree without driving it.
427        fn into_rayon(self) -> Self::Inner;
428        /// Returns the exact result length when known without evaluating callbacks.
429        fn opt_len(&self) -> Option<usize> {
430            None
431        }
432        /// Lazily transforms each item.
433        fn map<TOutput: Send, TMap: Fn(Self::Item) -> TOutput + Send + Sync>(
434            self,
435            f: TMap,
436        ) -> Map<Self, TMap> {
437            Delegated(rayon::iter::ParallelIterator::map(self.into_rayon(), f))
438        }
439        /// Retains items satisfying the predicate.
440        fn filter<TFilter: Fn(&Self::Item) -> bool + Send + Sync>(
441            self,
442            f: TFilter,
443        ) -> Delegated<rayon::iter::Filter<Self::Inner, TFilter>> {
444            Delegated(rayon::iter::ParallelIterator::filter(self.into_rayon(), f))
445        }
446        /// Transforms and retains items with a nonempty result.
447        fn filter_map<TOutput: Send, TMap: Fn(Self::Item) -> Option<TOutput> + Send + Sync>(
448            self,
449            f: TMap,
450        ) -> Delegated<rayon::iter::FilterMap<Self::Inner, TMap>> {
451            Delegated(rayon::iter::ParallelIterator::filter_map(self.into_rayon(), f))
452        }
453        /// Expands each item into another deterministic iterator.
454        fn flat_map<
455            TOutput: IntoParallelIterator,
456            TMap: Fn(Self::Item) -> TOutput + Send + Sync,
457        >(
458            self,
459            f: TMap,
460        ) -> impl ParallelIterator<Item = TOutput::Item> {
461            Delegated(rayon::iter::ParallelIterator::flat_map(self.into_rayon(), move |item| {
462                f(item).into_par_iter().into_rayon()
463            }))
464        }
465        /// Runs a callback for every item in source order.
466        fn for_each(self, f: impl Fn(Self::Item) + Send + Sync) {
467            rayon::iter::ParallelIterator::for_each(self.into_rayon(), f);
468        }
469        /// Runs fallible callbacks until the first error, preserving that error.
470        fn try_for_each<TError: Send>(
471            self,
472            f: impl Fn(Self::Item) -> Result<(), TError> + Send + Sync,
473        ) -> Result<(), TError> {
474            rayon::iter::ParallelIterator::try_for_each(self.into_rayon(), f)
475        }
476        /// Collects results using the collection's parallel-construction implementation.
477        fn collect<T: FromParallelIterator<Self::Item>>(self) -> T {
478            T::from_par_iter(self)
479        }
480        /// Folds each serial partition into one value.
481        fn fold<
482            TAccumulator: Send,
483            TIdentity: Fn() -> TAccumulator + Send + Sync,
484            TFold: Fn(TAccumulator, Self::Item) -> TAccumulator + Send + Sync,
485        >(
486            self,
487            identity: TIdentity,
488            fold: TFold,
489        ) -> Delegated<rayon::iter::Fold<Self::Inner, TIdentity, TFold>> {
490            Delegated(rayon::iter::ParallelIterator::fold(self.into_rayon(), identity, fold))
491        }
492        /// Combines all items starting with the identity value.
493        fn reduce(
494            self,
495            identity: impl Fn() -> Self::Item + Send + Sync,
496            reduce: impl Fn(Self::Item, Self::Item) -> Self::Item + Send + Sync,
497        ) -> Self::Item {
498            rayon::iter::ParallelIterator::reduce(self.into_rayon(), identity, reduce)
499        }
500        /// Combines all items, returning `None` for an empty iterator.
501        fn reduce_with(
502            self,
503            reduce: impl Fn(Self::Item, Self::Item) -> Self::Item + Send + Sync,
504        ) -> Option<Self::Item> {
505            rayon::iter::ParallelIterator::reduce_with(self.into_rayon(), reduce)
506        }
507        /// Sums all yielded values.
508        fn sum<T: Sum<Self::Item> + Sum<T> + Send>(self) -> T {
509            rayon::iter::ParallelIterator::sum(self.into_rayon())
510        }
511        /// Counts all yielded values.
512        fn count(self) -> usize {
513            rayon::iter::ParallelIterator::count(self.into_rayon())
514        }
515        /// Returns the first matching item in deterministic source order, or `None`.
516        fn find_any(
517            self,
518            predicate: impl Fn(&Self::Item) -> bool + Send + Sync,
519        ) -> Option<Self::Item> {
520            rayon::iter::ParallelIterator::find_any(self.into_rayon(), predicate)
521        }
522        /// Returns whether any value satisfies the predicate.
523        fn any(self, f: impl Fn(Self::Item) -> bool + Send + Sync) -> bool {
524            rayon::iter::ParallelIterator::any(self.into_rayon(), f)
525        }
526        /// Returns whether all values satisfy the predicate.
527        fn all(self, f: impl Fn(Self::Item) -> bool + Send + Sync) -> bool {
528            rayon::iter::ParallelIterator::all(self.into_rayon(), f)
529        }
530        /// Concatenates two compute iterators in source order.
531        fn chain<T: IntoParallelIterator<Item = Self::Item>>(
532            self,
533            other: T,
534        ) -> Chain<Self::Inner, <T::Iter as ParallelIterator>::Inner> {
535            Chain(self.into_rayon(), other.into_par_iter().into_rayon())
536        }
537    }
538    impl<TIterator: SerialDriver> ParallelIterator for TIterator {
539        type Item = TIterator::Item;
540        type Inner = Self;
541        fn into_rayon(self) -> Self {
542            self
543        }
544        fn opt_len(&self) -> Option<usize> {
545            rayon::iter::ParallelIterator::opt_len(self)
546        }
547    }
548
549    /// A compute iterator with an exact length and stable source indices.
550    pub trait IndexedParallelIterator:
551        ParallelIterator<Inner: rayon::iter::IndexedParallelIterator>
552    {
553        /// Returns the number of items without evaluating lazy mappings.
554        fn len(&self) -> usize;
555        /// Returns whether there are no items.
556        fn is_empty(&self) -> bool {
557            self.len() == 0
558        }
559        /// Attaches each item's zero-based source index.
560        fn enumerate(self) -> Serial<rayon::iter::Enumerate<Self::Inner>> {
561            Serial(rayon::iter::IndexedParallelIterator::enumerate(self.into_rayon()))
562        }
563        /// Preserves source order without partition scheduling.
564        fn by_exponential_blocks(self) -> Self {
565            self
566        }
567        /// Takes at most the first `count` items.
568        fn take(self, count: usize) -> Serial<rayon::iter::Take<Self::Inner>> {
569            Serial(rayon::iter::IndexedParallelIterator::take(self.into_rayon(), count))
570        }
571        /// Skips the first `count` items, driving the skipped prefix when consumed.
572        fn skip(self, count: usize) -> Skip<Self::Inner> {
573            let count = count.min(self.len());
574            Skip { base: self.into_rayon(), count }
575        }
576        /// Reverses source indices without evaluating lazy mappings.
577        fn rev(self) -> Serial<rayon::iter::Rev<Self::Inner>> {
578            Serial(rayon::iter::IndexedParallelIterator::rev(self.into_rayon()))
579        }
580        /// Pairs values at matching indices, stopping at the shorter iterator.
581        fn zip<T: IntoParallelIterator>(
582            self,
583            other: T,
584        ) -> Serial<rayon::iter::Zip<Self::Inner, <T::Iter as ParallelIterator>::Inner>>
585        where
586            T::Iter: IndexedParallelIterator,
587        {
588            Serial(rayon::iter::IndexedParallelIterator::zip(
589                self.into_rayon(),
590                other.into_par_iter().into_rayon(),
591            ))
592        }
593    }
594    impl<TIterator: SerialDriver + rayon::iter::IndexedParallelIterator> IndexedParallelIterator
595        for TIterator
596    {
597        fn len(&self) -> usize {
598            rayon::iter::IndexedParallelIterator::len(self)
599        }
600    }
601
602    /// A concatenation with serial branch drivers and producer-level indexed splitting.
603    #[derive(Debug, Clone)]
604    pub struct Chain<TLeft, TRight>(TLeft, TRight);
605    impl<
606            TLeft: rayon::iter::ParallelIterator,
607            TRight: rayon::iter::ParallelIterator<Item = TLeft::Item>,
608        > rayon::iter::ParallelIterator for Chain<TLeft, TRight>
609    {
610        type Item = TLeft::Item;
611        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
612            let (left, right, reducer) =
613                if let Some(len) = rayon::iter::ParallelIterator::opt_len(&self.0) {
614                    consumer.split_at(len)
615                } else {
616                    let reducer = consumer.to_reducer();
617                    (consumer.split_off_left(), consumer, reducer)
618                };
619            // Both branches must be driven even if the other branch panics or short-circuits.
620            let left = catch_unwind(AssertUnwindSafe(|| self.0.drive_unindexed(left)));
621            let right = catch_unwind(AssertUnwindSafe(|| self.1.drive_unindexed(right)));
622            // Rayon's join propagates the left panic when both branches panic.
623            match (left, right) {
624                (Ok(left), Ok(right)) => reducer.reduce(left, right),
625                (Err(panic), _) | (_, Err(panic)) => resume_unwind(panic),
626            }
627        }
628        fn opt_len(&self) -> Option<usize> {
629            rayon::iter::ParallelIterator::opt_len(&self.0)?
630                .checked_add(rayon::iter::ParallelIterator::opt_len(&self.1)?)
631        }
632    }
633    impl<
634            TLeft: rayon::iter::IndexedParallelIterator,
635            TRight: rayon::iter::IndexedParallelIterator<Item = TLeft::Item>,
636        > rayon::iter::IndexedParallelIterator for Chain<TLeft, TRight>
637    {
638        fn len(&self) -> usize {
639            rayon::iter::IndexedParallelIterator::len(&self.0)
640                .checked_add(rayon::iter::IndexedParallelIterator::len(&self.1))
641                .expect("indexed chain length fits usize")
642        }
643        fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
644            drive_serial(self, consumer)
645        }
646        fn with_producer<CB: ProducerCallback<Self::Item>>(self, callback: CB) -> CB::Output {
647            rayon::iter::IndexedParallelIterator::with_producer(
648                rayon::iter::ParallelIterator::chain(self.0, self.1),
649                callback,
650            )
651        }
652    }
653
654    /// An indexed skip whose prefix is driven at terminal producer preparation.
655    #[derive(Debug, Clone)]
656    pub struct Skip<TIterator> {
657        base: TIterator,
658        count: usize,
659    }
660    impl<TIterator: rayon::iter::IndexedParallelIterator> rayon::iter::ParallelIterator
661        for Skip<TIterator>
662    {
663        type Item = TIterator::Item;
664        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
665            drive_serial(self, consumer)
666        }
667        fn opt_len(&self) -> Option<usize> {
668            Some(rayon::iter::IndexedParallelIterator::len(self))
669        }
670    }
671    impl<TIterator: rayon::iter::IndexedParallelIterator> rayon::iter::IndexedParallelIterator
672        for Skip<TIterator>
673    {
674        fn len(&self) -> usize {
675            rayon::iter::IndexedParallelIterator::len(&self.base) - self.count
676        }
677        fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
678            drive_serial(self, consumer)
679        }
680        fn with_producer<CB: ProducerCallback<Self::Item>>(self, callback: CB) -> CB::Output {
681            struct Callback<CB> {
682                callback: CB,
683                count: usize,
684            }
685            impl<T, CB: ProducerCallback<T>> ProducerCallback<T> for Callback<CB> {
686                type Output = CB::Output;
687                fn callback<P: Producer<Item = T>>(self, base: P) -> CB::Output {
688                    let (before, after) = base.split_at(self.count);
689                    // Like Rayon's skip scope, a prefix panic must not cancel the suffix callback.
690                    let prefix =
691                        catch_unwind(AssertUnwindSafe(|| before.into_iter().for_each(drop)));
692                    let output = self.callback.callback(after);
693                    if let Err(panic) = prefix {
694                        resume_unwind(panic);
695                    }
696                    output
697                }
698            }
699            self.base.with_producer(Callback { callback, count: self.count })
700        }
701    }
702
703    /// In-place slice sorting without native workers in deterministic builds.
704    pub trait ParallelSliceMut<T: Send> {
705        /// Stably sorts items by their derived keys.
706        fn par_sort_by_key<TKey: Ord, TKeyFn: Fn(&T) -> TKey + Sync>(&mut self, key: TKeyFn);
707        /// Sorts items by their derived keys without preserving equal-key order.
708        fn par_sort_unstable_by_key<TKey: Ord, TKeyFn: Fn(&T) -> TKey + Sync>(
709            &mut self,
710            key: TKeyFn,
711        );
712        /// Sorts items by a comparator without preserving equal-item order.
713        fn par_sort_unstable_by<TCompare: Fn(&T, &T) -> Ordering + Sync>(
714            &mut self,
715            compare: TCompare,
716        );
717    }
718    impl<T: Send> ParallelSliceMut<T> for [T] {
719        fn par_sort_by_key<TKey: Ord, TKeyFn: Fn(&T) -> TKey + Sync>(&mut self, key: TKeyFn) {
720            self.sort_by_key(key);
721        }
722        fn par_sort_unstable_by_key<TKey: Ord, TKeyFn: Fn(&T) -> TKey + Sync>(
723            &mut self,
724            key: TKeyFn,
725        ) {
726            self.sort_unstable_by_key(key);
727        }
728        fn par_sort_unstable_by<TCompare: Fn(&T, &T) -> Ordering + Sync>(
729            &mut self,
730            compare: TCompare,
731        ) {
732            self.sort_unstable_by(compare);
733        }
734    }
735}