orx-parallel 4.0.0

Performant parallel computations with an expressive iterator API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
use crate::infallible::recursive::par_core::ParRecCore;
use crate::infallible::xap::FlattenOf;
use crate::infallible::{FilMapOf, FilOf, FlatMapOf, InsOf, MapOf};
use crate::runner::ParRunner;
use crate::{ChunkSize, IterationOrder, NumThreads};
use crate::{ParExtend, Sum};
use alloc::vec::Vec;
use core::cmp::Ordering;

/// Infallible parallel recursive iterator.
///
/// `ParRec` is the central trait for describing recursive parallel computations as iterator
/// pipelines. It mirrors common sequential iterator operations (`map`,
/// `filter`, `flat_map`, `collect`, `reduce`, ...) while allowing runtime
/// configuration of execution details such as number of threads, chunk size,
/// iteration order, and runner/pool selection.
///
/// Recursive traversal can be deterministic: with [`IterationOrder::Ordered`] (the default),
/// order-sensitive operations use breadth-first order, level by level and left-to-right following
/// input and child generation order.
///
/// [`IterationOrder::Ordered`]: crate::IterationOrder::Ordered
///
/// Related traits:
/// - [`ParUse`](crate::ParUse) for worker-local mutable state,
/// - [`ParOption`](crate::ParOption) for `Option`-based fallibility,
/// - [`ParResult`](crate::ParResult) for `Result`-based fallibility.
///
/// # Examples
///
/// ```
/// use orx_parallel::*;
///
/// // A small rooted tree represented as adjacency lists; node 0 is the root.
/// let children: Vec<Vec<usize>> = vec![vec![1, 2], vec![3, 4], vec![5], vec![], vec![], vec![]];
///
/// let sum_of_even_squares: usize = par_recursive([0usize], |node| children[*node].iter().copied())
///     .map(|x| x * x)
///     .filter(|x| x % 2 == 0)
///     .sum();
///
/// assert_eq!(sum_of_even_squares, 20);
/// ```
pub trait ParRec: Sized + ParRecCore {
    // configuration

    /// Replaces the current parallel runner with `runner`.
    ///
    /// This allows per-computation control over execution strategy.
    ///
    /// Please see [`Runner`] for parallel runners implemented in this crate.
    ///
    /// [`Runner`]: crate::Runner
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let children: Vec<Vec<usize>> = vec![vec![1, 2], vec![3, 4], vec![5], vec![], vec![], vec![]];
    ///
    /// let baseline: usize = par_recursive([0usize], |node| children[*node].iter().copied()).sum();
    ///
    /// let par = par_recursive([0usize], |node| children[*node].iter().copied());
    ///
    /// let par = par.runner(Runner::fixed());
    ///
    /// let configured: usize = par.sum();
    /// assert_eq!(baseline, configured);
    /// ```
    fn runner<Q: ParRunner>(
        self,
        runner: Q,
    ) -> impl ParRec<Item = Self::Item, Xap = Self::Xap, Input = Self::Input>;

    /// Wraps the current parallel runner with a diagnostics-enabled runner.
    ///
    /// The returned iterator behaves the same, but additionally reports runtime
    /// diagnostics at the end of the computation.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "std")]
    /// # fn main() {
    /// use orx_parallel::*;
    ///
    /// let par = par_recursive([1i32], |&x| (x < 10_000).then_some(x + 1))
    ///     .num_threads(4);
    ///
    /// #[cfg(feature = "std")]
    /// let par = par.runner_with_diagnostics();
    ///
    /// let sum = par.sum::<i32>();
    /// assert_eq!(sum, 50005000);
    /// # }
    /// ```
    ///
    /// This will print a summary report which currently looks like the following:
    ///
    /// ```console
    /// │ # Parallel Executor Diagnostics
    /// │
    /// │   Available threads : 4
    /// │   Used threads      : 4
    /// │   Wall time         : 1.15 ms
    /// │
    /// │ ## Summary Table
    /// │   thread  num_chunks   num_tasks  min_chunk  avg_chunk  max_chunk    util%
    /// │   ------  ----------  ----------  ---------  ---------  ---------  -------
    /// │        0          35       27335        781        781        781   100.0%
    /// │        1          32       24992        781        781        781    91.5%
    /// │        2          30       23430        781        781        781    85.9%
    /// │        3          28       21868        781        781        781    77.8%
    /// │
    /// │ ## Workload Balance
    /// │   max/min task ratio  : 1.25x  (1.00 = perfect balance)
    /// │   coeff. of variation : 8.3%  (lower is better)
    /// │
    /// │ ## Thread Active Timeline  (each block ≈ 0.02 ms)
    /// │   [ 0] ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇
    /// │   [ 1]     ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇
    /// │   [ 2]         ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇
    /// │   [ 3]             ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇
    /// │
    /// │ ## Thread Task Distribution  (bar length ∝ tasks processed)
    /// │   [ 0] ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇  (27335)
    /// │   [ 1] ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇  (24992)
    /// │   [ 2] ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇  (23430)
    /// │   [ 3] ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇  (21868)
    /// ```
    #[cfg(feature = "std")]
    fn runner_with_diagnostics(
        self,
    ) -> impl ParRec<Item = Self::Item, Xap = Self::Xap, Input = Self::Input>;

