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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
// TODO: remove this
#![allow(clippy::type_complexity)]

use crate::infallible_use::fun::{UFnCloned, UFnCopied};
use crate::infallible_use::{
    FilMapOf, FilOf, FlatMapOf, FlattenOf, InsOf, MapOf, MappedOf, XapUse,
};
use crate::option_use::ParUseOptionIter;
use crate::option_use::par_core::ParUseOptionCore;
use crate::runner::ParRunner;
use crate::sizes::{OneOne, SizePair};
use crate::{ChunkSize, IterationOrder, NumThreads, ParExtend, Sum};
use core::cmp::Ordering;
use orx_concurrent_iter::ExactSizeConcurrentIter;

/// Fallible parallel iterator with worker-local mutable state.
///
/// `ParUseOption` combines:
/// - fallible processing (`Option`-based short-circuiting), and
/// - mutable worker-local state (`&mut Use` passed to closures).
///
/// You can enter this mode from [`ParOption`](crate::ParOption) via
/// [`use_new`](crate::ParOption::use_new),
/// [`use_vec`](crate::ParOption::use_vec), or
/// [`use_slice`](crate::ParOption::use_slice).
///
/// Similar to using `?`, this trait keeps pipeline logic focused on successful
/// values while the computation short-circuits to `None` when any element
/// evaluates to `None`.
///
/// Related traits:
/// - [`ParOption`](crate::ParOption) for `Option`-fallible pipelines without worker-local state,
/// - [`ParUse`](crate::ParUse) for worker-local state in infallible pipelines.
///
/// # Examples
///
/// Reusing a per-worker buffer:
///
/// ```
/// use core::fmt::Write;
/// use orx_parallel::*;
///
/// let out: Option<Vec<usize>> = (0..16usize)
///     .into_par()
///     .map(Some)
///     .into_optional()
///     .use_new(|_| String::with_capacity(32))
///     .map(|buffer, x| {
///         buffer.clear();
///         write!(buffer, "{x}").unwrap();
///         buffer.parse::<usize>().unwrap()
///     })
///     .collect();
///
/// assert_eq!(out, Some((0..16).collect::<Vec<_>>()));
/// ```
///
/// Using RNG as mutable worker-local state:
///
/// ```
/// use orx_parallel::*;
/// use rand::prelude::*;
/// use rand_chacha::ChaCha8Rng;
///
/// let out: Option<Vec<usize>> = (0..32usize)
///     .into_par()
///     .map(Some)
///     .into_optional()
///     .use_new(|thread_idx| ChaCha8Rng::seed_from_u64(100 + thread_idx as u64))
///     .map(|rng, x| x + rng.random_range(0..10))
///     .collect();
///
/// assert_eq!(out.as_ref().map(Vec::len), Some(32));
/// assert!(out.unwrap().into_iter().enumerate().all(|(i, v)| v >= i));
/// ```
pub trait ParUseOption: Sized + ParUseOptionCore {
    // configuration

    /// Replaces the current parallel runner with `runner`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let par = ["1", "2", "3"]
    ///     .into_par()
    ///     .map(|s| s.parse::<usize>().ok())
    ///     .into_optional()
    ///     .use_new(|_| ());
    ///
    /// let par = par.runner(Runner::fixed());
    ///
    /// let out: Option<Vec<_>> = par.collect();
    /// assert_eq!(out, Some(vec![1, 2, 3]));
    /// ```
    fn runner<Q: ParRunner>(
        self,
        runner: Q,
    ) -> impl ParUseOption<
        Elem = Self::Elem,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = Self::Xap2,
        Input = Self::Input,
        Size = Self::Size,
    >;

    /// Wraps the current runner with diagnostics-enabled execution.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let par = ["1", "2", "3"]
    ///     .into_par()
    ///     .map(|s| s.parse::<usize>().ok())
    ///     .into_optional()
    ///     .use_new(|_| ());
    ///
    /// #[cfg(feature = "std")]
    /// let par = par.runner_with_diagnostics();
    ///
    /// let out: Option<Vec<_>> = par.collect();
    /// assert_eq!(out, Some(vec![1, 2, 3]));
    /// ```
    #[cfg(feature = "std")]
    fn runner_with_diagnostics(
        self,
    ) -> impl ParUseOption<
        Elem = Self::Elem,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = Self::Xap2,
        Input = Self::Input,
        Size = Self::Size,
    >;

