ndarray_parallel/
ext_traits.rs

1
2use ndarray::{
3    Dimension,
4    NdProducer,
5    Zip,
6    ArrayBase,
7    DataMut,
8};
9
10use prelude::*;
11
12// Arrays
13
14/// Parallel versions of `map_inplace` and `mapv_inplace`.
15pub trait ParMap {
16    type Item;
17    fn par_map_inplace<F>(&mut self, f: F)
18        where F: Fn(&mut Self::Item) + Sync + Send;
19    fn par_mapv_inplace<F>(&mut self, f: F)
20        where F: Fn(Self::Item) -> Self::Item + Sync + Send,
21              Self::Item: Clone;
22}
23
24impl<A, S, D> ParMap for ArrayBase<S, D>
25    where S: DataMut<Elem=A>,
26          D: Dimension,
27          A: Send + Sync,
28{
29    type Item = A;
30    fn par_map_inplace<F>(&mut self, f: F)
31        where F: Fn(&mut Self::Item) + Sync + Send
32    {
33        self.view_mut().into_par_iter().for_each(f)
34    }
35    fn par_mapv_inplace<F>(&mut self, f: F)
36        where F: Fn(Self::Item) -> Self::Item + Sync + Send,
37              Self::Item: Clone
38    {
39        self.view_mut().into_par_iter()
40            .for_each(move |x| *x = f(x.clone()))
41    }
42}
43
44
45
46
47// Zip
48
49macro_rules! zip_impl {
50    ($([$name:ident $($p:ident)*],)+) => {
51        $(
52        /// The `par_apply` method for `Zip`.
53        ///
54        /// This is a shorthand for using `.into_par_iter().for_each()` on
55        /// `Zip`.
56        pub trait $name<$($p),*> {
57            fn par_apply<F>(self, function: F)
58                where F: Fn($($p),*) + Sync + Send;
59        }
60
61        #[allow(non_snake_case)]
62        impl<Dim: Dimension, $($p: NdProducer<Dim=Dim>),*> $name<$($p::Item),*> for Zip<($($p,)*), Dim>
63            where $($p::Item : Send , )*
64                  $($p : Send , )*
65        {
66            fn par_apply<F>(self, function: F)
67                where F: Fn($($p::Item),*) + Sync + Send
68            {
69                self.into_par_iter().for_each(move |($($p,)*)| function($($p),*))
70            }
71        }
72        )+
73    }
74}
75
76zip_impl!{
77    [ParApply1 P1],
78    [ParApply2 P1 P2],
79    [ParApply3 P1 P2 P3],
80    [ParApply4 P1 P2 P3 P4],
81    [ParApply5 P1 P2 P3 P4 P5],
82    [ParApply6 P1 P2 P3 P4 P5 P6],
83}