    /// Sets the maximum number of worker threads for this computation.
    ///
    /// This method configures the **computation layer** of the thread count decision.
    /// The actual number of threads used is determined by combining:
    ///
    /// 1. **Pool constraint** (from `pool()` method or default pool)
    ///    - Already includes `ORX_NUM_THREADS` environment variable constraint
    /// 2. **Computation constraint** (this method)
    ///    - Your per-computation thread preference
    /// 3. **Input size constraint**
    ///    - Cannot spawn more threads than input elements
    ///
    /// The actual thread count is the **minimum** of all these constraints.
    ///
    /// # Parameter Interpretation
    ///
    /// Integer values map as follows:
    /// - `0` => `NumThreads::Auto` (use all available threads, spawn only as needed)
    /// - `n > 0` => `NumThreads::Max(n)` (cap at `n` threads)
    ///
    /// # Thread Count Decision Logic
    ///
    /// ```text
    /// available = pool.max_num_threads()      // Pool maximum (includes env variable)
    ///
    /// requested = match num_threads {
    ///     0 | Auto => input_size.max(1),      // Limited by input size
    ///     Max(n) => min(input_size, n),       // Limited by input size and this param
    /// };
    ///
    /// actual_threads = min(requested, available)
    /// ```
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use orx_parallel::*;
    ///
    /// // Sequential execution
    /// let sum: usize = par_recursive([1usize], |&x| (x < 10).then_some(x + 1))
    ///     .num_threads(1)
    ///     .sum();
    /// assert_eq!(sum, 55);
    ///
    /// // Cap at 4 threads
    /// let sum: usize = par_recursive([1usize], |&x| (x < 1000).then_some(x + 1))
    ///     .num_threads(4)
    ///     .sum();
    ///
    /// // Auto: uses available threads (respects ORX_NUM_THREADS)
    /// let sum: usize = par_recursive([1usize], |&x| (x < 10).then_some(x + 1))
    ///     .num_threads(0)
    ///     .sum();
    /// ```
    ///
    /// # See Also
    ///
    /// - [`NumThreads`](crate::NumThreads) - Type for thread configuration
    /// - [`thread_usage.md`](https://github.com/orxfun/orx-parallel/blob/main/docs/thread_usage.md) - Complete threading guide
    fn num_threads(self, num_threads: impl Into<NumThreads>) -> Self;

    /// Sets chunk size used when pulling items from the concurrent input.
    ///
    /// Integer values map as follows:
    /// - `0` => automatic (default)
    /// - `n > 0` => exact chunk size `n`
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let values: Vec<_> = par_recursive([0usize], |&x| (x < 31).then_some(x + 1))
    ///     .chunk_size(8)
    ///     .map(|x| x + 1)
    ///     .collect();
    ///
    /// assert_eq!(values.len(), 32);
    /// assert_eq!(values[0], 1);
    /// assert_eq!(values[31], 32);
    /// ```
    ///
    /// # Rules of Thumb
    ///
    /// * Automatic chunk size (default) is efficient in general.
    ///   Parallel runner aims to find best chunk sizes to balance between minimizing parallelization overhead
    ///   and maximizing resource utilization.
    /// * While tuning a specific computation, we aim to find the smallest chunk size that is large enough
    ///   to mitigate the impact of parallelization overhead.
    /// * If the individual tasks are large enough, parallelization overhead becomes insignificant making
    ///   `chunk_size = 1` the optimal choice.
    fn chunk_size(self, chunk_size: impl Into<ChunkSize>) -> Self;

