### Using install() to run a closure in the pool Source: https://docs.rs/rayon/latest/rayon/struct.ThreadPool.html Shows how to use install() to execute a closure that uses rayon::join inside the pool, with a fib function example. ```rust fn main() { let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap(); let n = pool.install(|| fib(20)); println!("{}", n); } fn fib(n: usize) -> usize { if n == 0 || n == 1 { return n; } let (a, b) = rayon::join(|| fib(n - 1), || fib(n - 2)); // runs inside of `pool` return a + b; } ``` -------------------------------- ### partial_cmp: Example (incomplete) Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html This example is incomplete in the source; it only shows the imports and starts the partial_cmp example. ```rust use rayon::prelude::*; use std::cmp::Ordering::*; ``` -------------------------------- ### Example of install() with execution order warning Source: https://docs.rs/rayon/latest/rayon/struct.ThreadPool.html Demonstrates the execution order warning for install(): when the current thread is part of a different pool, install() yields implicitly, allowing other tasks to run concurrently. ```rust fn main() { rayon::ThreadPoolBuilder::new().num_threads(1).build_global().unwrap(); let pool = rayon_core::ThreadPoolBuilder::default().build().unwrap(); let do_it = || { print!("one "); pool.install(||{}); print!("two "); }; rayon::join(|| do_it(), || do_it()); } ``` ```text one two one two ``` ```text one one two two ``` -------------------------------- ### Example of install() yielding execution order Source: https://docs.rs/rayon/latest/rayon/struct.ThreadPool.html?search= Shows that install() yields implicitly, allowing multiple instances of do_it() to run concurrently on a single global thread, producing output like 'one two one two' or 'one one two two'. ```rust fn main() { rayon::ThreadPoolBuilder::new().num_threads(1).build_global().unwrap(); let pool = rayon_core::ThreadPoolBuilder::default().build().unwrap(); let do_it = || { print!("one "); pool.install(||{}); print!("two "); }; rayon::join(|| do_it(), || do_it()); } ``` -------------------------------- ### Quick-sort example using rayon::join Source: https://docs.rs/rayon/latest/rayon/fn.join.html Example usage of `rayon::join` to perform a quick-sort on a vector. The example includes the `quick_sort` and `partition` functions. Note that this is not an optimized implementation; prefer `par_sort` for real sorting. ```rust let mut v = vec![5, 1, 8, 22, 0, 44]; quick_sort(&mut v); assert_eq!(v, vec![0, 1, 5, 8, 22, 44]); fn quick_sort(v: &mut [T]) { if v.len() > 1 { let mid = partition(v); let (lo, hi) = v.split_at_mut(mid); rayon::join(|| quick_sort(lo), || quick_sort(hi)); } } // Partition rearranges all items `<=` to the pivot // item (arbitrary selected to be the last item in the slice) // to the first half of the slice. It then returns the // "dividing point" where the pivot is placed. fn partition(v: &mut [T]) -> usize { let pivot = v.len() - 1; let mut i = 0; for j in 0..pivot { if v[j] <= v[pivot] { v.swap(i, j); i += 1; } } v.swap(i, pivot); i } ``` -------------------------------- ### take example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator that yields the first n elements. The example takes the first 5 elements of a range. ```rust use rayon::prelude::*; let result: Vec<_> = (0..100) .into_par_iter() .take(5) .collect(); assert_eq!(result, [0, 1, 2, 3, 4]); ``` -------------------------------- ### step_by example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator that steps by the given amount. The example collects every third element from a range. ```rust use rayon::prelude::*; let range = (3..10); let result: Vec = range .into_par_iter() .step_by(3) .collect(); assert_eq!(result, [3, 6, 9]) ``` -------------------------------- ### Example of spawning tasks with scope_fifo Source: https://docs.rs/rayon/latest/rayon/fn.scope_fifo.html?search=u32+-%3E+bool An example showing how to use scope_fifo to spawn tasks with FIFO order. Tasks are spawned with spawn_fifo, and nested scopes are used. The example is used to illustrate the execution order of tasks. ```rust // point start rayon::scope_fifo(|s| { s.spawn_fifo(|s| { // task s.1 s.spawn_fifo(|s| { // task s.1.1 rayon::scope_fifo(|t| { t.spawn_fifo(|_| ()); // task t.1 t.spawn_fifo(|_| ()); // task t.2 }); }); }); s.spawn_fifo(|s| { // task s.2 }); // point mid }); // point end ``` -------------------------------- ### enumerate example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Yields an index along with each item. The example collects into a vector of tuples. ```rust use rayon::prelude::*; let chars = vec!['a', 'b', 'c']; let result: Vec<_> = chars .into_par_iter() .enumerate() .collect(); assert_eq!(result, [(0, 'a'), (1, 'b'), (2, 'c')]); ``` -------------------------------- ### zip_eq example (panics on length mismatch) Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use zip_eq, which panics if the two iterators are not the same length. The example is marked as panicking. ```rust use rayon::prelude::*; let one = [1u8]; let two = [2u8, 2]; let one_iter = one.par_iter(); let two_iter = two.par_iter(); // this will panic let zipped: Vec<(&u8, &u8)> = one_iter.zip_eq(two_iter).collect(); ``` -------------------------------- ### position_any example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Searches for some item matching the predicate and returns its index. The example shows that the index may be 2 or 3 for the value 3. ```rust use rayon::prelude::*; let a = [1, 2, 3, 3]; let i = a.par_iter().position_any(|&x| x == 3).expect("found"); assert!(i == 2 || i == 3); assert_eq!(a.par_iter().position_any(|&x| x == 100), None); ``` -------------------------------- ### Example tree diagram for walk_tree_postfix Source: https://docs.rs/rayon/latest/rayon/iter/fn.walk_tree_postfix.html A simple tree diagram used in the first example: root 4 with children 2 and 3, and 3 has children 1 and 2. ```text 4 / \ / \ 2 3 / \ 1 2 ``` -------------------------------- ### for_each example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Executes a closure on each item in parallel. The example prints numbers 0 to 99. ```rust use rayon::prelude::*; (0..100).into_par_iter().for_each(|x| println!("{:?}", x)); ``` -------------------------------- ### Example: using Scope::spawn to spawn tasks Source: https://docs.rs/rayon/latest/rayon/struct.Scope.html?search=std%3A%3Avec Example from the documentation for Scope::spawn. It shows how to spawn tasks that write to local variables, and demonstrates that the scope waits for all spawned tasks to complete before the scope ends. ```rust let mut value_a = None; let mut value_b = None; let mut value_c = None; rayon::scope(|s| { s.spawn(|s1| { // ^ this is the same scope as `s`; this handle `s1` // is intended for use by the spawned task, // since scope handles cannot cross thread boundaries. value_a = Some(22); // the scope `s` will not end until all these tasks are done s1.spawn(|_| { value_b = Some(44); }); }); s.spawn(|_| { value_c = Some(66); }); }); assert_eq!(value_a, Some(22)); assert_eq!(value_b, Some(44)); assert_eq!(value_c, Some(66)); ``` -------------------------------- ### positions example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Collects indices of all elements matching a predicate. The example finds primes congruent to 1 and 5 modulo 6. ```rust use rayon::prelude::*; let primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; // Find the positions of primes congruent to 1 modulo 6 let p1mod6: Vec<_> = primes.par_iter().positions(|&p| p % 6 == 1).collect(); assert_eq!(p1mod6, [3, 5, 7]); // primes 7, 13, and 19 // Find the positions of primes congruent to 5 modulo 6 let p5mod6: Vec<_> = primes.par_iter().positions(|&p| p % 6 == 5).collect(); assert_eq!(p5mod6, [2, 4, 6, 8, 9]); // primes 5, 11, 17, 23, and 29 ``` -------------------------------- ### for_each_with example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Executes a closure with an initial value on each item in parallel. The init value is cloned as needed and does not need to be Sync. The example sends items through a channel and asserts the collected results. ```rust 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]) ``` -------------------------------- ### position_first example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Searches for the sequentially first item matching the predicate and returns its index. The example shows that the first occurrence of 3 is at index 2. ```rust use rayon::prelude::*; let a = [1, 2, 3, 3]; assert_eq!(a.par_iter().position_first(|&x| x == 3), Some(2)); ``` -------------------------------- ### fold_chunks_with example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Similar to fold_chunks but uses an initial value that is cloned for each chunk. The example sums each chunk of size 2. Panics if chunk_size is 0. ```rust use rayon::prelude::*; let nums = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let chunk_sums = nums.into_par_iter().fold_chunks_with(2, 0, |a, n| a + n).collect::>(); assert_eq!(chunk_sums, vec![3, 7, 11, 15, 19]); ``` -------------------------------- ### Example: using par_iter to sum and compare references Source: https://docs.rs/rayon/latest/rayon/iter/trait.IntoParallelRefIterator.html Shows how to use `par_iter` on a vector to compute a sum and to verify that `par_iter` produces the same references as `into_par_iter`. The example uses `rayon::prelude::*` and asserts the sum equals 100 * 99 / 2. ```rust use rayon::prelude::*; let v: Vec<_> = (0..100).collect(); assert_eq!(v.par_iter().sum::(), 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))); ``` -------------------------------- ### par_matches example Source: https://docs.rs/rayon/latest/rayon/str/trait.ParallelString.html?search= Finds all substrings matching a predicate in parallel. The example sums numeric digits parsed from matches. ```rust use rayon::prelude::*; let total = "1, 2, buckle, 3, 4, door" .par_matches(char::is_numeric) .map(|s| s.parse::().expect("digit")) .sum(); assert_eq!(10, total); ``` -------------------------------- ### partial_cmp example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Lexicographically compares the elements of this parallel iterator with another, returning an Option. The example shows comparisons yielding Some(Less), Some(Equal), and Some(Greater). ```rust use rayon::prelude::*; use std::cmp::Ordering::*; let x = vec![1, 2, 3]; assert_eq!(x.par_iter().partial_cmp(&vec![1, 3, 0]), Some(Less)); assert_eq!(x.par_iter().partial_cmp(&vec![1, 2, 3]), Some(Equal)); assert_eq!(x.par_iter().partial_cmp(&vec![1, 2]), Some(Greater)); ``` -------------------------------- ### skip example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator that skips the first n elements. The example skips the first 95 elements of a range. ```rust use rayon::prelude::*; let result: Vec<_> = (0..100) .into_par_iter() .skip(95) .collect(); assert_eq!(result, [95, 96, 97, 98, 99]); ``` -------------------------------- ### Examples for IndexedParallelIterator methods Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html These examples appear on the trait documentation page for `IndexedParallelIterator` in Rayon, one per method. They are copied verbatim from the documentation and demonstrate the typical usage of each method. ```rust use rayon::prelude::*; let a = [1, 2, 3, 3]; assert_eq!(a.par_iter().position_first(|&x| x == 3), Some(2)); assert_eq!(a.par_iter().position_first(|&x| x == 100), None); ``` ```rust use rayon::prelude::*; let a = [1, 2, 3, 3]; assert_eq!(a.par_iter().position_last(|&x| x == 3), Some(3)); assert_eq!(a.par_iter().position_last(|&x| x == 100), None); ``` ```rust use rayon::prelude::*; let primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; // Find the positions of primes congruent to 1 modulo 6 let p1mod6: Vec<_> = primes.par_iter().positions(|&p| p % 6 == 1).collect(); assert_eq!(p1mod6, [3, 5, 7]); // primes 7, 13, and 19 // Find the positions of primes congruent to 5 modulo 6 let p5mod6: Vec<_> = primes.par_iter().positions(|&p| p % 6 == 5).collect(); assert_eq!(p5mod6, [2, 4, 6, 8, 9]); // primes 5, 11, 17, 23, and 29 ``` ```rust use rayon::prelude::*; let result: Vec<_> = (0..5) .into_par_iter() .rev() .collect(); assert_eq!(result, [4, 3, 2, 1, 0]); ``` ```rust use rayon::prelude::*; let min = (0..1_000_000) .into_par_iter() .with_min_len(1234) .fold(|| 0, |acc, _| acc + 1) // count how many are in this segment .min().unwrap(); assert!(min >= 1234); ``` ```rust use rayon::prelude::*; let max = (0..1_000_000) .into_par_iter() .with_max_len(1234) .fold(|| 0, |acc, _| acc + 1) // count how many are in this segment .max().unwrap(); assert!(max <= 1234); ``` -------------------------------- ### for_each_init example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Executes a closure with a value returned by an init function on each item in parallel. The init function is called as needed and the returned type has no constraints. The example fills chunks with random bytes and checks that all byte values appear. ```rust use rand::Rng; use rayon::prelude::*; let mut v = vec![0u8; 1_000_000]; v.par_chunks_mut(1000) .for_each_init( || rand::rng(), |rng, chunk| rng.fill(chunk), ); // There's a remote chance that this will fail... for i in 0u8..=255 { assert!(v.contains(&i)); } ``` -------------------------------- ### product example: factorial using product Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Multiplies all items in a parallel iterator. The order of reduction is not specified, so results may be non-deterministic for non-associative operations. The example defines a factorial function and asserts values for 0, 1, and 5. ```rust use rayon::prelude::*; fn factorial(n: u32) -> u32 { (1..n+1).into_par_iter().product() } assert_eq!(factorial(0), 1); assert_eq!(factorial(1), 1); assert_eq!(factorial(5), 120); ``` -------------------------------- ### cmp example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Lexicographically compares the elements of this parallel iterator with another. The example shows comparisons yielding Less, Equal, and Greater. ```rust use rayon::prelude::*; use std::cmp::Ordering::*; let x = vec![1, 2, 3]; assert_eq!(x.par_iter().cmp(&vec![1, 3, 0]), Less); assert_eq!(x.par_iter().cmp(&vec![1, 2, 3]), Equal); assert_eq!(x.par_iter().cmp(&vec![1, 2]), Greater); ``` -------------------------------- ### Example: Using par_iter_mut to mutate a vector Source: https://docs.rs/rayon/latest/rayon/iter/trait.IntoParallelRefMutIterator.html Shows how to use par_iter_mut() to mutate each element of a vector in parallel. The example sets each element to its index and asserts the result. ```rust 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]); ``` -------------------------------- ### try_for_each_init example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Executes a fallible closure with a value returned by an init function on each item in parallel, combining for_each_init and try_for_each semantics. The example fills chunks with random bytes using try_fill_bytes and expects no rand errors. ```rust use rand::{Rng, TryRngCore}; use rayon::prelude::*; let mut v = vec![0u8; 1_000_000]; v.par_chunks_mut(1000) .try_for_each_init( || rand::rng(), |rng, chunk| rng.try_fill_bytes(chunk), ) .expect("expected no rand errors"); // There's a remote chance that this will fail... for i in 0u8..=255 { assert!(v.contains(&i)); } ``` -------------------------------- ### try_for_each example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Executes a fallible closure on each item in parallel, stopping early on error. The example writes to stdout and expects no write errors. ```rust 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"); ``` -------------------------------- ### Usage example: parallel range iteration with zip, filter, map, and sum Source: https://docs.rs/rayon/latest/rayon/range/struct.Iter.html?search= This example demonstrates using Iter via into_par_iter() on a range, zipping with another range, filtering, mapping, and summing. It compares the parallel result with a sequential equivalent and asserts equality. Note that zip requires IndexedParallelIterator, which is not implemented for u64, i64, u128, or i128. ```rust use rayon::prelude::*; let p = (0..25usize).into_par_iter() .zip(0..25usize) .filter(|&(x, y)| x % 5 == 0 || y % 5 == 0) .map(|(x, y)| x * y) .sum::(); let s = (0..25usize).zip(0..25) .filter(|&(x, y)| x % 5 == 0 || y % 5 == 0) .map(|(x, y)| x * y) .sum(); assert_eq!(p, s); ``` -------------------------------- ### zip example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to zip two parallel iterators into tuples, stopping at the shorter iterator. ```rust use rayon::prelude::*; let result: Vec<_> = (1..4) .into_par_iter() .zip(vec!['a', 'b', 'c']) .collect(); assert_eq!(result, [(1, 'a'), (2, 'b'), (3, 'c')]); ``` -------------------------------- ### Example of nested spawn_fifo tasks Source: https://docs.rs/rayon/latest/rayon/fn.scope_fifo.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example showing how to use scope_fifo with nested spawn_fifo calls. Tasks are executed in FIFO order on the spawning thread, so s.1 runs before s.2 and t.1 before t.2. ```rust // point start rayon::scope_fifo(|s| { s.spawn_fifo(|s| { // task s.1 s.spawn_fifo(|s| { // task s.1.1 rayon::scope_fifo(|t| { t.spawn_fifo(|_| ()); // task t.1 t.spawn_fifo(|_| ()); // task t.2 }); }); }); s.spawn_fifo(|s| { // task s.2 }); // point mid }); // point end ``` -------------------------------- ### position_first example with panic case Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=std%3A%3Avec Shows the documented panic behavior for position_first when no item matches the predicate. The example asserts that searching for 100 in [1, 2, 3, 3] returns None. ```rust assert_eq!(a.par_iter().position_first(|&x| x == 100), None); ``` -------------------------------- ### try_for_each_with example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Executes a fallible closure with an initial value on each item in parallel, combining for_each_with and try_for_each semantics. The example sends items through a channel and expects no send errors. ```rust 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]) ``` -------------------------------- ### unzip: pairs and nested pairs Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html?search= Examples for `ParallelIterator::unzip` showing how to unzip tuples into two collectionsyahoo, and how nested pairs can be unzipped into nested collections. The second example uses `.map()` to create nested tuples before unzipping. ```rust use rayon::prelude::*; let a = [(0, 1), (1, 2), (2, 3), (3, 4)]; let (left, right): (Vec<_>, Vec<_>) = a.par_iter().cloned().unzip(); assert_eq!(left, [0, 1, 2, 3]); assert_eq!(right, [1, 2, 3, 4]); ``` ```rust use rayon::prelude::*; let (values, (squares, cubes)): (Vec<_>, (Vec<_>, Vec<_>)) = (0..4).into_par_iter() .map(|i| (i, (i * i, i * i * i))) .unzip(); ``` -------------------------------- ### fold_chunks example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Splits an iterator into fixed-size chunks and performs a sequential fold on each chunk. The example sums each chunk of size 2. Panics if chunk_size is 0. ```rust use rayon::prelude::*; let nums = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let chunk_sums = nums.into_par_iter().fold_chunks(2, || 0, |a, n| a + n).collect::>(); assert_eq!(chunk_sums, vec![3, 7, 11, 15, 19]); ``` -------------------------------- ### par_split_whitespace examples Source: https://docs.rs/rayon/latest/rayon/str/trait.ParallelString.html?search= Splits a string by Unicode whitespace. Includes three examples: finding the longest word, splitting with various whitespace characters, and handling empty or all-whitespace strings. ```rust use rayon::prelude::*; let longest = "which is the longest word?" .par_split_whitespace() .max_by_key(|word| word.len()); assert_eq!(Some("longest"), longest); ``` ```rust use rayon::prelude::*; let words: Vec<&str> = " Mary had\ta\u{2009}little \n\t lamb" .par_split_whitespace() .collect(); assert_eq!(words, ["Mary", "had", "a", "little", "lamb"]); ``` ```rust use rayon::prelude::*; assert_eq!("".par_split_whitespace().count(), 0); assert_eq!(" ".par_split_whitespace().count(), 0); ``` -------------------------------- ### partial_cmp example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use partial_cmp on a parallel iterator to compare with a vector, returning an Ordering. ```rust let x = vec![1.0, 2.0, 3.0]; assert_eq!(x.par_iter().partial_cmp(&vec![1.0, 3.0, 0.0]), Some(Less)); assert_eq!(x.par_iter().partial_cmp(&vec![1.0, 2.0, 3.0]), Some(Equal)); assert_eq!(x.par_iter().partial_cmp(&vec![1.0, 2.0]), Some(Greater)); assert_eq!(x.par_iter().partial_cmp(&vec![1.0, f64::NAN]), None); ``` -------------------------------- ### walk_tree_postfix example with custom Node struct Source: https://docs.rs/rayon/latest/rayon/iter/fn.walk_tree_postfix.html?search=std%3A%3Avec Example using walk_tree_postfix on a custom Node struct with left and right children. The children_of closure chains left and right child references. The collected contents are asserted to be [3, 18, 14, 10]. ```rust use rayon::prelude::*; use rayon::iter::walk_tree_postfix; struct Node { content: u32, left: Option>, right: Option>, } // Here we loop on the following tree: // // 10 // / \ // / \ // 3 14 // \ // \ // 18 let root = Node { content: 10, left: Some(Box::new(Node { content: 3, left: None, right: None, })), right: Some(Box::new(Node { content: 14, left: None, right: Some(Box::new(Node { content: 18, left: None, right: None, })), })), }; let mut v: Vec = walk_tree_postfix(&root, |r| { r.left .as_ref() .into_iter() .chain(r.right.as_ref()) .map(|n| &**n) }) .map(|node| node.content) .collect(); assert_eq!(v, vec![3, 18, 14, 10]); ``` -------------------------------- ### Example: Using len() on an IndexedParallelIterator Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use the len() method to get an exact count of items in a parallel iterator. The example creates a parallel iterator over a range zipped with a vector and asserts the length is 10. ```rust use rayon::prelude::*; let par_iter = (0..100).into_par_iter().zip(vec![0; 10]); assert_eq!(par_iter.len(), 10); let vec: Vec<_> = par_iter.collect(); assert_eq!(vec.len(), 10); ``` -------------------------------- ### par_rchunks_mut example Source: https://docs.rs/rayon/latest/rayon/slice/trait.ParallelSliceMut.html Reverses each mutable chunk of at most 2 elements, starting from the end. The last chunk may be shorter if the length is not divisible by the chunk size. ```rust use rayon::prelude::*; let mut array = [1, 2, 3, 4, 5]; array.par_rchunks_mut(2) .for_each(|slice| slice.reverse()); assert_eq!(array, [1, 3, 2, 5, 4]); ``` -------------------------------- ### par_rchunks_exact_mut example Source: https://docs.rs/rayon/latest/rayon/slice/trait.ParallelSliceMut.html Reverses each mutable chunk of exactly 3 elements, starting from the end. If the chunk size does not divide the length, the last up to chunk_size-1 elements are omitted and can be retrieved from the remainder function. ```rust use rayon::prelude::*; let mut array = [1, 2, 3, 4, 5]; array.par_rchunks_exact_mut(3) .for_each(|slice| slice.reverse()); assert_eq!(array, [1, 2, 5, 4, 3]); ``` -------------------------------- ### step_by Source: https://docs.rs/rayon/latest/rayon/iter/struct.MultiZip.html Creates an iterator that yields every nth element starting from the first. ```APIDOC ### Description Creates an iterator that steps by the given amount. ### Method Method call: `step_by` ### Signature fn step_by(self, step: usize) -> StepBy ``` -------------------------------- ### par_rchunks: parallel iterator over chunks from the end Source: https://docs.rs/rayon/latest/rayon/slice/trait.ParallelSlice.html Like par_chunks but processes chunks starting from the end of the slice; the first chunk (from the end) may be shorter. The example collects chunks of size 2 from five elements in reverse order. ```rust use rayon::prelude::*; let chunks: Vec<_> = [1, 2, 3, 4, 5].par_rchunks(2).collect(); assert_eq!(chunks, vec![&[4, 5][..], &[2, 3], &[1]]); ``` -------------------------------- ### par_rchunks_exact: parallel iterator over exact chunks from the end Source: https://docs.rs/rayon/latest/rayon/slice/trait.ParallelSlice.html Like par_chunks_exact but processes chunks starting from the end; any remainder is omitted and can be retrieved from the iterator's remainder function. The example collects exact chunks of size 2 from five elements, dropping the first element. ```rust use rayon::prelude::*; let chunks: Vec<_> = [1, 2, 3, 4, 5].par_rchunks_exact(2).collect(); assert_eq!(chunks, vec![&[4, 5][..], &[2, 3]]); ``` -------------------------------- ### Method: for_each_init Source: https://docs.rs/rayon/latest/rayon/iter/struct.WalkTreePostfix.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for the `for_each_init` method on `WalkTreePostfix`, which executes an operation with a newly initialized state on each item. ```APIDOC ## [method] for_each_init(self, init: INIT, op: OP) ### Description Executes `OP` on a value returned by `init` with each item produced by the iterator, in parallel. ### Signature `fn for_each_init(self, init: INIT, op: OP) where OP: Fn(&mut T, Self::Item) + Sync + Send, INIT: Fn() -> T + Sync + Send` ### Parameters - `init` (closure) - Required - A closure that returns a new `T` value for each parallel invocation. - `op` (closure) - Required - The operation to execute with the mutable reference to the value and each item. ### Note This is a method of the `ParallelIterator` trait, available on `WalkTreePostfix`. ``` -------------------------------- ### Postfix ordering example with a perfect binary tree Source: https://docs.rs/rayon/latest/rayon/iter/fn.walk_tree_postfix.html Shows the reduction order for a perfect binary tree of 7 nodes: d,e,b,f,g,c,a. This illustrates the postfix ordering guarantee. ```text a / \ / \ b c / \ / \ d e f g reduced as d,e,b,f,g,c,a ``` -------------------------------- ### Method: try_for_each_init Source: https://docs.rs/rayon/latest/rayon/iter/struct.WalkTreePostfix.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for the `try_for_each_init` method on `WalkTreePostfix`, which executes a fallible operation with a newly initialized state on each item. ```APIDOC ## [method] try_for_each_init(self, init: INIT, op: OP) -> R ### Description Executes a fallible `OP` on a value returned by `init` with each item produced by the iterator, in parallel. ### Signature `fn try_for_each_init(self, init: INIT, op: OP) -> R where OP: Fn(&mut T, Self::Item) -> R + Sync + Send, INIT: Fn() -> T + Sync + Send, R: Try + Send` ### Parameters - `init` (closure) - Required - A closure that returns a new `T` value for each parallel invocation. - `op` (closure) - Required - The fallible operation to execute with the mutable reference to the value and each item. ### Returns - `R` - The result of the operation, which implements `Try` with `Output = ()`. ### Note This is a method of the `ParallelIterator` trait, available on `WalkTreePostfix`. ``` -------------------------------- ### par_lines example Source: https://docs.rs/rayon/latest/rayon/str/trait.ParallelString.html?search= Iterates over lines in parallel, excluding line endings. The example computes the length of each line. ```rust use rayon::prelude::*; let lengths: Vec<_> = "hello world\nfizbuzz" .par_lines() .map(|l| l.len()) .collect(); assert_eq!(vec![11, 7], lengths); ``` -------------------------------- ### par_sort_unstable_by examples Source: https://docs.rs/rayon/latest/rayon/slice/trait.ParallelSliceMut.html?search=u32+-%3E+bool Sorts a mutable slice in parallel using a comparator function. The comparator must define a total ordering. The first example sorts floats using partial_cmp, and the second example sorts integers in ascending and then descending order. ```rust use rayon::prelude::*; let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0]; floats.par_sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]); ``` ```rust use rayon::prelude::*; let mut v = [5, 4, 1, 3, 2]; v.par_sort_unstable_by(|a, b| a.cmp(b)); assert_eq!(v, [1, 2, 3, 4, 5]); // reverse sorting v.par_sort_unstable_by(|a, b| b.cmp(a)); assert_eq!(v, [5, 4, 3, 2, 1]); ``` -------------------------------- ### Prefix ordering example tree Source: https://docs.rs/rayon/latest/rayon/iter/fn.walk_tree_prefix.html?search=std%3A%3Avec A diagram of a perfect binary tree of 7 nodes, used to illustrate the prefix ordering guarantee of walk_tree_prefix. ```text a / \ / \ b c / \ / \ d e f g reduced as a,b,d,e,c,f,g ``` -------------------------------- ### all example: check if all items match predicate Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Returns true if every item matches the predicate. If a counter-example is found, processing stops and false is returned. ```rust use rayon::prelude::*; let a = [0, 12, 3, 4, 0, 23, 0]; let is_valid = a.par_iter().all(|&x| x > 10); assert!(!is_valid); ``` -------------------------------- ### par_match_indices example Source: https://docs.rs/rayon/latest/rayon/str/trait.ParallelString.html?search= Finds substrings matching a predicate along with their byte indices. The example collects digit matches and their positions. ```rust use rayon::prelude::*; let digits: Vec<_> = "1, 2, buckle, 3, 4, door" .par_match_indices(char::is_numeric) .collect(); assert_eq!(digits, vec![(0, "1"), (3, "2"), (14, "3"), (17, "4")]); ``` -------------------------------- ### count example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Counts the number of items in the parallel iterator. The example counts 0 to 99 and asserts the result is 100. ```rust use rayon::prelude::*; let count = (0..100).into_par_iter().count(); assert_eq!(count, 100); ``` -------------------------------- ### any example: check if any item matches predicate Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Returns true if some item matches the predicate. Processing stops as soon as a match is found. Proving no match requires visiting every item. ```rust use rayon::prelude::*; let a = [0, 12, 3, 4, 0, 23, 0]; let is_valid = a.par_iter().any(|&x| x > 10); assert!(is_valid); ``` -------------------------------- ### pub fn join(&self, oper_a: A, oper_b: B) -> (RA, RB) Source: https://docs.rs/rayon/latest/rayon/struct.ThreadPool.html?search=u32+-%3E+bool Executes two closures in the thread pool and returns their results. Equivalent to self.install(|| join(oper_a, oper_b)). ```APIDOC ## pub fn join(&self, oper_a: A, oper_b: B) -> (RA, RB) ### Description Execute `oper_a` and `oper_b` in the thread pool and return the results. Equivalent to `self.install(|| join(oper_a, oper_b))`. ### Method join ### Signature pub fn join(&self, oper_a: A, oper_b: B) -> (RA, RB) where A: FnOnce() -> RA + Send, B: FnOnce() -> RB + Send, RA: Send, RB: Send, ### Parameters - **oper_a** (A) - Required - The first closure to execute. - **oper_b** (B) - Required - The second closure to execute. ### Returns - **(RA, RB)** - A tuple containing the results of `oper_a` and `oper_b`. ``` -------------------------------- ### chain example Source: https://docs.rs/rayon/latest/rayon/iter/trait.ParallelIterator.html Creates a new iterator that chains two parallel iterators. The example chains two arrays and collects the result. ```rust use rayon::prelude::*; let a = [0, 1, 2]; let b = [9, 8, 7]; let par_iter = a.par_iter().chain(b.par_iter()); let chained: Vec<_> = par_iter.cloned().collect(); assert_eq!(&chained[..], &[0, 1, 2, 9, 8, 7]); ``` -------------------------------- ### Example: traverse struct tree with walk_tree_prefix Source: https://docs.rs/rayon/latest/rayon/iter/fn.walk_tree_prefix.html?search=std%3A%3Avec Builds a binary tree of Node structs and uses walk_tree_prefix to collect node contents in prefix order. The children_of closure chains left and right child references. The result is asserted to be [10, 3, 14, 18]. ```rust use rayon::prelude::*; use rayon::iter::walk_tree_prefix; struct Node { content: u32, left: Option>, right: Option>, } // Here we loop on the following tree: // // 10 // / \ // / \ // 3 14 // \ // \ // 18 let root = Node { content: 10, left: Some(Box::new(Node { content: 3, left: None, right: None, })), right: Some(Box::new(Node { content: 14, left: None, right: Some(Box::new(Node { content: 18, left: None, right: None, })), })), }; let mut v: Vec = walk_tree_prefix(&root, |r| { r.left .as_ref() .into_iter() .chain(r.right.as_ref()) .map(|n| &**n) }) .map(|node| node.content) .collect(); assert_eq!(v, vec![10, 3, 14, 18]); ``` -------------------------------- ### Example: Using repeat with zip to create a finite parallel iterator Source: https://docs.rs/rayon/latest/rayon/iter/fn.repeat.html Creates a parallel iterator that repeats 22 and zips it with a range 0..3, collecting into a vector of pairs. The result is [(22, 0), (22, 1), (22, 2)]. ```rust use rayon::prelude::*; use rayon::iter::repeat; let x: Vec<(i32, i32)> = repeat(22).zip(0..3).collect(); assert_eq!(x, vec![(22, 0), (22, 1), (22, 2)]); ``` -------------------------------- ### Method: map_init Source: https://docs.rs/rayon/latest/rayon/iter/struct.WalkTreePostfix.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for the `map_init` method on `WalkTreePostfix`, which applies a mapping function with an initialized state to each item. ```APIDOC ## [method] map_init(self, init: INIT, map_op: F) -> MapInit ### Description Applies `map_op` to a value returned by `init` with each item of this iterator, producing a new iterator with the results. ### Signature `fn map_init(self, init: INIT, map_op: F) -> MapInit where F: Fn(&mut T, Self::Item) -> R + Sync + Send, INIT: Fn() -> T + Sync + Send, R: Send` ### Parameters - `init` (closure) - Required - A closure that returns a new `T` value for each parallel invocation. - `map_op` (closure) - Required - The mapping operation to apply with the mutable reference to the value and each item. ### Returns - `MapInit` - A new parallel iterator that yields the mapped results. ### Note This is a method of the `ParallelIterator` trait, available on `WalkTreePostfix`. ``` -------------------------------- ### take Source: https://docs.rs/rayon/latest/rayon/array/struct.IntoIter.html Creates an iterator that yields the first `n` elements. ```APIDOC ## take ### Description Creates an iterator that yields the first `n` elements. ### Method take ### Signature fn take(self, n: usize) -> Take ### Parameters - **n** (usize) - Required - The number of elements to take. ### Return Value - **Take** - An iterator that yields the first `n` elements. ``` -------------------------------- ### with_max_len example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets the maximum length of iterators processed in each rayon job. The example counts elements in a segment and asserts the maximum is at most 1234. ```rust use rayon::prelude::*; let max = (0..1_000_000) .into_par_iter() .with_max_len(1234) .fold(|| 0, |acc, _| acc + 1) // count how many are in this segment .max().unwrap(); assert!(max <= 1234); ``` -------------------------------- ### Minimal spawn_handler example Source: https://docs.rs/rayon/latest/rayon/struct.ThreadPoolBuilder.html A minimal `spawn_handler` that just spawns a thread and calls `run()`. The handler must return `Ok(())` or an error. This is the simplest way to build a pool with a custom thread spawner. ```rust fn main() -> Result<(), rayon::ThreadPoolBuildError> { let pool = rayon::ThreadPoolBuilder::new() .spawn_handler(|thread| { std::thread::spawn(|| thread.run()); Ok(()) }) .build()?; pool.install(|| println!("Hello from my custom thread!")); Ok(()) } ``` -------------------------------- ### interleave_shortest example Source: https://docs.rs/rayon/latest/rayon/iter/trait.IndexedParallelIterator.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Interleaves elements of two parallel iterators until one is exhausted. The example shows that the result stops when the shorter iterator is exhausted. ```rust use rayon::prelude::*; let (x, y) = (vec![1, 2, 3, 4], vec![5, 6]); let r: Vec = x.into_par_iter().interleave_shortest(y).collect(); assert_eq!(r, vec![1, 5, 2, 6, 3]); ```