-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathstack_once.rs
More file actions
40 lines (33 loc) · 997 Bytes
/
stack_once.rs
File metadata and controls
40 lines (33 loc) · 997 Bytes
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
use std::{cell::Cell, thread::LocalKey};
pub struct StackOnceToken {
active: &'static LocalKey<Cell<bool>>,
}
impl StackOnceToken {
#[doc(hidden)]
pub const fn new(active: &'static LocalKey<Cell<bool>>) -> StackOnceToken {
Self { active }
}
pub fn try_enter(&self) -> Option<StackOnceGuard> {
if self.active.get() {
None
} else {
self.active.set(true);
Some(StackOnceGuard(self.active))
}
}
}
pub struct StackOnceGuard(&'static LocalKey<Cell<bool>>);
impl Drop for StackOnceGuard {
fn drop(&mut self) {
self.0.set(false);
}
}
macro_rules! stack_once_token {
($name:ident) => {
static $name: $crate::stack_once::StackOnceToken = {
::std::thread_local! { static ACTIVE: ::core::cell::Cell<bool> = ::core::cell::Cell::new(false) }
$crate::stack_once::StackOnceToken::new(&ACTIVE)
};
};
}
pub(crate) use stack_once_token;