    /// Sets the maximum number of worker threads for this computation.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Option<Vec<_>> = (1..6)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .num_threads(1)
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 2, 3, 4, 5]));
    /// ```
    fn num_threads(self, num_threads: impl Into<NumThreads>) -> Self;

    /// Sets chunk size used when pulling items from the concurrent input.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Option<Vec<_>> = (0..8)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .chunk_size(2)
    ///     .collect();
    ///
    /// assert_eq!(out, Some((0..8).collect::<Vec<_>>()));
    /// ```
    fn chunk_size(self, chunk_size: impl Into<ChunkSize>) -> Self;

    /// Sets iteration-order semantics for order-sensitive operations.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let ordered = (1..10_000)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .iteration_order(IterationOrder::Ordered)
    ///     .find(|_, x| x % 3421 == 0);
    /// assert_eq!(ordered, Some(Some(3421)));
    /// ```
    fn iteration_order(self, iteration_order: IterationOrder) -> Self;

    // kind transformations

    /// Copies elements of a reference iterator on the success path.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let data = vec![1, 2, 3];
    /// let out: Option<Vec<_>> = data
    ///     .par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .copied()
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 2, 3]));
    /// ```
    fn copied<'a, O>(
        self,
    ) -> impl ParUseOption<
        Elem = O,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = MappedOf<Self::Xap2, UFnCopied<'a, Self::Use, O>>,
        Input = Self::Input,
        Size = Self::Size,
    >
    where
        Self: ParUseOption<Elem = &'a O>,
        O: Copy + 'a,
        Self::Use: 'a,
    {
        let (u, iter, x1, x2, exe, _, params) = self.destruct();
        ParUseOptionIter::new(u, iter, x1, x2.mapped(UFnCopied::new()), exe, params)
    }

    /// Clones elements of a reference iterator on the success path.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let data = vec!["a".to_string(), "b".to_string()];
    /// let out: Option<Vec<_>> = data
    ///     .par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .cloned()
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec!["a".to_string(), "b".to_string()]));
    /// ```
    fn cloned<'a, O>(
        self,
    ) -> impl ParUseOption<
        Elem = O,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = MappedOf<Self::Xap2, UFnCloned<'a, Self::Use, O>>,
        Input = Self::Input,
        Size = Self::Size,
    >
    where
        Self: ParUseOption<Elem = &'a O>,
        O: Clone + 'a,
        Self::Use: 'a,
    {
        let (u, iter, x1, x2, exe, _, params) = self.destruct();
        ParUseOptionIter::new(u, iter, x1, x2.mapped(UFnCloned::new()), exe, params)
    }

    // transformations

    /// Maps each successful element with closure `h`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Option<Vec<_>> = (1..4)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .map(|_, x| 2 * x)
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![2, 4, 6]));
    /// ```
    fn map<Q, H>(
        self,
        h: H,
    ) -> impl ParUseOption<
        Elem = Q,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = MapOf<Self::Xap2, Q, H>,
        Input = Self::Input,
        Size = Self::Size,
    >
    where
        H: Fn(&mut Self::Use, Self::Elem) -> Q + Copy + Send;

    /// Runs `h` on each successful element and forwards the item unchanged.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let mut use_vec = UseVec::new(|_| 0usize);
    /// let out: Option<Vec<_>> = (1..5)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_vec(&mut use_vec)
    ///     .inspect(|count, _| *count += 1)
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 2, 3, 4]));
    /// assert_eq!(use_vec.into_vec().into_iter().sum::<usize>(), 4);
    /// ```
    fn inspect<H>(
        self,
        h: H,
    ) -> impl ParUseOption<
        Elem = Self::Elem,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = InsOf<Self::Xap2, H>,
        Input = Self::Input,
        Size = Self::Size,
    >
    where
        H: Fn(&mut Self::Use, &Self::Elem) + Copy + Send;

    /// Keeps successful elements satisfying predicate `h`.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Option<Vec<_>> = (1..7)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .filter(|_, x| x % 2 == 1)
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 3, 5]));
    /// ```
    fn filter<H>(
        self,
        h: H,
    ) -> impl ParUseOption<
        Elem = Self::Elem,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = FilOf<Self::Xap2, H>,
        Input = Self::Input,
        Size = <Self::Size as SizePair>::ThenBin,
    >
    where
        H: Fn(&mut Self::Use, &Self::Elem) -> bool + Copy + Send;

    /// Maps and filters successful elements in one pass.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Option<Vec<_>> = ["1", "x", "5"]
    ///     .into_par()
    ///     .map(|s| Some(s))
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .filter_map(|_, s| s.parse::<usize>().ok())
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 5]));
    /// ```
    fn filter_map<Q, H>(
        self,
        h: H,
    ) -> impl ParUseOption<
        Elem = Q,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = FilMapOf<Self::Xap2, Q, H>,
        Input = Self::Input,
        Size = <Self::Size as SizePair>::ThenBin,
    >
    where
        H: Fn(&mut Self::Use, Self::Elem) -> Option<Q> + Copy + Send;

    /// Maps each successful element to an iterator and flattens one level.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Option<Vec<_>> = (1..4)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .flat_map(|_, x| [x, x + 10])
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 11, 2, 12, 3, 13]));
    /// ```
    fn flat_map<V, H>(
        self,
        h: H,
    ) -> impl ParUseOption<
        Elem = V::Item,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = FlatMapOf<Self::Xap2, V, H>,
        Input = Self::Input,
        Size = <Self::Size as SizePair>::ThenMany,
    >
    where
        V: IntoIterator,
        H: Fn(&mut Self::Use, Self::Elem) -> V + Copy + Send;

    /// Flattens one level of nested iterables on the success path.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let nested = vec![vec![1, 2], vec![3, 4]];
    /// let out: Option<Vec<_>> = nested
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .flatten()
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 2, 3, 4]));
    /// ```
    fn flatten(
        self,
    ) -> impl ParUseOption<
        Elem = <Self::Elem as IntoIterator>::Item,
        Use = Self::Use,
        Xap1 = Self::Xap1,
        M = Self::M,
        Xap2 = FlattenOf<Self::Xap2>,
        Input = Self::Input,
        Size = <Self::Size as SizePair>::ThenMany,
    >
    where
        Self::Elem: IntoIterator;

    /// Returns a lower and optional upper bound on the number of successful output items.
    ///
    /// The bounds follow the usual [`Iterator::size_hint`] convention.
    /// The upper bound includes items that may be removed by filtering or short-circuiting.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let values = (0..4)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .filter(|_, x| x % 2 == 0);
    ///
    /// assert_eq!(values.size_hint(), (0, Some(4)));
    /// ```
    fn size_hint(&self) -> (usize, Option<usize>);

    /// Returns the exact number of output items.
    fn len(&self) -> usize
    where
        Self::Input: ExactSizeConcurrentIter,
        Self: ParUseOption<Size = OneOne>,
    {
        self.size_hint().0
    }

    /// Returns `true` when the parallel iterator has no output items.
    fn is_empty(&self) -> bool
    where
        Self::Input: ExactSizeConcurrentIter,
        Self: ParUseOption<Size = OneOne>,
    {
        self.len() == 0
    }

    // compute

    /// Returns the first successful item according to iteration order.
    ///
    /// Returns:
    /// - `None` if computation short-circuits due to a failure
    /// - `Some(None)` if no successful element exists
    /// - `Some(Some(x))` for the first successful element
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let ok = (1..4)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .first();
    /// assert_eq!(ok, Some(Some(1)));
    ///
    /// let fail = vec![None, Some(1), Some(3)]
    ///     .into_par()
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .first();
    /// assert_eq!(fail, None);
    /// ```
    fn first(self) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Send;

    /// Reduces successful items into one value using `f`.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let ok = (1..6)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .reduce(|_, a, b| a + b);
    /// assert_eq!(ok, Some(Some(15)));
    ///
    /// let fail = vec![Some(1), None, Some(3)]
    ///     .into_par()
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .reduce(|_, a, b| a + b);
    /// assert_eq!(fail, None);
    /// ```
    fn reduce<F>(self, f: F) -> Option<Option<Self::Elem>>
    where
        F: Fn(&mut Self::Use, Self::Elem, Self::Elem) -> Self::Elem + Send + Copy,
        Self::Elem: Send;

    /// Collects successful items into `dst`.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let mut dst = vec![10usize];
    /// let ok = (0..3)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .collect_into(&mut dst);
    /// assert_eq!(ok, Some(()));
    /// assert_eq!(dst, vec![10, 0, 1, 2]);
    /// ```
    fn collect_into<P>(self, dst: &mut P) -> Option<()>
    where
        P: ParExtend<Self::Elem>,
        Self::Elem: Send;

    /// Collects successful items into a new collection.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let out: Option<Vec<_>> = (1..4)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .collect();
    ///
    /// assert_eq!(out, Some(vec![1, 2, 3]));
    /// ```
    fn collect<P>(self) -> Option<P>
    where
        P: ParExtend<Self::Elem> + Default,
        Self::Elem: Send,
    {
        let mut dst = P::default();
        self.collect_into(&mut dst)?;
        Some(dst)
    }

    // compute - derived

    /// Returns `Some(true)` if all successful items satisfy `f`.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let ok = (1..5)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .all(|_, x| x > &0);
    /// assert_eq!(ok, Some(true));
    ///
    /// let fail = vec![Some(1), None, Some(3)]
    ///     .into_par()
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .all(|_, x| x > &0);
    /// assert_eq!(fail, None);
    /// ```
    fn all<F>(self, f: F) -> Option<bool>
    where
        Self::Elem: Send,
        F: Fn(&mut Self::Use, &Self::Elem) -> bool + Sync,
    {
        self.map(|u, x| f(u, &x))
            .find(|_, x| !*x)
            .map(|x| x.is_none())
    }

    /// Returns `Some(true)` if any successful item satisfies `f`.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let ok = (1..5)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .any(|_, x| x % 2 == 0);
    /// assert_eq!(ok, Some(true));
    ///
    /// let fail = vec![Some(1), None, Some(3)]
    ///     .into_par()
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .any(|_, x| x % 2 == 0);
    /// assert_eq!(fail, None);
    /// ```
    fn any<F>(self, f: F) -> Option<bool>
    where
        Self::Elem: Send,
        F: Fn(&mut Self::Use, &Self::Elem) -> bool + Sync,
    {
        self.map(|u, x| f(u, &x))
            .find(|_, x| *x)
            .map(|x| x.is_some())
    }

    /// Counts successful elements.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let ok = (1..11)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .filter(|_, x| x % 3 == 0)
    ///     .count();
    /// assert_eq!(ok, Some(3));
    /// ```
    fn count(self) -> Option<usize> {
        self.map(|_, _| 1)
            .reduce(|_, a, b| a + b)
            .map(|x| x.unwrap_or(0))
    }

    /// Finds first (ordered) or any (arbitrary) successful item satisfying `f`.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let found = (1..101)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .find(|_, x| x % 17 == 0);
    /// assert_eq!(found, Some(Some(17)));
    /// ```
    fn find<F>(self, f: F) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Send,
        F: Fn(&mut Self::Use, &Self::Elem) -> bool + Sync,
    {
        self.filter(&f).first()
    }

    /// Executes `f` for each successful element.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let mut sums = UseVec::new(|_| 0usize);
    ///
    /// let result = (1..5)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_vec(&mut sums)
    ///     .for_each(|local, x| *local += x);
    ///
    /// assert_eq!(result, Some(()));
    /// assert_eq!(sums.into_vec().into_iter().sum::<usize>(), 10);
    /// ```
    fn for_each<F>(self, f: F) -> Option<()>
    where
        F: Fn(&mut Self::Use, Self::Elem) + Send + Copy,
    {
        self.map(f).reduce(|_, _, _| {}).map(|_| ())
    }

    /// Returns maximum successful element.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let m = (1..5)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .max();
    /// assert_eq!(m, Some(Some(4)));
    /// ```
    fn max(self) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Ord + Send,
    {
        self.reduce(|_, a, b| Ord::max(a, b))
    }

    /// Returns successful element considered maximum by comparator `f`.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = vec![-3_i32, 0, 1, 5, -10]
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .max_by(|_, a, b| a.cmp(b));
    /// assert_eq!(x, Some(Some(5)));
    /// ```
    fn max_by<F>(self, f: F) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Send,
        F: Fn(&mut Self::Use, &Self::Elem, &Self::Elem) -> Ordering + Sync,
    {
        let reduce = |u: &mut Self::Use, x, y| match f(u, &x, &y) {
            Ordering::Greater | Ordering::Equal => x,
            Ordering::Less => y,
        };
        self.reduce(reduce)
    }

    /// Returns successful element with maximum key value.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = vec![-3_i32, 0, 1, 5, -10]
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .max_by_key(|_, x| x.abs());
    /// assert_eq!(x, Some(Some(-10)));
    /// ```
    fn max_by_key<B, F>(self, f: F) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Send,
        B: Ord,
        F: Fn(&mut Self::Use, &Self::Elem) -> B + Sync,
    {
        let reduce = |u: &mut Self::Use, x, y| match f(u, &x).cmp(&f(u, &y)) {
            Ordering::Greater | Ordering::Equal => x,
            Ordering::Less => y,
        };
        self.reduce(reduce)
    }

    /// Returns minimum successful element.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let m = (1..5)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .min();
    /// assert_eq!(m, Some(Some(1)));
    /// ```
    fn min(self) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Ord + Send,
    {
        self.reduce(|_, a, b| Ord::min(a, b))
    }

    /// Returns successful element considered minimum by comparator `f`.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = vec![-3_i32, 0, 1, 5, -10]
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .min_by(|_, a, b| a.cmp(b));
    /// assert_eq!(x, Some(Some(-10)));
    /// ```
    fn min_by<F>(self, f: F) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Send,
        F: Fn(&mut Self::Use, &Self::Elem, &Self::Elem) -> Ordering + Sync,
    {
        let reduce = |u: &mut Self::Use, x, y| match f(u, &x, &y) {
            Ordering::Less | Ordering::Equal => x,
            Ordering::Greater => y,
        };
        self.reduce(reduce)
    }

    /// Returns successful element with minimum key value.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let x = vec![-3_i32, 0, 1, 5, -10]
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .min_by_key(|_, x| x.abs());
    /// assert_eq!(x, Some(Some(0)));
    /// ```
    fn min_by_key<B, F>(self, f: F) -> Option<Option<Self::Elem>>
    where
        Self::Elem: Send,
        B: Ord,
        F: Fn(&mut Self::Use, &Self::Elem) -> B + Sync,
    {
        let reduce = |u: &mut Self::Use, x, y| match f(u, &x).cmp(&f(u, &y)) {
            Ordering::Less | Ordering::Equal => x,
            Ordering::Greater => y,
        };
        self.reduce(reduce)
    }

    /// Sums successful elements using [`Sum`] implementation.
    ///
    /// Returns `None` on short-circuit failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_parallel::*;
    ///
    /// let s: Option<usize> = (1..5)
    ///     .into_par()
    ///     .map(Some)
    ///     .into_optional()
    ///     .use_new(|_| ())
    ///     .sum();
    /// assert_eq!(s, Some(10));
    /// ```
    fn sum<S>(self) -> Option<S>
    where
        Self::Elem: Sum<S>,
        S: Send,
    {
        self.map(|_, x| Self::Elem::owned(x))
            .reduce(|_, a, b| Self::Elem::add(a, b))
            .map(|x| x.unwrap_or(Self::Elem::zero()))
    }
}