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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use std::cell::Cell;
use std::fmt;
use std::mem::ManuallyDrop;
use std::ptr;
use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
use std::sync::Arc;
use super::utils::abort_on_panic;
use super::LocalsMap;
thread_local! {
static CURRENT: Cell<*const Karx> = Cell::new(ptr::null_mut());
}
struct Inner {
id: KarxId,
name: Option<Box<str>>,
locals: LocalsMap,
}
impl Inner {
#[inline]
fn new(name: Option<String>) -> Inner {
Inner {
id: KarxId::generate(),
name: name.map(String::into_boxed_str),
locals: LocalsMap::new(),
}
}
}
pub struct Karx {
inner: AtomicPtr<Inner>,
}
unsafe impl Send for Karx {}
unsafe impl Sync for Karx {}
impl Karx {
#[inline]
pub(crate) fn new(name: Option<String>) -> Karx {
let inner = match name {
None => AtomicPtr::default(),
Some(name) => {
let raw = Arc::into_raw(Arc::new(Inner::new(Some(name))));
AtomicPtr::new(raw as *mut Inner)
}
};
Karx { inner }
}
#[inline]
pub fn id(&self) -> KarxId {
self.inner().id
}
pub fn name(&self) -> Option<&str> {
self.inner().name.as_ref().map(|s| &**s)
}
pub(crate) fn locals(&self) -> &LocalsMap {
&self.inner().locals
}
#[inline]
pub(crate) unsafe fn drop_locals(&self) {
let raw = self.inner.load(Ordering::Acquire);
if let Some(inner) = raw.as_mut() {
abort_on_panic(|| {
inner.locals.clear();
});
}
}
fn inner(&self) -> &Inner {
loop {
let raw = self.inner.load(Ordering::Acquire);
if !raw.is_null() {
return unsafe { &*raw };
}
let new = Arc::into_raw(Arc::new(Inner::new(None))) as *mut Inner;
if self.inner.compare_and_swap(raw, new, Ordering::AcqRel) != raw {
unsafe {
drop(Arc::from_raw(new));
}
}
}
}
pub(crate) unsafe fn set_current<F, R>(karx: *const Karx, f: F) -> R
where
F: FnOnce() -> R,
{
CURRENT.with(|current| {
let old_karx = current.replace(karx);
defer! {
current.set(old_karx);
}
f()
})
}
pub(crate) fn get_current<F, R>(f: F) -> Option<R>
where
F: FnOnce(&Karx) -> 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 Karx {
fn drop(&mut self) {
let raw = *self.inner.get_mut();
if !raw.is_null() {
unsafe {
drop(Arc::from_raw(raw));
}
}
}
}
impl Clone for Karx {
fn clone(&self) -> Karx {
let arc = unsafe { ManuallyDrop::new(Arc::from_raw(self.inner())) };
let raw = Arc::into_raw(Arc::clone(&arc));
Karx {
inner: AtomicPtr::new(raw as *mut Inner),
}
}
}
impl fmt::Debug for Karx {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Karx")
.field("id", &self.id())
.field("name", &self.name())
.finish()
}
}
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
pub struct KarxId(pub(crate) u64);
impl KarxId {
pub(crate) fn generate() -> KarxId {
static COUNTER: AtomicU64 = AtomicU64::new(1);
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
if id > u64::max_value() / 2 {
std::process::abort();
}
KarxId(id)
}
}
impl fmt::Display for KarxId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}