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
use ::core::marker::PhantomData;
use crate::Unique;
#[repr(transparent)]
pub struct StaticToken<'id>(PhantomData<fn(&'id ()) -> &'id ()>);
impl<'id> StaticToken<'id> {
#[inline]
pub fn acquire<R, F>(f: F) -> R
where
F: for<'new_id> FnOnce(StaticToken<'new_id>) -> R,
{
f(StaticToken(PhantomData))
}
}
unsafe impl<'id> Unique for StaticToken<'id> {}
#[derive(Debug)]
pub struct RuntimeTokenError;
#[macro_export]
macro_rules! runtime_token {
($name:ident) => {
$crate::runtime_token!(@impl $name);
};
(pub $name:ident) => {
$crate::runtime_token!(@impl $name pub);
};
(pub ($($vis:tt)*) $name:ident) => {
$crate::runtime_token!(@impl $name pub($($vis)*));
};
(@impl $name:ident $($vis:tt)*) => {
#[repr(transparent)]
$($vis)* struct $name(::core::marker::PhantomData<()>);
const _: () = {
static ALIVE: ::core::sync::atomic::AtomicBool =
::core::sync::atomic::AtomicBool::new(false);
impl Drop for $name {
#[inline]
fn drop(&mut self) {
ALIVE.compare_exchange(
true,
false,
::core::sync::atomic::Ordering::AcqRel,
::core::sync::atomic::Ordering::Acquire,
).unwrap();
}
}
impl $name {
#[inline]
pub fn acquire() -> Self {
Self::try_acquire().unwrap()
}
#[inline]
pub fn try_acquire() ->
::core::result::Result<Self, $crate::RuntimeTokenError>
{
let result = ALIVE.compare_exchange(
false,
true,
::core::sync::atomic::Ordering::AcqRel,
::core::sync::atomic::Ordering::Acquire,
);
match result {
Ok(_) => ::core::result::Result::Ok(
$name(::core::marker::PhantomData),
),
Err(_) => ::core::result::Result::Err(
$crate::RuntimeTokenError,
),
}
}
}
unsafe impl $crate::Unique for $name {}
};
};
}
#[cfg(test)]
mod tests {
use crate::Unique;
#[inline]
fn assert_unique<T: Unique>() {}
#[test]
fn static_token() {
use crate::StaticToken;
StaticToken::acquire(|_: StaticToken| {
assert_unique::<StaticToken>();
});
}
#[test]
fn runtime_token() {
runtime_token!(Foo);
assert_unique::<Foo>();
let foo: Foo = Foo::acquire();
assert!(matches!(Foo::try_acquire(), Err(_)));
drop(foo);
assert!(matches!(Foo::try_acquire(), Ok(_)));
}
#[test]
#[should_panic]
fn runtime_token_duplicate() {
runtime_token!(Foo);
assert_unique::<Foo>();
let foo: Foo = Foo::acquire();
let bar: Foo = Foo::acquire();
drop(foo);
drop(bar);
}
}