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
73
74
75
76
#![allow(unsafe_code)]
#![deny(missing_docs)]
use rayon;
use std::cell::{Ref, RefCell, RefMut};
use std::ops::DerefMut;
pub struct ScopedTLS<'scope, T: Send> {
pool: &'scope rayon::ThreadPool,
slots: Box<[RefCell<Option<T>>]>,
}
unsafe impl<'scope, T: Send> Sync for ScopedTLS<'scope, T> {}
impl<'scope, T: Send> ScopedTLS<'scope, T> {
pub fn new(p: &'scope rayon::ThreadPool) -> Self {
let count = p.current_num_threads();
let mut v = Vec::with_capacity(count);
for _ in 0..count {
v.push(RefCell::new(None));
}
ScopedTLS {
pool: p,
slots: v.into_boxed_slice(),
}
}
pub fn borrow(&self) -> Ref<Option<T>> {
let idx = self.pool.current_thread_index().unwrap();
self.slots[idx].borrow()
}
pub fn borrow_mut(&self) -> RefMut<Option<T>> {
let idx = self.pool.current_thread_index().unwrap();
self.slots[idx].borrow_mut()
}
#[inline(always)]
pub fn ensure<F: FnOnce(&mut Option<T>)>(&self, f: F) -> RefMut<T> {
let mut opt = self.borrow_mut();
if opt.is_none() {
f(opt.deref_mut());
}
RefMut::map(opt, |x| x.as_mut().unwrap())
}
pub unsafe fn unsafe_get(&self) -> &[RefCell<Option<T>>] {
&self.slots
}
}