Repository navigation
Expand file tree
/
Copy pathpar.rs
More file actions
72 lines (66 loc) · 2.34 KB
/
Copy pathpar.rs
File metadata and controls
72 lines (66 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! Optional data parallelism (rayon behind the `threads` feature; sequential otherwise and on
//! wasm32).
#[cfg(feature = "threads")]
use std::sync::Arc;
/// A handle to the decoder's worker pool (or none: run on the calling thread).
#[derive(Clone, Default)]
pub(crate) struct Pool {
#[cfg(feature = "threads")]
pool: Option<Arc<rayon::ThreadPool>>,
}
impl Pool {
/// A pool of `threads` workers (sequential when `threads` <= 1, without the `threads`
/// feature, or on wasm32).
pub fn new(threads: usize) -> Pool {
#[cfg(feature = "threads")]
{
let pool = if threads > 1 && cfg!(not(target_arch = "wasm32")) {
rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("av1-{i}")).build().ok().map(Arc::new)
} else {
None
};
Pool { pool }
}
#[cfg(not(feature = "threads"))]
{
let _ = threads;
Pool {}
}
}
pub fn is_parallel(&self) -> bool {
#[cfg(feature = "threads")]
{
self.pool.is_some()
}
#[cfg(not(feature = "threads"))]
{
false
}
}
/// `f(i, &mut items[i])` for every item, in parallel when possible; results in order.
pub fn map_mut<T: Send, R: Send>(&self, items: &mut [T], f: impl Fn(usize, &mut T) -> R + Sync + Send) -> Vec<R> {
#[cfg(feature = "threads")]
if let Some(pool) = &self.pool
&& items.len() > 1
{
use rayon::prelude::*;
return pool.install(|| items.par_iter_mut().enumerate().map(|(i, t)| f(i, t)).collect());
}
items.iter_mut().enumerate().map(|(i, t)| f(i, t)).collect()
}
/// `f(i, chunk)` for the consecutive `chunk_len`-element chunks of `data`.
pub fn chunks<T: Send>(&self, data: &mut [T], chunk_len: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) {
let chunk_len = chunk_len.max(1);
#[cfg(feature = "threads")]
if let Some(pool) = &self.pool
&& data.len() > chunk_len
{
use rayon::prelude::*;
pool.install(|| data.par_chunks_mut(chunk_len).enumerate().for_each(|(i, c)| f(i, c)));
return;
}
for (i, c) in data.chunks_mut(chunk_len).enumerate() {
f(i, c);
}
}
}