    /// Sets iteration order semantics for operations sensitive to ordering.
    ///
    /// `Ordered` (default) preserves positional meaning (for example, `first` returns the
    /// earliest matching element in input order). `Arbitrary` allows any matching
    /// element that is reached first in parallel execution.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let ordered = par_recursive([1i32], |&x| (x < 9_999).then_some(x + 1))
    ///     .iteration_order(IterationOrder::Ordered)
    ///     .find(|x| x % 3421 == 0);
    /// assert_eq!(ordered, Some(3421));
    ///
    /// let any = par_recursive([1i32], |&x| (x < 9_999).then_some(x + 1))
    ///     .iteration_order(IterationOrder::Arbitrary)
    ///     .find(|x| x % 3421 == 0)
    ///     .unwrap();
    /// assert!([3421, 6842].contains(&any));
    /// ```
    fn iteration_order(self, collect: IterationOrder) -> Self;

    // transformations

    /// Maps each element with closure `h`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let doubled: Vec<_> = par_recursive([1i32], |&x| (x < 3).then_some(x + 1))
    ///     .map(|x| 2 * x)
    ///     .collect();
    /// assert_eq!(doubled, vec![2, 4, 6]);
    /// ```
    fn map<Q, H>(
        self,
        h: H,
    ) -> impl ParRec<Item = Q, Xap = MapOf<Self::Xap, Q, H>, Input = Self::Input>
    where
        H: Fn(Self::Item) -> Q + Copy + Send;

    /// Runs `h` on each element and forwards the item unchanged.
    ///
    /// Useful for logging or debugging pipelines.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Vec<_> = par_recursive([1i32], |&x| (x < 4).then_some(x + 1))
    ///     .inspect(|x| {
    ///         println!("observed {x}");
    ///     })
    ///     .collect();
    ///
    /// assert_eq!(out, vec![1, 2, 3, 4]);
    /// ```
    fn inspect<H>(
        self,
        h: H,
    ) -> impl ParRec<Item = Self::Item, Xap = InsOf<Self::Xap, H>, Input = Self::Input>
    where
        H: Fn(&Self::Item) + Copy + Send;

    /// Keeps only elements satisfying predicate `h`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let odds: Vec<_> = par_recursive([1i32], |&x| (x < 6).then_some(x + 1))
    ///     .filter(|x| x % 2 == 1)
    ///     .collect();
    /// assert_eq!(odds, vec![1, 3, 5]);
    /// ```
    fn filter<H>(
        self,
        h: H,
    ) -> impl ParRec<Item = Self::Item, Xap = FilOf<Self::Xap, H>, Input = Self::Input>
    where
        H: Fn(&Self::Item) -> bool + Copy + Send;

    /// Maps and filters in a single pass.
    ///
    /// Returns mapped values for elements where `h` returns `Some(_)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let numbers: Vec<_> = par_recursive(["1", "x", "5"], |_: &&str| None::<&str>)
    ///     .filter_map(|s| s.parse::<usize>().ok())
    ///     .collect();
    ///
    /// assert_eq!(numbers, vec![1, 5]);
    /// ```
    fn filter_map<Q, H>(
        self,
        h: H,
    ) -> impl ParRec<Item = Q, Xap = FilMapOf<Self::Xap, Q, H>, Input = Self::Input>
    where
        H: Fn(Self::Item) -> Option<Q> + Copy + Send;

    /// Maps each element to an iterator and flattens one level.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Vec<_> = par_recursive([1i32], |&x| (x < 3).then_some(x + 1))
    ///     .flat_map(|x| [x, x + 10])
    ///     .collect();
    /// assert_eq!(out, vec![1, 11, 2, 12, 3, 13]);
    /// ```
    fn flat_map<V, H>(
        self,
        h: H,
    ) -> impl ParRec<Item = V::Item, Xap = FlatMapOf<Self::Xap, V, H>, Input = Self::Input>
    where
        V: IntoIterator,
        H: Fn(Self::Item) -> V + Copy + Send;

