Rayon Parallel Map

Map a slice in parallel with Rayon, turning a sequential iteration into work-stealing parallelism.

RustData Integrity

Code

snippet
use rayon::prelude::*;

/// Sum of squares, computed across all available worker threads.
pub fn sum_of_squares(values: &[i64]) -> i64 {
    values.par_iter().map(|value| value.saturating_mul(*value)).sum()
}

/// Transform each element in place, preserving order in the result.
pub fn transform(value: &mut [i64], factor: i64) {
    value.par_iter_mut().for_each(|slot| {
        *slot = slot.checked_mul(factor).unwrap_or(*slot);
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn squares_match_sequential() {
        let data: Vec<i64> = (1..=1000).collect();
        let expected: i64 = data.iter().map(|v| v * v).sum();
        assert_eq!(sum_of_squares(&data), expected);
    }
}