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
77
78
79
80
81
82
83
84
use std::cell::Cell;
use std::ptr;
use crate::task::{LocalsMap, Task, TaskId};
use crate::utils::abort_on_panic;
thread_local! {
static CURRENT: Cell<*const TaskLocalsWrapper> = Cell::new(ptr::null_mut());
}
pub(crate) struct TaskLocalsWrapper {
task: Task,
locals: LocalsMap,
}
impl TaskLocalsWrapper {
#[inline]
pub(crate) fn new(task: Task) -> Self {
Self {
task,
locals: LocalsMap::new(),
}
}
#[inline]
pub fn id(&self) -> TaskId {
self.task.id()
}
pub(crate) fn task(&self) -> &Task {
&self.task
}
pub(crate) fn locals(&self) -> &LocalsMap {
&self.locals
}
pub(crate) unsafe fn set_current<F, R>(task: *const TaskLocalsWrapper, f: F) -> R
where
F: FnOnce() -> R,
{
CURRENT.with(|current| {
let old_task = current.replace(task);
defer! {
current.set(old_task);
}
f()
})
}
pub(crate) fn get_current<F, R>(f: F) -> Option<R>
where
F: FnOnce(&TaskLocalsWrapper) -> R,
{
let res = CURRENT.try_with(|current| unsafe { current.get().as_ref().map(f) });
match res {
Ok(Some(val)) => Some(val),
Ok(None) | Err(_) => None,
}
}
}
impl Drop for TaskLocalsWrapper {
fn drop(&mut self) {
abort_on_panic(|| {
unsafe { self.locals.clear() };
});
}
}