    /// Flattens one level of nested iterables.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let nested = vec![vec![1, 2], vec![3, 4]];
    /// let mut flat: Vec<_> = par_recursive(nested, |_: &Vec<i32>| None::<Vec<i32>>)
    ///     .flatten()
    ///     .collect();
    /// flat.sort();
    ///
    /// assert_eq!(flat, vec![1, 2, 3, 4]);
    /// ```
    fn flatten(
        self,
    ) -> impl ParRec<
        Item = <Self::Item as IntoIterator>::Item,
        Xap = FlattenOf<Self::Xap>,
        Input = Self::Input,
    >
    where
        Self::Item: IntoIterator;

    // compute

    /// Returns an item, or `None` if empty.
    ///
    /// When [`IterationOrder::Ordered`] (default) is set, returns the first item in deterministic
    /// breadth-first order (level by level, left-to-right following input and child generation order).
    ///
    /// Setting [`IterationOrder::Arbitrary`] may provide speed improvements when ordering is not
    /// important; however, ordered traversal is also optimized so the performance difference
    /// is generally small.
    ///
    /// This operation is short-circuiting: once a first candidate is determined,
    /// remaining work is cancelled.
    ///
    /// [`IterationOrder::Ordered`]: crate::IterationOrder::Ordered
    /// [`IterationOrder::Arbitrary`]: crate::IterationOrder::Arbitrary
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let empty = par_recursive(Vec::<usize>::new(), |_: &usize| None::<usize>).first();
    /// assert_eq!(empty, None);
    ///
    /// let first = par_recursive([1usize], |&x| (x < 3).then_some(x + 1))
    ///     .first();
    /// assert_eq!(first, Some(1));
    /// ```
    fn first(self) -> Option<Self::Item>
    where
        Self::Item: Send,
        <Self::Input as IntoIterator>::Item: Send;

    /// Reduces items into one value using associative reducer `f`.
    ///
    /// Returns `None` for an empty iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let reduced = par_recursive([1i32], |&x| (x < 5).then_some(x + 1))
    ///     .reduce(|a, b| a + b);
    /// assert_eq!(reduced, Some(15));
    /// ```
    fn reduce<F>(self, f: F) -> Option<Self::Item>
    where
        F: Fn(Self::Item, Self::Item) -> Self::Item + Send + Copy,
        Self::Item: Send,
        <Self::Input as IntoIterator>::Item: Send;

    /// Collects all items into `dst`.
    ///
    /// When [`IterationOrder::Ordered`] (default) is set, items are collected in a deterministic
    /// breadth-first order (level by level, left-to-right following input and child generation order).
    ///
    /// Setting [`IterationOrder::Arbitrary`] may provide speed improvements when ordering is not
    /// important; however, ordered collection is also optimized so the performance difference
    /// is generally small.
    ///
    /// [`IterationOrder::Ordered`]: crate::IterationOrder::Ordered
    /// [`IterationOrder::Arbitrary`]: crate::IterationOrder::Arbitrary
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let mut dst = vec![10];
    /// par_recursive([0i32], |&x| (x < 2).then_some(x + 1))
    ///     .collect_into(&mut dst);
    /// assert_eq!(dst, vec![10, 0, 1, 2]);
    /// ```
    fn collect_into<P>(self, dst: &mut P)
    where
        P: ParExtend<Self::Item>,
        Self::Item: Send,
        <Self::Input as IntoIterator>::Item: Send;

