snark_verifier/
util.rs

1//! Utilities.
2
3pub mod arithmetic;
4pub mod hash;
5pub mod msm;
6pub mod poly;
7pub mod transcript;
8
9pub(crate) use itertools::Itertools;
10
11#[cfg(feature = "parallel")]
12pub(crate) use rayon::current_num_threads;
13
14/// Parallelly executing the function on the items of the given iterator.
15pub fn parallelize_iter<I, T, F>(iter: I, f: F)
16where
17    I: Send + Iterator<Item = T>,
18    T: Send,
19    F: Fn(T) + Send + Sync + Clone,
20{
21    #[cfg(feature = "parallel")]
22    rayon::scope(|scope| {
23        for item in iter {
24            let f = f.clone();
25            scope.spawn(move |_| f(item));
26        }
27    });
28    #[cfg(not(feature = "parallel"))]
29    iter.for_each(f);
30}
31
32/// Parallelly executing the function on the given mutable slice.
33pub fn parallelize<T, F>(v: &mut [T], f: F)
34where
35    T: Send,
36    F: Fn((&mut [T], usize)) + Send + Sync + Clone,
37{
38    #[cfg(feature = "parallel")]
39    {
40        let num_threads = current_num_threads();
41        let chunk_size = v.len() / num_threads;
42        if chunk_size < num_threads {
43            f((v, 0));
44        } else {
45            parallelize_iter(v.chunks_mut(chunk_size).zip((0..).step_by(chunk_size)), f);
46        }
47    }
48    #[cfg(not(feature = "parallel"))]
49    f((v, 0));
50}