### Basic Example Source: https://docs.rs/rayon/1.12.0/rayon/iter/fn.walk_tree_prefix.html A simple example demonstrating the usage of `walk_tree_prefix` with integer nodes. ```APIDOC ## §Example ``` 4 / \ / \ 2 3 / \ 1 2 ``` ```rust use rayon::iter::walk_tree_prefix; use rayon::prelude::*; let par_iter = walk_tree_prefix(4, |&e| { if e <= 2 { Vec::new() } else { vec![e / 2, e / 2 + 1] } }); assert_eq!(par_iter.sum::(), 12); ``` ``` -------------------------------- ### walk_tree Ordering and Example Source: https://docs.rs/rayon/1.12.0/rayon/iter/fn.walk_tree.html Explains the ordering guarantees (or lack thereof) for walk_tree and provides an example of its usage. ```APIDOC ## §Ordering This function does not guarantee any ordering but will use whatever algorithm is thought to achieve the fastest traversal. See also `walk_tree_prefix` which guarantees a prefix order and `walk_tree_postfix` which guarantees a postfix order. ## §Example ``` 4 / \ / \ 2 3 / \ 1 2 ``` ```rust use rayon::iter::walk_tree; use rayon::prelude::*; let par_iter = walk_tree(4, |&e| { if e <= 2 { Vec::new() } else { vec![e / 2, e / 2 + 1] } }); assert_eq!(par_iter.sum::(), 12); ``` ``` -------------------------------- ### Handle Concurrent Execution with install() Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadPool.html Demonstrates how install() can lead to concurrent execution even with a single global thread, due to implicit yielding. The output order may vary. ```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()); } ``` -------------------------------- ### Basic walk_tree_postfix example Source: https://docs.rs/rayon/1.12.0/rayon/iter/fn.walk_tree_postfix.html This example demonstrates the basic usage of `walk_tree_postfix` with a simple numerical tree structure. It calculates the sum of all nodes in the tree. ```rust use rayon::iter::walk_tree_postfix; use rayon::prelude::*; let par_iter = walk_tree_postfix(4, |&e| { if e <= 2 { Vec::new() } else { vec![e / 2, e / 2 + 1] } }); assert_eq!(par_iter.sum::(), 12); ``` -------------------------------- ### Struct Node Example Source: https://docs.rs/rayon/1.12.0/rayon/iter/fn.walk_tree_prefix.html An example using a custom `Node` struct to demonstrate `walk_tree_prefix` with more complex data structures. ```APIDOC ## §Example ```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]); ``` ``` -------------------------------- ### Basic walk_tree_prefix example Source: https://docs.rs/rayon/1.12.0/rayon/iter/fn.walk_tree_prefix.html This example demonstrates the basic usage of `walk_tree_prefix` with a simple numeric tree. It calculates the sum of all nodes in the tree, verifying the prefix traversal order implicitly through the sum. ```rust use rayon::iter::walk_tree_prefix; use rayon::prelude::*; let par_iter = walk_tree_prefix(4, |&e| { if e <= 2 { Vec::new() } else { vec![e / 2, e / 2 + 1] } }); assert_eq!(par_iter.sum::(), 12); ``` -------------------------------- ### Execute Closure in ThreadPool using install() Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadPool.html The install() method executes a closure within one of the ThreadPool's threads. Any Rayon operations called within this closure will also operate within the context of this ThreadPool. Thread-local data from the calling thread is not accessible. ```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; } ``` -------------------------------- ### Execute Thread Main Loop Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadBuilder.html Starts the main loop for the thread. This method will not return until the ThreadPool is dropped. ```rust pub fn run(self) ``` -------------------------------- ### walk_tree Example Source: https://docs.rs/rayon/1.12.0/rayon/iter/fn.walk_tree.html Demonstrates creating a parallel iterator from a tree and summing its elements. The `children_of` function defines the tree structure. ```rust use rayon::iter::walk_tree; use rayon::prelude::*; let par_iter = walk_tree(4, |&e| { if e <= 2 { Vec::new() } else { vec![e / 2, e / 2 + 1] } }); assert_eq!(par_iter.sum::(), 12); ``` -------------------------------- ### walk_tree_postfix with custom Node struct Source: https://docs.rs/rayon/1.12.0/rayon/iter/fn.walk_tree_postfix.html This example shows how to use `walk_tree_postfix` with a custom `Node` struct. It collects the content of each node in postfix order. ```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]); ``` -------------------------------- ### scope_fifo Task Execution Example Source: https://docs.rs/rayon/1.12.0/rayon/fn.scope_fifo.html Illustrates the task execution order within a scope_fifo. Tasks spawned using spawn_fifo are processed in the order they are added to the scope. ```rust 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 ``` -------------------------------- ### Parallel Iteration Example Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.IntoParallelIterator.html Demonstrates parallel iteration over a range of numbers using into_par_iter(). This is useful for performing operations on each element of a sequence concurrently. ```rust use rayon::prelude::*; println!("counting in parallel:"); (0..100).into_par_iter() .for_each(|i| println!("{}", i)); ``` -------------------------------- ### Parallel Iteration Example Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.IntoParallelRefIterator.html Demonstrates summing elements of a vector in parallel using par_iter(). Verifies that par_iter() produces the same references as a manual into_par_iter() call. ```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))); ``` -------------------------------- ### Parallel Mutable Iteration Example Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.IntoParallelRefMutIterator.html Demonstrates how to use `par_iter_mut()` to get a parallel iterator yielding mutable references, then modifies elements in parallel. Ensure the `rayon::prelude::*` is imported. ```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]); ``` -------------------------------- ### Clone Implementation for TryFold Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.TryFold.html Allows cloning a TryFold iterator. This is useful for scenarios where you need to duplicate the iterator state, for example, to perform multiple operations on the same parallel iteration setup. ```rust impl Clone for TryFold ``` -------------------------------- ### Increment Global Counter with Rayon spawn Source: https://docs.rs/rayon/1.12.0/rayon/fn.spawn.html This example demonstrates spawning a Rayon task to increment a global atomic counter. Ensure the `std::sync::atomic` module is imported. ```rust use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; static GLOBAL_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; rayon::spawn(move || { GLOBAL_COUNTER.fetch_add(1, Ordering::SeqCst); }); ``` -------------------------------- ### Get Length of IndexedParallelIterator Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.IndexedParallelIterator.html Use the `len()` method to get the exact number of items an IndexedParallelIterator will produce. This is useful for pre-allocating collections or understanding the scope of parallel operations. ```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); ``` -------------------------------- ### init Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Cloned.html Initializes a with the given initializer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Implementing join using scope Source: https://docs.rs/rayon/1.12.0/rayon/fn.scope.html Demonstrates how the `join` function can be implemented using `scope` and `spawn`. This is less efficient than the native `join` implementation. ```rust pub fn join(oper_a: A, oper_b: B) -> (RA, RB) where A: FnOnce() -> RA + Send, B: FnOnce() -> RB + Send, RA: Send, RB: Send, { let mut result_a: Option = None; let mut result_b: Option = None; rayon::scope(|s| { s.spawn(|_| result_a = Some(oper_a())); s.spawn(|_| result_b = Some(oper_b())); }); (result_a.unwrap(), result_b.unwrap()) } ``` -------------------------------- ### type_id Source: https://docs.rs/rayon/1.12.0/rayon/collections/binary_heap/struct.IntoIter.html Gets the TypeId of self. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Returns The `TypeId` of the object. ``` -------------------------------- ### take Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Take.html Creates a ParallelIterator that yields the first `n` elements. ```APIDOC ## take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements. ### Parameters #### Path Parameters None #### Query Parameters - **n** (usize) - Required - The number of elements to take. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Take** - A new iterator that yields at most the first `n` elements. #### Response Example None ``` -------------------------------- ### take Source: https://docs.rs/rayon/1.12.0/rayon/collections/binary_heap/struct.Iter.html Creates an iterator that yields the first `n` elements. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Take** - An iterator that yields the first `n` elements. ``` -------------------------------- ### Any for T Source: https://docs.rs/rayon/1.12.0/rayon/slice/struct.IterMut.html Provides the `type_id` method to get the `TypeId` of `self`. ```APIDOC ## fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ``` -------------------------------- ### Folding elements within fixed-size chunks with initial value Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Chunks.html Use `fold_chunks_with` to split an iterator into fixed-size chunks and perform a sequential `fold()` operation on each chunk, starting with a provided initial value. This is an alternative to `fold_chunks` when you have a specific starting point for your fold. ```rust fn fold_chunks_with( self, chunk_size: usize, init: T, fold_op: F, ) -> FoldChunksWith where T: Send + Clone, F: Fn(T, Self::Item) -> T + Send + Sync, ``` -------------------------------- ### Parallel Quick Sort using join Source: https://docs.rs/rayon/1.12.0/rayon/fn.join.html Demonstrates a recursive quick-sort implementation using Rayon's `join` function to parallelize the sorting of sub-arrays. This example is for illustrative purposes and not an optimized sorting solution. ```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 } ``` -------------------------------- ### MapInit Method Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Positions.html Applies a closure with a newly initialized state for each thread to each item, producing a new iterator with the results. ```rust 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, ``` -------------------------------- ### deref Source: https://docs.rs/rayon/1.12.0/rayon/slice/struct.Iter.html Dereferences the given pointer to get an immutable reference. ```APIDOC ## unsafe fn deref<'a>(ptr: usize) -> &'a T ### Description Dereferences the given pointer to get an immutable reference. ### Safety This function is unsafe and requires `ptr` to be a valid pointer to an initialized object of type `T`. ### Parameters - **ptr** (usize) - The pointer to dereference. ### Returns An immutable reference `&'a T` to the object. ``` -------------------------------- ### init Source: https://docs.rs/rayon/1.12.0/rayon/collections/binary_heap/struct.IntoIter.html Initializes a with the given initializer. This is an unsafe operation. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Parameters * `init`: The initializer for the object. ### Returns The size in bytes of the initialized object. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Enumerate.html Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Parameters - `self`: A reference to the object. ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### From and Into Implementations Source: https://docs.rs/rayon/1.12.0/rayon/slice/struct.ChunksMut.html Enables conversion to and from other types. ```APIDOC fn from(t: T) -> T Returns the argument unchanged. fn into(self) -> U Calls `U::from(self)`. ``` -------------------------------- ### fn type_id(&self) -> TypeId Source: https://docs.rs/rayon/1.12.0/rayon/array/struct.IntoIter.html Gets the `TypeId` of `self`. ```APIDOC #### fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ``` -------------------------------- ### ThreadPoolBuilder::start_handler Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadPoolBuilder.html Sets a callback function to be invoked when a thread starts. ```APIDOC ## ThreadPoolBuilder::start_handler ### Description Sets a callback to be invoked on thread start. The closure is passed the index of the thread. ### Method `start_handler(self, start_handler: H) -> ThreadPoolBuilder` ### Parameters - **start_handler** (Fn(usize) + Send + Sync + 'static) - A closure that takes a `usize` (thread index) and is invoked on thread start. ``` -------------------------------- ### MapInit Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.ParallelIterator.html ParallelIterator implementation for MapInit. It initializes a state and then maps items using that state. ```APIDOC impl ParallelIterator for MapInit where I: ParallelIterator, INIT: Fn() -> T + Sync + Send, F: Fn(&mut T, I::Item) -> R + Sync + Send, R: Send, { type Item = R; } ``` -------------------------------- ### Parallel Iteration with Map and While Some Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.ParallelIterator.html Demonstrates parallel iteration, mapping elements, and short-circuiting with `while_some`. It also shows how to track the number of visited elements. ```rust use rayon::prelude::*; use std::sync::atomic::{AtomicUsize, Ordering}; let counter = AtomicUsize::new(0); let value = (0_i32..2048) .into_par_iter() .map(|x| { counter.fetch_add(1, Ordering::SeqCst); if x < 1024 { Some(x) } else { None } }) .while_some() .max(); assert!(value < Some(1024)); assert!(counter.load(Ordering::SeqCst) < 2048); // should not have visited every single one ``` -------------------------------- ### Length Information Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.MultiZip.html Method to get the exact number of items the iterator will produce. ```APIDOC ## len(&self) -> usize ### Description Produces an exact count of how many items this iterator will produce, presuming no panic occurs. ### Method `len` ``` -------------------------------- ### init Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.MinLen.html Initializes memory with the given initializer. This is an unsafe operation. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes memory with the given initializer. This is an unsafe operation. ### Parameters - **init** (`::Init`) - The initializer for the memory. ### Returns - `usize` - The pointer to the initialized memory. ``` -------------------------------- ### Length Information Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.MultiZip.html Method to get the exact number of elements the iterator will produce. ```APIDOC ## len(&self) -> usize ### Description Produces an exact count of how many items this iterator will produce, presuming no panic occurs. ### Method `len` ### Response - `usize`: The total number of items the iterator will yield. ``` -------------------------------- ### Create a scoped ThreadPool with thread-local data Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadPoolBuilder.html This example demonstrates building a scoped thread pool that can utilize thread-local storage. The `build_scoped` function allows a wrapper to set up thread-local data before executing a closure that uses the pool. ```rust scoped_tls::scoped_thread_local!(static POOL_DATA: Vec); fn main() -> Result<(), rayon::ThreadPoolBuildError> { let pool_data = vec![1, 2, 3]; // We haven't assigned any TLS data yet. assert!(!POOL_DATA.is_set()); rayon::ThreadPoolBuilder::new() .build_scoped( // Borrow `pool_data` in TLS for each thread. |thread| POOL_DATA.set(&pool_data, || thread.run()), // Do some work that needs the TLS data. |pool| pool.install(|| assert!(POOL_DATA.is_set())), )?; // Once we've returned, `pool_data` is no longer borrowed. drop(pool_data); Ok(()) } ``` -------------------------------- ### deref Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.MaxLen.html Dereferences the given pointer to get an immutable reference. This is an unsafe operation. ```APIDOC #### unsafe fn deref<'a>(ptr: usize) -> &'a T Dereferences the given pointer. Read more ``` -------------------------------- ### BroadcastContext Methods Source: https://docs.rs/rayon/1.12.0/rayon/struct.BroadcastContext.html Methods available on the BroadcastContext struct to get information about the broadcast operation. ```APIDOC ## BroadcastContext Provides context to a closure called by `broadcast`. ### Methods #### `fn index(&self) -> usize` Our index amongst the broadcast threads (ranges from `0..self.num_threads()`). #### `fn num_threads(&self) -> usize` The number of threads receiving the broadcast in the thread pool. ##### Future compatibility note Future versions of Rayon might vary the number of threads over time, but this method will always return the number of threads which are actually receiving your particular `broadcast` call. ``` -------------------------------- ### Parallel Drain Example with HashSet and BinaryHeap Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.ParallelDrainFull.html Demonstrates draining a BinaryHeap in parallel, asserting that all drained items are present in the original HashSet. The heap is guaranteed to be empty after draining, and its capacity will be at least the number of elements originally in the HashSet. ```rust use rayon::prelude::*; use std::collections::{BinaryHeap, HashSet}; let squares: HashSet = (0..10).map(|x| x * x).collect(); let mut heap: BinaryHeap<_> = squares.iter().copied().collect(); assert_eq!( // heaps are drained in arbitrary order heap.par_drain() .inspect(|x| assert!(squares.contains(x))) .count(), squares.len(), ); assert!(heap.is_empty()); assert!(heap.capacity() >= squares.len()); ``` -------------------------------- ### Get Thread Name Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadBuilder.html Retrieves the optional string name specified for this thread during ThreadPoolBuilder configuration. ```rust pub fn name(&self) -> Option<&str> ``` -------------------------------- ### enumerate Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.MultiZip.html Yields pairs of (index, item) for each element in the parallel iterator. The index starts from 0. ```APIDOC ## enumerate(self) -> Enumerate ### Description Yields an index along with each item. Read more ### Method `enumerate` ``` -------------------------------- ### try_from Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Cloned.html Performs the conversion. ```APIDOC ## fn try_from(value: U) -> Result>::Error> where U: Into, ### Description Performs the conversion. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Implementing ParallelExtend for a Custom Type Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.ParallelExtend.html An example demonstrating how to implement the `ParallelExtend` trait for a custom struct `BlackHole`. ```APIDOC ## §Examples Implementing `ParallelExtend` for your type: ```rust use rayon::prelude::*; struct BlackHole { mass: usize, } impl ParallelExtend for BlackHole { fn par_extend(&mut self, par_iter: I) where I: IntoParallelIterator { let par_iter = par_iter.into_par_iter(); self.mass += par_iter.count() * size_of::(); } } let mut bh = BlackHole { mass: 0 }; bh.par_extend(0i32..1000); assert_eq!(bh.mass, 4000); bh.par_extend(0i64..10); assert_eq!(bh.mass, 4080); ``` ``` -------------------------------- ### Implementing FromParallelIterator for a Custom Type Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.FromParallelIterator.html An example demonstrating how to implement the FromParallelIterator trait for a custom struct, BlackHole. ```APIDOC ## §Examples Implementing `FromParallelIterator` for your type: ```rust use rayon::prelude::*; struct BlackHole { mass: usize, } impl FromParallelIterator for BlackHole { fn from_par_iter(par_iter: I) -> Self where I: IntoParallelIterator { let par_iter = par_iter.into_par_iter(); BlackHole { mass: par_iter.count() * size_of::(), } } } let bh: BlackHole = (0i32..1000).into_par_iter().collect(); assert_eq!(bh.mass, 4000); ``` ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Enumerate.html Provides the `clone_to_uninit` method for nightly-only experimental cloning to uninitialized memory. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description 🔬 This is a nightly-only experimental API. Performs copy-assignment from `self` to `dest`. ### Parameters - `self`: A reference to the object to clone. - `dest`: A raw pointer to the destination memory location. ``` -------------------------------- ### Get Thread Stack Size Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadBuilder.html Retrieves the optional stack size specified for this thread during ThreadPoolBuilder configuration. ```rust pub fn stack_size(&self) -> Option ``` -------------------------------- ### into Source: https://docs.rs/rayon/1.12.0/rayon/collections/binary_heap/struct.IntoIter.html Calls U::from(self). ```APIDOC ## fn into(self) -> U ### Description Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ### Returns The converted value of type `U`. ``` -------------------------------- ### UniformBlocks Initialization Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.UniformBlocks.html Provides methods for initializing and managing objects within UniformBlocks. ```APIDOC ## init ### Description Initializes an object with the given initializer. ### Signature `unsafe fn init(init: ::Init) -> usize` ``` ```APIDOC ## deref ### Description Dereferences the given pointer to access the object. ### Signature `unsafe fn deref<'a>(ptr: usize) -> &'a T` ``` ```APIDOC ## deref_mut ### Description Mutably dereferences the given pointer to access the object. ### Signature `unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T` ``` ```APIDOC ## drop ### Description Drops the object pointed to by the given pointer. ### Signature `unsafe fn drop(ptr: usize)` ``` -------------------------------- ### filter_map Source: https://docs.rs/rayon/1.12.0/rayon/collections/btree_map/struct.Iter.html Applies `filter_op` to each item of this iterator to get an `Option`, producing a new iterator with only the items from `Some` results. ```APIDOC ## fn filter_map(self, filter_op: P) -> FilterMap ### Description Applies `filter_op` to each item of this iterator to get an `Option`, producing a new iterator with only the items from `Some` results. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ERROR HANDLING: None ``` -------------------------------- ### filter_map Source: https://docs.rs/rayon/1.12.0/rayon/collections/hash_map/struct.Iter.html Applies `filter_op` to each item of this iterator to get an `Option`, producing a new iterator with only the items from `Some` results. ```APIDOC ## fn filter_map(self, filter_op: P) -> FilterMap ### Description Applies `filter_op` to each item of this iterator to get an `Option`, producing a new iterator with only the items from `Some` results. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None ### Endpoint None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Step By Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Chunks.html Creates an iterator that steps by a specified amount. ```APIDOC ## fn step_by(self, step: usize) -> StepBy ### Description Creates an iterator that steps by the given amount. ### Parameters - `step`: The number of elements to step by. ### Returns A `StepBy` iterator. ``` -------------------------------- ### MapInit Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.IndexedParallelIterator.html Implementation of IndexedParallelIterator for MapInit. ```APIDOC ## impl IndexedParallelIterator for MapInit ### Description Provides parallel iteration capabilities for the MapInit struct. ### Type Parameters - `I`: The type of the indexed parallel iterator. - `INIT`: A function that returns an initial value of type `T`. - `T`: The type of the initial value, must be `Send` and `Sync`. - `F`: A function that takes a mutable reference to `T` and an item from `I` and returns a value of type `R`. - `R`: The type of the result, must be `Send`. ### Traits Requires `I: IndexedParallelIterator`, `INIT: Fn() -> T + Sync + Send`, `F: Fn(&mut T, I::Item) -> R + Sync + Send`, `R: Send`. ``` -------------------------------- ### par_rchunks_exact Source: https://docs.rs/rayon/1.12.0/rayon/slice/trait.ParallelSlice.html Returns a parallel iterator over `chunk_size` elements of `self` at a time, starting at the end. The chunks do not overlap. ```APIDOC ## par_rchunks_exact ### Description Returns a parallel iterator over `chunk_size` elements of `self` at a time, starting at the end. The chunks do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the remainder function of the iterator. ### Method `par_rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>` ``` -------------------------------- ### par_rchunks Source: https://docs.rs/rayon/1.12.0/rayon/slice/trait.ParallelSlice.html Returns a parallel iterator over at most `chunk_size` elements of `self` at a time, starting at the end. The chunks do not overlap. ```APIDOC ## par_rchunks ### Description Returns a parallel iterator over at most `chunk_size` elements of `self` at a time, starting at the end. The chunks do not overlap. If the number of elements in the iterator is not divisible by `chunk_size`, the last chunk may be shorter than `chunk_size`. All other chunks will have that exact length. ### Method `par_rchunks(&self, chunk_size: usize) -> RChunks<'_, T>` ### Examples ```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]]); ``` ``` -------------------------------- ### step_by Source: https://docs.rs/rayon/1.12.0/rayon/collections/binary_heap/struct.Iter.html Creates an iterator that steps by the given amount. ```APIDOC ## fn step_by(self, step: usize) -> StepBy ### Description Creates an iterator that steps by the given amount. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **StepBy** - An iterator that yields elements with the specified step. ``` -------------------------------- ### step_by Source: https://docs.rs/rayon/1.12.0/rayon/array/struct.IntoIter.html Creates an iterator that steps by the given amount. ```APIDOC ## step_by(self, step: usize) -> StepBy ### Description Creates an iterator that steps by the given amount. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature `fn step_by(self, step: usize) -> StepBy` ``` -------------------------------- ### walk_tree Source: https://docs.rs/rayon/1.12.0/rayon/iter/index.html Creates a tree-like parallel iterator from a root node, using a closure to define how to get child nodes. ```APIDOC ## walk_tree Create a tree like parallel iterator from an initial root node. The `children_of` function should take a node and iterate on all of its child nodes. The best parallelization is obtained when the tree is balanced but we should also be able to handle harder cases. ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/rayon/1.12.0/rayon/slice/struct.ChunksMut.html Supports fallible conversions to and from other types. ```APIDOC type Error = Infallible The type returned in the event of a conversion error. fn try_from(value: U) -> Result>::Error> Performs the conversion. type Error = >::Error The type returned in the event of a conversion error. fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### fold_with Source: https://docs.rs/rayon/1.12.0/rayon/str/struct.Split.html Performs a parallel fold operation starting with a given initial value, producing a single final result. ```APIDOC ## fn fold_with(self, init: T, fold_op: F) -> FoldWith ### Description Applies `fold_op` to the given `init` value with each item of this iterator, finally producing the value for further use. ### Parameters - `init` (T): The initial value for the fold. Must be `Send + Clone`. - `fold_op` (F): A closure that takes an accumulator and an item, returning the updated accumulator. Must be `Sync + Send`. - `T`: The type of the accumulator. Must be `Send + Clone`. ``` -------------------------------- ### par_rchunks_exact_mut Source: https://docs.rs/rayon/1.12.0/rayon/slice/trait.ParallelSliceMut.html Returns a parallel iterator over `chunk_size` elements of `self` at a time, starting at the end. The chunks are mutable and do not overlap. ```APIDOC ## fn par_rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> ### Description Returns a parallel iterator over `chunk_size` elements of `self` at a time, starting at the end. The chunks are mutable and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the remainder function of the iterator. ### Parameters #### Path Parameters - **chunk_size** (usize) - Required - The size of each chunk. ### Request Example ```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]); ``` ``` -------------------------------- ### Clone Implementation for FlatMap Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.FlatMap.html Details on how to clone a FlatMap instance. ```APIDOC ## Clone for FlatMap ### Methods - **`clone(&self) -> FlatMap`** Returns a duplicate of the value. - **`clone_from(&mut self, source: &Self)`** Performs copy-assignment from `source`. ``` -------------------------------- ### MapInit Method Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.TakeAnyWhile.html Applies a mapping function `map_op` with a mutable value created by `init` for each thread, producing a new iterator. `init` and `map_op` must be `Sync` and `Send`. ```rust 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, ``` -------------------------------- ### par_rchunks_mut Source: https://docs.rs/rayon/1.12.0/rayon/slice/trait.ParallelSliceMut.html Returns a parallel iterator over at most `chunk_size` elements of `self` at a time, starting at the end. The chunks are mutable and do not overlap. ```APIDOC ## par_rchunks_mut ### Description Returns a parallel iterator over at most `chunk_size` elements of `self` at a time, starting at the end. The chunks are mutable and do not overlap. If the number of elements in the iterator is not divisible by `chunk_size`, the last chunk may be shorter than `chunk_size`. All other chunks will have that exact length. ### Method `par_rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T>` ### Parameters * `chunk_size`: The desired size of each chunk. ### Examples ```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]); ``` ``` -------------------------------- ### fold_with Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.ExponentialBlocks.html Applies a folding operation to each item, starting with an initial value. This is a parallel version of the standard fold operation. ```APIDOC ## fn fold_with(self, init: T, fold_op: F) -> FoldWith ### Description Applies `fold_op` to the given `init` value with each item of this iterator, finally producing the value for further use. ### Method `fold_with` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let mut buffer = String::new(); (0..10).into_par_iter().fold_with(buffer, |mut acc, item| { acc.push_str(&item.to_string()); acc }); ``` ### Response #### Success Response (200) A `FoldWith` struct that accumulates results. #### Response Example None ``` -------------------------------- ### Parallel Range Summation with Rayon Source: https://docs.rs/rayon/1.12.0/rayon/range/index.html Demonstrates how to convert a standard Rust range into a parallel iterator and compute its sum. Ensure `rayon::prelude::*` is imported. ```rust use rayon::prelude::*; let r = (0..100u64).into_par_iter() .sum(); // compare result with sequential calculation assert_eq!((0..100).sum::(), r); ``` -------------------------------- ### CloneToUninit::clone_to_uninit Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.ZipEq.html Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ```APIDOC #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. Read more ``` -------------------------------- ### step_by Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.Take.html Creates a ParallelIterator that steps by the given amount. ```APIDOC ## step_by(self, step: usize) -> StepBy ### Description Creates an iterator that steps by the given amount. ### Parameters #### Path Parameters None #### Query Parameters - **step** (usize) - Required - The amount to step by. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **StepBy** - A new iterator that yields elements with the specified step. #### Response Example None ``` -------------------------------- ### Get Thread Index Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadBuilder.html Retrieves the index of the current thread within the thread pool, ranging from 0 to num_threads - 1. ```rust pub fn index(&self) -> usize ``` -------------------------------- ### Get Optional Length Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.UniformBlocks.html Internal method to determine the optional length of the parallel iterator. Not intended for direct user calls. ```APIDOC ## opt_len ### Description Internal method used to define the behavior of this parallel iterator. You should not need to call this directly. ### Signature ```rust fn opt_len(&self) -> Option ``` ``` -------------------------------- ### FlattenIter Initialization and Dereferencing Source: https://docs.rs/rayon/1.12.0/rayon/iter/struct.FlattenIter.html Provides methods for initializing, dereferencing, and mutably dereferencing FlattenIter objects. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes with the given initializer. ### Parameters * **init** (::Init) - Description of the initializer. ### Returns * usize - The pointer to the initialized object. ``` ```APIDOC ## unsafe fn deref<'a>(ptr: usize) -> &'a T ### Description Dereferences the given pointer to provide immutable access to the object. ### Parameters * **ptr** (usize) - The pointer to the object to dereference. ### Returns * &'a T - An immutable reference to the object. ``` ```APIDOC ## unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T ### Description Mutably dereferences the given pointer to provide mutable access to the object. ### Parameters * **ptr** (usize) - The pointer to the object to mutably dereference. ### Returns * &'a mut T - A mutable reference to the object. ``` ```APIDOC ## unsafe fn drop(ptr: usize) ### Description Drops the object pointed to by the given pointer, releasing its resources. ### Parameters * **ptr** (usize) - The pointer to the object to drop. ``` -------------------------------- ### walk_tree_prefix Source: https://docs.rs/rayon/1.12.0/rayon/iter/index.html Creates a tree-like prefix parallel iterator from a root node, using a closure to define how to get child nodes. ```APIDOC ## walk_tree_prefix Create a tree-like prefix parallel iterator from an initial root node. The `children_of` function should take a node and return an iterator over its child nodes. The best parallelization is obtained when the tree is balanced but we should also be able to handle harder cases. ``` -------------------------------- ### Take elements with a shared mutable quota in parallel Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.ParallelIterator.html This example demonstrates using `take_any_while` with an `AtomicUsize` to limit the total sum of collected items. The `fetch_update` operation ensures thread-safe decrements of the quota. ```rust use rayon::prelude::* use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; // Collect any group of items that sum <= 1000 let quota = AtomicUsize::new(1000); let result: Vec<_> = (0_usize..100) .into_par_iter() .take_any_while(|&x| { quota.fetch_update(Relaxed, Relaxed, |q| q.checked_sub(x)) .is_ok() }) .collect(); let sum = result.iter().sum::(); assert!(matches!(sum, 902..=1000)); ``` -------------------------------- ### scope Source: https://docs.rs/rayon/1.12.0/rayon/struct.ThreadPool.html Creates a scope for executing closures within the thread pool. This is equivalent to calling `self.install(|| scope(...))`. ```APIDOC ## scope ### Description Creates a scope that executes within this thread pool. Equivalent to `self.install(|| scope(...))`. See also: the `scope()` function. ### Method `scope<'scope, OP, R>(&self, op: OP) -> R` ### Type Parameters - `'scope`: Lifetime parameter for the scope. - `OP`: `FnOnce(&Scope<'scope>) -> R + Send` - `R`: `Send` ``` -------------------------------- ### walk_tree_postfix Source: https://docs.rs/rayon/1.12.0/rayon/iter/index.html Creates a tree-like postfix parallel iterator from a root node, using a closure to define how to get child nodes. ```APIDOC ## walk_tree_postfix Create a tree like postfix parallel iterator from an initial root node. The `children_of` function should take a node and iterate on all of its child nodes. The best parallelization is obtained when the tree is balanced but we should also be able to handle harder cases. ``` -------------------------------- ### RChunks Source: https://docs.rs/rayon/1.12.0/rayon/slice/struct.RChunks.html RChunks is a parallel iterator over immutable non-overlapping chunks of a slice, starting at the end. It is part of the rayon::slice module. ```APIDOC ## Struct RChunks ```rust pub struct RChunks<'data, T> { /* private fields */ } ``` Parallel iterator over immutable non-overlapping chunks of a slice, starting at the end. ``` -------------------------------- ### Skip elements Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.IndexedParallelIterator.html Creates an iterator that skips the first `n` elements. Useful for processing data starting from a specific offset. ```rust use rayon::prelude::*; let result: Vec<_> = (0..100) .into_par_iter() .skip(95) .collect(); assert_eq!(result, [95, 96, 97, 98, 99]); ``` -------------------------------- ### take_any Source: https://docs.rs/rayon/1.12.0/rayon/iter/trait.ParallelIterator.html Creates an iterator that yields the first `n` elements of this iterator. ```APIDOC ## take_any ### Description Creates an iterator that yields the first `n` elements of this iterator. ### Signature ```rust fn take_any(self, n: usize) -> TakeAny ``` ```