    /// Collects all items into a new collection.
    ///
    /// When [`IterationOrder::Ordered`] (default) is set, items are collected in a deterministic
    /// breadth-first order (level by level, left-to-right following input and child generation order).
    ///
    /// Setting [`IterationOrder::Arbitrary`] may provide speed improvements when ordering is not
    /// important; however, ordered collection is also optimized so the performance difference
    /// is generally small.
    ///
    /// [`IterationOrder::Ordered`]: crate::IterationOrder::Ordered
    /// [`IterationOrder::Arbitrary`]: crate::IterationOrder::Arbitrary
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Vec<_> = par_recursive([1i32], |&x| (x < 3).then_some(x + 1))
    ///     .map(|x| x * 2)
    ///     .collect();
    /// assert_eq!(out, vec![2, 4, 6]);
    /// ```
    fn collect<P>(self) -> P
    where
        P: ParExtend<Self::Item> + Default,
        Self::Item: Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        let mut dst = P::default();
        self.collect_into(&mut dst);
        dst
    }

    // compute - derived

    /// Returns `true` if all items satisfy predicate `f`.
    ///
    /// Empty iterators return `true`.
    ///
    /// This operation is short-circuiting: evaluation stops as soon as one item
    /// fails the predicate.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// assert!(par_recursive([1i32], |&x| (x < 4).then_some(x + 1))
    ///     .all(|x| x > &0));
    /// assert!(!par_recursive([1i32], |&x| (x < 4).then_some(x + 1))
    ///     .all(|x| x % 2 == 0));
    /// ```
    fn all<F>(self, f: F) -> bool
    where
        F: Fn(&Self::Item) -> bool + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        self.map(move |x| f(&x)).find(|x| !*x).is_none()
    }

    /// Returns `true` if any item satisfies predicate `f`.
    ///
    /// Empty iterators return `false`.
    ///
    /// This operation is short-circuiting: evaluation stops as soon as one item
    /// satisfies the predicate.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// assert!(par_recursive([1i32], |&x| (x < 4).then_some(x + 1))
    ///     .any(|x| x % 2 == 0));
    /// assert!(!par_recursive([1i32], |&x| (x < 4).then_some(x + 1))
    ///     .any(|x| x > &10));
    /// ```
    fn any<F>(self, f: F) -> bool
    where
        F: Fn(&Self::Item) -> bool + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        self.map(move |x| f(&x)).find(|x| *x).is_some()
    }

    /// Counts elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let n = par_recursive([1i32], |&x| (x < 10).then_some(x + 1))
    ///     .filter(|x| x % 3 == 0)
    ///     .count();
    /// assert_eq!(n, 3);
    /// ```
    fn count(self) -> usize
    where
        <Self::Input as IntoIterator>::Item: Send,
    {
        self.map(|_| 1).reduce(|a, b| a + b).unwrap_or(0)
    }

    /// Finds the first item satisfying predicate `f`, or `None` if none match.
    ///
    /// When [`IterationOrder::Ordered`] (default) is set, returns the first matching item in
    /// deterministic breadth-first order (level by level, left-to-right following input and child
    /// generation order).
    ///
    /// Setting [`IterationOrder::Arbitrary`] may provide speed improvements when ordering is not
    /// important; however, ordered traversal is also optimized so the performance difference
    /// is generally small.
    ///
    /// This is equivalent to `self.filter(f).first()`.
    ///
    /// This operation is short-circuiting: once a matching item is found,
    /// remaining work is cancelled.
    ///
    /// [`IterationOrder::Ordered`]: crate::IterationOrder::Ordered
    /// [`IterationOrder::Arbitrary`]: crate::IterationOrder::Arbitrary
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let found = par_recursive([1i32], |&x| (x < 100).then_some(x + 1))
    ///     .find(|x| x % 17 == 0);
    /// assert_eq!(found, Some(17));
    /// ```
    fn find<F>(self, f: F) -> Option<Self::Item>
    where
        Self::Item: Send,
        F: Fn(&Self::Item) -> bool + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        self.filter(f).first()
    }

    /// Folds elements into per-thread accumulators and returns them.
    ///
    /// The output contains one accumulator for each participating worker.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let partials: Vec<usize> = par_recursive([1usize], |&x| (x < 5).then_some(x + 1))
    ///     .num_threads(2)
    ///     .fold(|| 0usize, |acc, x| *acc += x);
    ///
    /// assert!(!partials.is_empty());
    ///
    /// assert_eq!(partials.iter().sum::<usize>(), 15);
    /// ```
    fn fold<B, I, F>(self, init: I, f: F) -> Vec<B>
    where
        B: Send,
        I: Fn() -> B,
        F: Fn(&mut B, Self::Item) + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send;

    /// Executes `f` for each item.
    ///
    /// # Examples
    ///
    /// ```
    /// use core::sync::atomic::{AtomicUsize, Ordering};
    /// use orx_parallel::*;
    ///
    /// let total = AtomicUsize::new(0);
    ///
    /// par_recursive([1usize], |&x| (x < 4).then_some(x + 1))
    ///     .for_each(|x| {
    ///         total.fetch_add(x, Ordering::Relaxed);
    ///     });
    ///
    /// assert_eq!(total.load(Ordering::Relaxed), 10);
    /// ```
    fn for_each<F>(self, f: F)
    where
        F: Fn(Self::Item) + Send + Copy,
        <Self::Input as IntoIterator>::Item: Send,
    {
        let _ = self.map(f).reduce(|_, _| {});
    }

    /// Returns maximum element, or `None` if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let max = par_recursive([1i32], |&x| (x < 4).then_some(x + 1))
    ///     .max();
    /// assert_eq!(max, Some(4));
    ///
    /// let empty = par_recursive(Vec::<usize>::new(), |_: &usize| None::<usize>)
    ///     .max();
    /// assert_eq!(empty, None);
    /// ```
    fn max(self) -> Option<Self::Item>
    where
        Self::Item: Ord + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        self.reduce(Ord::max)
    }

    /// Returns element considered maximum by comparator `f`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = par_recursive(vec![-3_i32, 0, 1, 5, -10], |_: &i32| None::<i32>)
    ///     .max_by(|a, b| a.cmp(b));
    /// assert_eq!(x, Some(5));
    /// ```
    fn max_by<F>(self, f: F) -> Option<Self::Item>
    where
        Self::Item: Send,
        F: Fn(&Self::Item, &Self::Item) -> Ordering + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        let reduce = move |x, y| match f(&x, &y) {
            Ordering::Greater | Ordering::Equal => x,
            Ordering::Less => y,
        };
        self.reduce(reduce)
    }

    /// Returns element with maximum key value.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = par_recursive(vec![-3_i32, 0, 1, 5, -10], |_: &i32| None::<i32>)
    ///     .max_by_key(|x| x.abs());
    /// assert_eq!(x, Some(-10));
    /// ```
    fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
    where
        Self::Item: Send,
        B: Ord,
        F: Fn(&Self::Item) -> B + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        let reduce = move |x, y| match f(&x).cmp(&f(&y)) {
            Ordering::Greater | Ordering::Equal => x,
            Ordering::Less => y,
        };
        self.reduce(reduce)
    }

    /// Returns minimum element, or `None` if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let min = par_recursive([1i32], |&x| (x < 4).then_some(x + 1))
    ///     .min();
    /// assert_eq!(min, Some(1));
    ///
    /// let empty = par_recursive(Vec::<usize>::new(), |_: &usize| None::<usize>)
    ///     .min();
    /// assert_eq!(empty, None);
    /// ```
    fn min(self) -> Option<Self::Item>
    where
        Self::Item: Ord + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        self.reduce(Ord::min)
    }

    /// Returns element considered minimum by comparator `f`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = par_recursive(vec![-3_i32, 0, 1, 5, -10], |_: &i32| None::<i32>)
    ///     .min_by(|a, b| a.cmp(b));
    /// assert_eq!(x, Some(-10));
    /// ```
    fn min_by<F>(self, f: F) -> Option<Self::Item>
    where
        Self::Item: Send,
        F: Fn(&Self::Item, &Self::Item) -> Ordering + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        let reduce = move |x, y| match f(&x, &y) {
            Ordering::Less | Ordering::Equal => x,
            Ordering::Greater => y,
        };
        self.reduce(reduce)
    }

    /// Returns element with minimum key value.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = par_recursive(vec![-3_i32, 0, 1, 5, -10], |_: &i32| None::<i32>)
    ///     .min_by_key(|x| x.abs());
    /// assert_eq!(x, Some(0));
    /// ```
    fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
    where
        Self::Item: Send,
        B: Ord,
        F: Fn(&Self::Item) -> B + Copy + Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        let reduce = move |x, y| match f(&x).cmp(&f(&y)) {
            Ordering::Less | Ordering::Equal => x,
            Ordering::Greater => y,
        };
        self.reduce(reduce)
    }

    /// Sums elements using [`Sum`] implementation of the item type.
    ///
    /// Empty iterators return additive identity (`zero`).
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let sum: usize = par_recursive([1usize], |&x| (x < 4).then_some(x + 1))
    ///     .sum();
    /// assert_eq!(sum, 10);
    /// ```
    fn sum<S>(self) -> S
    where
        Self::Item: Sum<S>,
        S: Send,
        <Self::Input as IntoIterator>::Item: Send,
    {
        self.map(Self::Item::owned)
            .reduce(Self::Item::add)
            .unwrap_or(Self::Item::zero())
    }
}