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
#[macro_export]
macro_rules! runtime_token {
($vis: vis $id: ident) => {
    $crate::paste! {
        $vis use [<__ $id _mod__ >]::$id;
        #[allow(nonstandard_style)]
        mod [<__ $id _mod__ >] {
            use core::{convert::Infallible, sync::atomic::AtomicU16};
            static COUNTER: AtomicU16 = AtomicU16::new(0);
            pub struct $id(u16);
            impl $crate::core::TokenTrait for $id {
                type ConstructionError = Infallible;
                type RunError = Infallible;
                type Identifier = u16;
                type ComparisonError = $crate::macros::IdMismatch;
                fn new() -> Result<Self, Self::ConstructionError> {
                    Ok($id(
                        COUNTER.fetch_add(1, core::sync::atomic::Ordering::Relaxed),
                    ))
                }
                fn with_token<R, F: FnOnce(Self)->R>(f: F) -> Result<R, Self::RunError> {
                    Self::new().map(f)
                }
                fn identifier(&self) -> Self::Identifier {
                    self.0
                }
                fn compare(&self, id: &Self::Identifier) -> Result<(), Self::ComparisonError> {
                    if self.0 == *id {
                        Ok(())
                    } else {
                        Err($crate::macros::IdMismatch {
                            cell: *id,
                            token: self.0,
                        })
                    }
                }
            }
        }
    }
};
($($vis: vis $id: ident),*) => {
    $($crate::runtime_token!($vis $id);)*
}
}

#[macro_export]
macro_rules! singleton_token {
($vis: vis $id: ident) => {
    $crate::paste! {
        $vis use [<__ $id _mod__ >]::$id;
        #[allow(nonstandard_style)]
        mod [<__ $id _mod__ >] {
            use core::{convert::Infallible, sync::atomic::AtomicBool};
            use $crate::SingletonUnavailable;
            static AVAILABLE: AtomicBool = AtomicBool::new(true);
            pub struct $id(());
            impl $crate::core::TokenTrait for $id {
                type ConstructionError = SingletonUnavailable;
                type RunError = SingletonUnavailable;
                type Identifier = ();
                type ComparisonError = Infallible;
                fn new() -> Result<Self, Self::ConstructionError> {
                    if AVAILABLE.swap(false, core::sync::atomic::Ordering::Relaxed) {
                        Ok($id(()))
                    } else {
                        Err(SingletonUnavailable)
                    }
                }
                fn with_token<R, F: FnOnce(Self)->R>(f: F) -> Result<R, Self::RunError> {
                    Self::new().map(f)
                }
                fn identifier(&self) -> Self::Identifier {
                    self.0
                }
                fn compare(&self, _: &Self::Identifier) -> Result<(), Self::ComparisonError> {
                    Ok(())
                }
            }
            impl ::core::ops::Drop for $id {
                fn drop(&mut self) {
                    AVAILABLE.store(true, core::sync::atomic::Ordering::Relaxed);
                }
            }
        }
    }
};
($($vis: vis $id: ident),*) => {
    $($crate::singleton_token!($vis $id);)*
}
}

#[macro_export]
macro_rules! unsafe_token {
($vis: vis $id: ident) => {
    $crate::paste! {
        $vis use [<__ $id _mod__ >]::$id;
        #[allow(nonstandard_style)]
        mod [<__ $id _mod__ >] {
            use core::convert::Infallible;
            pub struct $id(());
            impl $crate::core::TokenTrait for $id {
                type ConstructionError = Infallible;
                type RunError = Infallible;
                type Identifier = ();
                type ComparisonError = Infallible;
                fn new() -> Result<Self, Self::ConstructionError> {
                    Ok($id(()))
                }
                fn with_token<R, F: FnOnce(Self)->R>(f: F) -> Result<R, Self::RunError> {
                    Self::new().map(f)
                }
                fn identifier(&self) -> Self::Identifier {
                    self.0
                }
                fn compare(&self, _: &Self::Identifier) -> Result<(), Self::ComparisonError> {
                    Ok(())
                }
            }
        }
    }
};
($($vis: vis $id: ident),*) => {
    $($crate::unsafe_token!($vis $id);)*
}
}
pub use token::token;
#[cfg(any(feature = "debug", debug_assertions))]
mod token {
    pub use crate::runtime_token as token;
}
#[cfg(not(any(feature = "debug", debug_assertions)))]
mod token {
    pub use crate::unsafe_token as token;
}

#[derive(Debug, Clone, Copy)]
pub struct IdMismatch {
    pub cell: u16,
    pub token: u16,
}
impl ::core::fmt::Display for IdMismatch {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        write!(f, "{:?}", self)
    }
}
#[derive(Debug, Clone, Copy)]
pub struct SingletonUnavailable;
impl ::core::fmt::Display for SingletonUnavailable {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        write!(f, "{:?}", self)
    }
}