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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use std::prelude::v1::*;
use std::any::TypeId;
use std::hash::{BuildHasherDefault, Hasher};
use std::collections::HashMap;
use task;
#[macro_export]
macro_rules! task_local {
(static $NAME:ident: $t:ty = $e:expr) => (
static $NAME: $crate::task::LocalKey<$t> = {
fn __init() -> $t { $e }
fn __key() -> ::std::any::TypeId {
struct __A;
::std::any::TypeId::of::<__A>()
}
$crate::task::LocalKey {
__init: __init,
__key: __key,
}
};
)
}
pub struct LocalMap(HashMap<TypeId, Box<Opaque>, BuildHasherDefault<IdHasher>>);
pub fn local_map() -> LocalMap {
LocalMap(HashMap::default())
}
pub trait Opaque: Send {}
impl<T: Send> Opaque for T {}
#[derive(Debug)]
pub struct LocalKey<T> {
#[doc(hidden)]
pub __key: fn() -> TypeId,
#[doc(hidden)]
pub __init: fn() -> T,
}
pub struct IdHasher {
id: u64,
}
impl Default for IdHasher {
fn default() -> IdHasher {
IdHasher { id: 0 }
}
}
impl Hasher for IdHasher {
fn write(&mut self, _bytes: &[u8]) {
panic!("can only hash u64");
}
fn write_u64(&mut self, u: u64) {
self.id = u;
}
fn finish(&self) -> u64 {
self.id
}
}
impl<T: Send + 'static> LocalKey<T> {
pub fn get_mut<'a>(&'static self, cx: &'a mut task::Context) -> &'a mut T {
let key = (self.__key)();
let data = &mut cx.map.inner.0;
let entry: &mut Box<Opaque> = data.entry(key).or_insert_with(|| {
Box::new((self.__init)())
});
unsafe { &mut *(&mut **entry as *mut Opaque as *mut T) }
}
}