-
Notifications
You must be signed in to change notification settings - Fork 501
/
mod.rs
3661 lines (3485 loc) · 120 KB
/
mod.rs
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Traits for writing parallel programs using an iterator-style interface
//!
//! You will rarely need to interact with this module directly unless you have
//! need to name one of the iterator types.
//!
//! Parallel iterators make it easy to write iterator-like chains that
//! execute in parallel: typically all you have to do is convert the
//! first `.iter()` (or `iter_mut()`, `into_iter()`, etc) method into
//! `par_iter()` (or `par_iter_mut()`, `into_par_iter()`, etc). For
//! example, to compute the sum of the squares of a sequence of
//! integers, one might write:
//!
//! ```rust
//! use rayon::prelude::*;
//! fn sum_of_squares(input: &[i32]) -> i32 {
//! input.par_iter()
//! .map(|i| i * i)
//! .sum()
//! }
//! ```
//!
//! Or, to increment all the integers in a slice, you could write:
//!
//! ```rust
//! use rayon::prelude::*;
//! fn increment_all(input: &mut [i32]) {
//! input.par_iter_mut()
//! .for_each(|p| *p += 1);
//! }
//! ```
//!
//! To use parallel iterators, first import the traits by adding
//! something like `use rayon::prelude::*` to your module. You can
//! then call `par_iter`, `par_iter_mut`, or `into_par_iter` to get a
//! parallel iterator. Like a [regular iterator][], parallel
//! iterators work by first constructing a computation and then
//! executing it.
//!
//! In addition to `par_iter()` and friends, some types offer other
//! ways to create (or consume) parallel iterators:
//!
//! - Slices (`&[T]`, `&mut [T]`) offer methods like `par_split` and
//! `par_windows`, as well as various parallel sorting
//! operations. See [the `ParallelSlice` trait] for the full list.
//! - Strings (`&str`) offer methods like `par_split` and `par_lines`.
//! See [the `ParallelString` trait] for the full list.
//! - Various collections offer [`par_extend`], which grows a
//! collection given a parallel iterator. (If you don't have a
//! collection to extend, you can use [`collect()`] to create a new
//! one from scratch.)
//!
//! [the `ParallelSlice` trait]: ../slice/trait.ParallelSlice.html
//! [the `ParallelString` trait]: ../str/trait.ParallelString.html
//! [`par_extend`]: trait.ParallelExtend.html
//! [`collect()`]: trait.ParallelIterator.html#method.collect
//!
//! To see the full range of methods available on parallel iterators,
//! check out the [`ParallelIterator`] and [`IndexedParallelIterator`]
//! traits.
//!
//! If you'd like to build a custom parallel iterator, or to write your own
//! combinator, then check out the [split] function and the [plumbing] module.
//!
//! [regular iterator]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
//! [`ParallelIterator`]: trait.ParallelIterator.html
//! [`IndexedParallelIterator`]: trait.IndexedParallelIterator.html
//! [split]: fn.split.html
//! [plumbing]: plumbing/index.html
//!
//! Note: Several of the `ParallelIterator` methods rely on a `Try` trait which
//! has been deliberately obscured from the public API. This trait is intended
//! to mirror the unstable `std::ops::Try` with implementations for `Option` and
//! `Result`, where `Some`/`Ok` values will let those iterators continue, but
//! `None`/`Err` values will exit early.
//!
//! A note about object safety: It is currently _not_ possible to wrap
//! a `ParallelIterator` (or any trait that depends on it) using a
//! `Box<dyn ParallelIterator>` or other kind of dynamic allocation,
//! because `ParallelIterator` is **not object-safe**.
//! (This keeps the implementation simpler and allows extra optimizations.)
use self::plumbing::*;
use self::private::Try;
pub use either::Either;
use std::cmp::Ordering;
use std::collections::LinkedList;
use std::iter::{Product, Sum};
use std::ops::{Fn, RangeBounds};
pub mod plumbing;
#[cfg(test)]
mod test;
// There is a method to the madness here:
//
// - These modules are private but expose certain types to the end-user
// (e.g., `enumerate::Enumerate`) -- specifically, the types that appear in the
// public API surface of the `ParallelIterator` traits.
// - In **this** module, those public types are always used unprefixed, which forces
// us to add a `pub use` and helps identify if we missed anything.
// - In contrast, items that appear **only** in the body of a method,
// e.g. `find::find()`, are always used **prefixed**, so that they
// can be readily distinguished.
mod blocks;
mod chain;
mod chunks;
mod cloned;
mod collect;
mod copied;
mod empty;
mod enumerate;
mod extend;
mod filter;
mod filter_map;
mod find;
mod find_first_last;
mod flat_map;
mod flat_map_iter;
mod flatten;
mod flatten_iter;
mod fold;
mod fold_chunks;
mod fold_chunks_with;
mod for_each;
mod from_par_iter;
mod inspect;
mod interleave;
mod interleave_shortest;
mod intersperse;
mod len;
mod map;
mod map_with;
mod multizip;
mod noop;
mod once;
mod panic_fuse;
mod par_bridge;
mod positions;
mod product;
mod reduce;
mod repeat;
mod rev;
mod skip;
mod skip_any;
mod skip_any_while;
mod splitter;
mod step_by;
mod sum;
mod take;
mod take_any;
mod take_any_while;
mod try_fold;
mod try_reduce;
mod try_reduce_with;
mod unzip;
mod update;
mod walk_tree;
mod while_some;
mod zip;
mod zip_eq;
pub use self::{
blocks::{ExponentialBlocks, UniformBlocks},
chain::Chain,
chunks::Chunks,
cloned::Cloned,
copied::Copied,
empty::{empty, Empty},
enumerate::Enumerate,
filter::Filter,
filter_map::FilterMap,
flat_map::FlatMap,
flat_map_iter::FlatMapIter,
flatten::Flatten,
flatten_iter::FlattenIter,
fold::{Fold, FoldWith},
fold_chunks::FoldChunks,
fold_chunks_with::FoldChunksWith,
inspect::Inspect,
interleave::Interleave,
interleave_shortest::InterleaveShortest,
intersperse::Intersperse,
len::{MaxLen, MinLen},
map::Map,
map_with::{MapInit, MapWith},
multizip::MultiZip,
once::{once, Once},
panic_fuse::PanicFuse,
par_bridge::{IterBridge, ParallelBridge},
positions::Positions,
repeat::{repeat, repeatn, Repeat, RepeatN},
rev::Rev,
skip::Skip,
skip_any::SkipAny,
skip_any_while::SkipAnyWhile,
splitter::{split, Split},
step_by::StepBy,
take::Take,
take_any::TakeAny,
take_any_while::TakeAnyWhile,
try_fold::{TryFold, TryFoldWith},
update::Update,
walk_tree::{
walk_tree, walk_tree_postfix, walk_tree_prefix, WalkTree, WalkTreePostfix, WalkTreePrefix,
},
while_some::WhileSome,
zip::Zip,
zip_eq::ZipEq,
};
/// `IntoParallelIterator` implements the conversion to a [`ParallelIterator`].
///
/// By implementing `IntoParallelIterator` for a type, you define how it will
/// transformed into an iterator. This is a parallel version of the standard
/// library's [`std::iter::IntoIterator`] trait.
///
/// [`ParallelIterator`]: trait.ParallelIterator.html
/// [`std::iter::IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html
pub trait IntoParallelIterator {
/// The parallel iterator type that will be created.
type Iter: ParallelIterator<Item = Self::Item>;
/// The type of item that the parallel iterator will produce.
type Item: Send;
/// Converts `self` into a parallel iterator.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// println!("counting in parallel:");
/// (0..100).into_par_iter()
/// .for_each(|i| println!("{}", i));
/// ```
///
/// This conversion is often implicit for arguments to methods like [`zip`].
///
/// ```
/// use rayon::prelude::*;
///
/// let v: Vec<_> = (0..5).into_par_iter().zip(5..10).collect();
/// assert_eq!(v, [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]);
/// ```
///
/// [`zip`]: trait.IndexedParallelIterator.html#method.zip
fn into_par_iter(self) -> Self::Iter;
}
/// `IntoParallelRefIterator` implements the conversion to a
/// [`ParallelIterator`], providing shared references to the data.
///
/// This is a parallel version of the `iter()` method
/// defined by various collections.
///
/// This trait is automatically implemented
/// `for I where &I: IntoParallelIterator`. In most cases, users
/// will want to implement [`IntoParallelIterator`] rather than implement
/// this trait directly.
///
/// [`ParallelIterator`]: trait.ParallelIterator.html
/// [`IntoParallelIterator`]: trait.IntoParallelIterator.html
pub trait IntoParallelRefIterator<'data> {
/// The type of the parallel iterator that will be returned.
type Iter: ParallelIterator<Item = Self::Item>;
/// The type of item that the parallel iterator will produce.
/// This will typically be an `&'data T` reference type.
type Item: Send + 'data;
/// Converts `self` into a parallel iterator.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let v: Vec<_> = (0..100).collect();
/// assert_eq!(v.par_iter().sum::<i32>(), 100 * 99 / 2);
///
/// // `v.par_iter()` is shorthand for `(&v).into_par_iter()`,
/// // producing the exact same references.
/// assert!(v.par_iter().zip(&v)
/// .all(|(a, b)| std::ptr::eq(a, b)));
/// ```
fn par_iter(&'data self) -> Self::Iter;
}
impl<'data, I: 'data + ?Sized> IntoParallelRefIterator<'data> for I
where
&'data I: IntoParallelIterator,
{
type Iter = <&'data I as IntoParallelIterator>::Iter;
type Item = <&'data I as IntoParallelIterator>::Item;
fn par_iter(&'data self) -> Self::Iter {
self.into_par_iter()
}
}
/// `IntoParallelRefMutIterator` implements the conversion to a
/// [`ParallelIterator`], providing mutable references to the data.
///
/// This is a parallel version of the `iter_mut()` method
/// defined by various collections.
///
/// This trait is automatically implemented
/// `for I where &mut I: IntoParallelIterator`. In most cases, users
/// will want to implement [`IntoParallelIterator`] rather than implement
/// this trait directly.
///
/// [`ParallelIterator`]: trait.ParallelIterator.html
/// [`IntoParallelIterator`]: trait.IntoParallelIterator.html
pub trait IntoParallelRefMutIterator<'data> {
/// The type of iterator that will be created.
type Iter: ParallelIterator<Item = Self::Item>;
/// The type of item that will be produced; this is typically an
/// `&'data mut T` reference.
type Item: Send + 'data;
/// Creates the parallel iterator from `self`.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let mut v = vec![0usize; 5];
/// v.par_iter_mut().enumerate().for_each(|(i, x)| *x = i);
/// assert_eq!(v, [0, 1, 2, 3, 4]);
/// ```
fn par_iter_mut(&'data mut self) -> Self::Iter;
}
impl<'data, I: 'data + ?Sized> IntoParallelRefMutIterator<'data> for I
where
&'data mut I: IntoParallelIterator,
{
type Iter = <&'data mut I as IntoParallelIterator>::Iter;
type Item = <&'data mut I as IntoParallelIterator>::Item;
fn par_iter_mut(&'data mut self) -> Self::Iter {
self.into_par_iter()
}
}
/// Parallel version of the standard iterator trait.
///
/// The combinators on this trait are available on **all** parallel
/// iterators. Additional methods can be found on the
/// [`IndexedParallelIterator`] trait: those methods are only
/// available for parallel iterators where the number of items is
/// known in advance (so, e.g., after invoking `filter`, those methods
/// become unavailable).
///
/// For examples of using parallel iterators, see [the docs on the
/// `iter` module][iter].
///
/// [iter]: index.html
/// [`IndexedParallelIterator`]: trait.IndexedParallelIterator.html
pub trait ParallelIterator: Sized + Send {
/// The type of item that this parallel iterator produces.
/// For example, if you use the [`for_each`] method, this is the type of
/// item that your closure will be invoked with.
///
/// [`for_each`]: #method.for_each
type Item: Send;
/// Executes `OP` on each item produced by the iterator, in parallel.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// (0..100).into_par_iter().for_each(|x| println!("{:?}", x));
/// ```
fn for_each<OP>(self, op: OP)
where
OP: Fn(Self::Item) + Sync + Send,
{
for_each::for_each(self, &op)
}
/// Executes `OP` on the given `init` value with each item produced by
/// the iterator, in parallel.
///
/// The `init` value will be cloned only as needed to be paired with
/// the group of items in each rayon job. It does not require the type
/// to be `Sync`.
///
/// # Examples
///
/// ```
/// use std::sync::mpsc::channel;
/// use rayon::prelude::*;
///
/// let (sender, receiver) = channel();
///
/// (0..5).into_par_iter().for_each_with(sender, |s, x| s.send(x).unwrap());
///
/// let mut res: Vec<_> = receiver.iter().collect();
///
/// res.sort();
///
/// assert_eq!(&res[..], &[0, 1, 2, 3, 4])
/// ```
fn for_each_with<OP, T>(self, init: T, op: OP)
where
OP: Fn(&mut T, Self::Item) + Sync + Send,
T: Send + Clone,
{
self.map_with(init, op).collect()
}
/// Executes `OP` on a value returned by `init` with each item produced by
/// the iterator, in parallel.
///
/// The `init` function will be called only as needed for a value to be
/// paired with the group of items in each rayon job. There is no
/// constraint on that returned type at all!
///
/// # Examples
///
/// ```
/// use rand::Rng;
/// use rayon::prelude::*;
///
/// let mut v = vec![0u8; 1_000_000];
///
/// v.par_chunks_mut(1000)
/// .for_each_init(
/// || rand::thread_rng(),
/// |rng, chunk| rng.fill(chunk),
/// );
///
/// // There's a remote chance that this will fail...
/// for i in 0u8..=255 {
/// assert!(v.contains(&i));
/// }
/// ```
fn for_each_init<OP, INIT, T>(self, init: INIT, op: OP)
where
OP: Fn(&mut T, Self::Item) + Sync + Send,
INIT: Fn() -> T + Sync + Send,
{
self.map_init(init, op).collect()
}
/// Executes a fallible `OP` on each item produced by the iterator, in parallel.
///
/// If the `OP` returns `Result::Err` or `Option::None`, we will attempt to
/// stop processing the rest of the items in the iterator as soon as
/// possible, and we will return that terminating value. Otherwise, we will
/// return an empty `Result::Ok(())` or `Option::Some(())`. If there are
/// multiple errors in parallel, it is not specified which will be returned.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
/// use std::io::{self, Write};
///
/// // This will stop iteration early if there's any write error, like
/// // having piped output get closed on the other end.
/// (0..100).into_par_iter()
/// .try_for_each(|x| writeln!(io::stdout(), "{:?}", x))
/// .expect("expected no write errors");
/// ```
fn try_for_each<OP, R>(self, op: OP) -> R
where
OP: Fn(Self::Item) -> R + Sync + Send,
R: Try<Output = ()> + Send,
{
fn ok<R: Try<Output = ()>>(_: (), _: ()) -> R {
R::from_output(())
}
self.map(op).try_reduce(<()>::default, ok)
}
/// Executes a fallible `OP` on the given `init` value with each item
/// produced by the iterator, in parallel.
///
/// This combines the `init` semantics of [`for_each_with()`] and the
/// failure semantics of [`try_for_each()`].
///
/// [`for_each_with()`]: #method.for_each_with
/// [`try_for_each()`]: #method.try_for_each
///
/// # Examples
///
/// ```
/// use std::sync::mpsc::channel;
/// use rayon::prelude::*;
///
/// let (sender, receiver) = channel();
///
/// (0..5).into_par_iter()
/// .try_for_each_with(sender, |s, x| s.send(x))
/// .expect("expected no send errors");
///
/// let mut res: Vec<_> = receiver.iter().collect();
///
/// res.sort();
///
/// assert_eq!(&res[..], &[0, 1, 2, 3, 4])
/// ```
fn try_for_each_with<OP, T, R>(self, init: T, op: OP) -> R
where
OP: Fn(&mut T, Self::Item) -> R + Sync + Send,
T: Send + Clone,
R: Try<Output = ()> + Send,
{
fn ok<R: Try<Output = ()>>(_: (), _: ()) -> R {
R::from_output(())
}
self.map_with(init, op).try_reduce(<()>::default, ok)
}
/// Executes a fallible `OP` on a value returned by `init` with each item
/// produced by the iterator, in parallel.
///
/// This combines the `init` semantics of [`for_each_init()`] and the
/// failure semantics of [`try_for_each()`].
///
/// [`for_each_init()`]: #method.for_each_init
/// [`try_for_each()`]: #method.try_for_each
///
/// # Examples
///
/// ```
/// use rand::Rng;
/// use rayon::prelude::*;
///
/// let mut v = vec![0u8; 1_000_000];
///
/// v.par_chunks_mut(1000)
/// .try_for_each_init(
/// || rand::thread_rng(),
/// |rng, chunk| rng.try_fill(chunk),
/// )
/// .expect("expected no rand errors");
///
/// // There's a remote chance that this will fail...
/// for i in 0u8..=255 {
/// assert!(v.contains(&i));
/// }
/// ```
fn try_for_each_init<OP, INIT, T, R>(self, init: INIT, op: OP) -> R
where
OP: Fn(&mut T, Self::Item) -> R + Sync + Send,
INIT: Fn() -> T + Sync + Send,
R: Try<Output = ()> + Send,
{
fn ok<R: Try<Output = ()>>(_: (), _: ()) -> R {
R::from_output(())
}
self.map_init(init, op).try_reduce(<()>::default, ok)
}
/// Counts the number of items in this parallel iterator.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let count = (0..100).into_par_iter().count();
///
/// assert_eq!(count, 100);
/// ```
fn count(self) -> usize {
fn one<T>(_: T) -> usize {
1
}
self.map(one).sum()
}
/// Applies `map_op` to each item of this iterator, producing a new
/// iterator with the results.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let mut par_iter = (0..5).into_par_iter().map(|x| x * 2);
///
/// let doubles: Vec<_> = par_iter.collect();
///
/// assert_eq!(&doubles[..], &[0, 2, 4, 6, 8]);
/// ```
fn map<F, R>(self, map_op: F) -> Map<Self, F>
where
F: Fn(Self::Item) -> R + Sync + Send,
R: Send,
{
Map::new(self, map_op)
}
/// Applies `map_op` to the given `init` value with each item of this
/// iterator, producing a new iterator with the results.
///
/// The `init` value will be cloned only as needed to be paired with
/// the group of items in each rayon job. It does not require the type
/// to be `Sync`.
///
/// # Examples
///
/// ```
/// use std::sync::mpsc::channel;
/// use rayon::prelude::*;
///
/// let (sender, receiver) = channel();
///
/// let a: Vec<_> = (0..5)
/// .into_par_iter() // iterating over i32
/// .map_with(sender, |s, x| {
/// s.send(x).unwrap(); // sending i32 values through the channel
/// x // returning i32
/// })
/// .collect(); // collecting the returned values into a vector
///
/// let mut b: Vec<_> = receiver.iter() // iterating over the values in the channel
/// .collect(); // and collecting them
/// b.sort();
///
/// assert_eq!(a, b);
/// ```
fn map_with<F, T, R>(self, init: T, map_op: F) -> MapWith<Self, T, F>
where
F: Fn(&mut T, Self::Item) -> R + Sync + Send,
T: Send + Clone,
R: Send,
{
MapWith::new(self, init, map_op)
}
/// Applies `map_op` to a value returned by `init` with each item of this
/// iterator, producing a new iterator with the results.
///
/// The `init` function will be called only as needed for a value to be
/// paired with the group of items in each rayon job. There is no
/// constraint on that returned type at all!
///
/// # Examples
///
/// ```
/// use rand::Rng;
/// use rayon::prelude::*;
///
/// let a: Vec<_> = (1i32..1_000_000)
/// .into_par_iter()
/// .map_init(
/// || rand::thread_rng(), // get the thread-local RNG
/// |rng, x| if rng.gen() { // randomly negate items
/// -x
/// } else {
/// x
/// },
/// ).collect();
///
/// // There's a remote chance that this will fail...
/// assert!(a.iter().any(|&x| x < 0));
/// assert!(a.iter().any(|&x| x > 0));
/// ```
fn map_init<F, INIT, T, R>(self, init: INIT, map_op: F) -> MapInit<Self, INIT, F>
where
F: Fn(&mut T, Self::Item) -> R + Sync + Send,
INIT: Fn() -> T + Sync + Send,
R: Send,
{
MapInit::new(self, init, map_op)
}
/// Creates an iterator which clones all of its elements. This may be
/// useful when you have an iterator over `&T`, but you need `T`, and
/// that type implements `Clone`. See also [`copied()`].
///
/// [`copied()`]: #method.copied
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let a = [1, 2, 3];
///
/// let v_cloned: Vec<_> = a.par_iter().cloned().collect();
///
/// // cloned is the same as .map(|&x| x), for integers
/// let v_map: Vec<_> = a.par_iter().map(|&x| x).collect();
///
/// assert_eq!(v_cloned, vec![1, 2, 3]);
/// assert_eq!(v_map, vec![1, 2, 3]);
/// ```
fn cloned<'a, T>(self) -> Cloned<Self>
where
T: 'a + Clone + Send,
Self: ParallelIterator<Item = &'a T>,
{
Cloned::new(self)
}
/// Creates an iterator which copies all of its elements. This may be
/// useful when you have an iterator over `&T`, but you need `T`, and
/// that type implements `Copy`. See also [`cloned()`].
///
/// [`cloned()`]: #method.cloned
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let a = [1, 2, 3];
///
/// let v_copied: Vec<_> = a.par_iter().copied().collect();
///
/// // copied is the same as .map(|&x| x), for integers
/// let v_map: Vec<_> = a.par_iter().map(|&x| x).collect();
///
/// assert_eq!(v_copied, vec![1, 2, 3]);
/// assert_eq!(v_map, vec![1, 2, 3]);
/// ```
fn copied<'a, T>(self) -> Copied<Self>
where
T: 'a + Copy + Send,
Self: ParallelIterator<Item = &'a T>,
{
Copied::new(self)
}
/// Applies `inspect_op` to a reference to each item of this iterator,
/// producing a new iterator passing through the original items. This is
/// often useful for debugging to see what's happening in iterator stages.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let a = [1, 4, 2, 3];
///
/// // this iterator sequence is complex.
/// let sum = a.par_iter()
/// .cloned()
/// .filter(|&x| x % 2 == 0)
/// .reduce(|| 0, |sum, i| sum + i);
///
/// println!("{}", sum);
///
/// // let's add some inspect() calls to investigate what's happening
/// let sum = a.par_iter()
/// .cloned()
/// .inspect(|x| println!("about to filter: {}", x))
/// .filter(|&x| x % 2 == 0)
/// .inspect(|x| println!("made it through filter: {}", x))
/// .reduce(|| 0, |sum, i| sum + i);
///
/// println!("{}", sum);
/// ```
fn inspect<OP>(self, inspect_op: OP) -> Inspect<Self, OP>
where
OP: Fn(&Self::Item) + Sync + Send,
{
Inspect::new(self, inspect_op)
}
/// Mutates each item of this iterator before yielding it.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let par_iter = (0..5).into_par_iter().update(|x| {*x *= 2;});
///
/// let doubles: Vec<_> = par_iter.collect();
///
/// assert_eq!(&doubles[..], &[0, 2, 4, 6, 8]);
/// ```
fn update<F>(self, update_op: F) -> Update<Self, F>
where
F: Fn(&mut Self::Item) + Sync + Send,
{
Update::new(self, update_op)
}
/// Applies `filter_op` to each item of this iterator, producing a new
/// iterator with only the items that gave `true` results.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let mut par_iter = (0..10).into_par_iter().filter(|x| x % 2 == 0);
///
/// let even_numbers: Vec<_> = par_iter.collect();
///
/// assert_eq!(&even_numbers[..], &[0, 2, 4, 6, 8]);
/// ```
fn filter<P>(self, filter_op: P) -> Filter<Self, P>
where
P: Fn(&Self::Item) -> bool + Sync + Send,
{
Filter::new(self, filter_op)
}
/// Applies `filter_op` to each item of this iterator to get an `Option`,
/// producing a new iterator with only the items from `Some` results.
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let mut par_iter = (0..10).into_par_iter()
/// .filter_map(|x| {
/// if x % 2 == 0 { Some(x * 3) }
/// else { None }
/// });
///
/// let even_numbers: Vec<_> = par_iter.collect();
///
/// assert_eq!(&even_numbers[..], &[0, 6, 12, 18, 24]);
/// ```
fn filter_map<P, R>(self, filter_op: P) -> FilterMap<Self, P>
where
P: Fn(Self::Item) -> Option<R> + Sync + Send,
R: Send,
{
FilterMap::new(self, filter_op)
}
/// Applies `map_op` to each item of this iterator to get nested parallel iterators,
/// producing a new parallel iterator that flattens these back into one.
///
/// See also [`flat_map_iter`](#method.flat_map_iter).
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let a = [[1, 2], [3, 4], [5, 6], [7, 8]];
///
/// let par_iter = a.par_iter().cloned().flat_map(|a| a.to_vec());
///
/// let vec: Vec<_> = par_iter.collect();
///
/// assert_eq!(&vec[..], &[1, 2, 3, 4, 5, 6, 7, 8]);
/// ```
fn flat_map<F, PI>(self, map_op: F) -> FlatMap<Self, F>
where
F: Fn(Self::Item) -> PI + Sync + Send,
PI: IntoParallelIterator,
{
FlatMap::new(self, map_op)
}
/// Applies `map_op` to each item of this iterator to get nested serial iterators,
/// producing a new parallel iterator that flattens these back into one.
///
/// # `flat_map_iter` versus `flat_map`
///
/// These two methods are similar but behave slightly differently. With [`flat_map`],
/// each of the nested iterators must be a parallel iterator, and they will be further
/// split up with nested parallelism. With `flat_map_iter`, each nested iterator is a
/// sequential `Iterator`, and we only parallelize _between_ them, while the items
/// produced by each nested iterator are processed sequentially.
///
/// When choosing between these methods, consider whether nested parallelism suits the
/// potential iterators at hand. If there's little computation involved, or its length
/// is much less than the outer parallel iterator, then it may perform better to avoid
/// the overhead of parallelism, just flattening sequentially with `flat_map_iter`.
/// If there is a lot of computation, potentially outweighing the outer parallel
/// iterator, then the nested parallelism of `flat_map` may be worthwhile.
///
/// [`flat_map`]: #method.flat_map
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
/// use std::cell::RefCell;
///
/// let a = [[1, 2], [3, 4], [5, 6], [7, 8]];
///
/// let par_iter = a.par_iter().flat_map_iter(|a| {
/// // The serial iterator doesn't have to be thread-safe, just its items.
/// let cell_iter = RefCell::new(a.iter().cloned());
/// std::iter::from_fn(move || cell_iter.borrow_mut().next())
/// });
///
/// let vec: Vec<_> = par_iter.collect();
///
/// assert_eq!(&vec[..], &[1, 2, 3, 4, 5, 6, 7, 8]);
/// ```
fn flat_map_iter<F, SI>(self, map_op: F) -> FlatMapIter<Self, F>
where
F: Fn(Self::Item) -> SI + Sync + Send,
SI: IntoIterator,
SI::Item: Send,
{
FlatMapIter::new(self, map_op)
}
/// An adaptor that flattens parallel-iterable `Item`s into one large iterator.
///
/// See also [`flatten_iter`](#method.flatten_iter).
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let x: Vec<Vec<_>> = vec![vec![1, 2], vec![3, 4]];
/// let y: Vec<_> = x.into_par_iter().flatten().collect();
///
/// assert_eq!(y, vec![1, 2, 3, 4]);
/// ```
fn flatten(self) -> Flatten<Self>
where
Self::Item: IntoParallelIterator,
{
Flatten::new(self)
}
/// An adaptor that flattens serial-iterable `Item`s into one large iterator.
///
/// See also [`flatten`](#method.flatten) and the analogous comparison of
/// [`flat_map_iter` versus `flat_map`](#flat_map_iter-versus-flat_map).
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let x: Vec<Vec<_>> = vec![vec![1, 2], vec![3, 4]];
/// let iters: Vec<_> = x.into_iter().map(Vec::into_iter).collect();
/// let y: Vec<_> = iters.into_par_iter().flatten_iter().collect();
///
/// assert_eq!(y, vec![1, 2, 3, 4]);
/// ```
fn flatten_iter(self) -> FlattenIter<Self>
where
Self::Item: IntoIterator,
<Self::Item as IntoIterator>::Item: Send,
{
FlattenIter::new(self)
}
/// Reduces the items in the iterator into one item using `op`.
/// The argument `identity` should be a closure that can produce
/// "identity" value which may be inserted into the sequence as
/// needed to create opportunities for parallel execution. So, for
/// example, if you are doing a summation, then `identity()` ought
/// to produce something that represents the zero for your type
/// (but consider just calling `sum()` in that case).
///
/// # Examples
///
/// ```
/// // Iterate over a sequence of pairs `(x0, y0), ..., (xN, yN)`
/// // and use reduce to compute one pair `(x0 + ... + xN, y0 + ... + yN)`
/// // where the first/second elements are summed separately.
/// use rayon::prelude::*;
/// let sums = [(0, 1), (5, 6), (16, 2), (8, 9)]
/// .par_iter() // iterating over &(i32, i32)
/// .cloned() // iterating over (i32, i32)
/// .reduce(|| (0, 0), // the "identity" is 0 in both columns
/// |a, b| (a.0 + b.0, a.1 + b.1));
/// assert_eq!(sums, (0 + 5 + 16 + 8, 1 + 6 + 2 + 9));
/// ```
///
/// **Note:** unlike a sequential `fold` operation, the order in
/// which `op` will be applied to reduce the result is not fully
/// specified. So `op` should be [associative] or else the results
/// will be non-deterministic. And of course `identity()` should
/// produce a true identity.
///
/// [associative]: https://en.wikipedia.org/wiki/Associative_property
fn reduce<OP, ID>(self, identity: ID, op: OP) -> Self::Item
where
OP: Fn(Self::Item, Self::Item) -> Self::Item + Sync + Send,
ID: Fn() -> Self::Item + Sync + Send,
{
reduce::reduce(self, identity, op)
}