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;

/// A type of which there can only ever exist one value.
#[repr(transparent)]
pub struct StaticToken<'id>(PhantomData<fn(&'id ()) -> &'id ()>);

impl<'id> StaticToken<'id> {
    /// Calls the given function with a fresh, unique token that will never be
    /// used again.
    #[inline]
    pub fn acquire<R, F>(f: F) -> R
    where
        F: for<'new_id> FnOnce(StaticToken<'new_id>) -> R,
    {
        f(StaticToken(PhantomData))
    }
}

// SAFETY: All `StaticToken`s have fresh, unused lifetimes and so are unique
// types.
unsafe impl<'id> Unique for StaticToken<'id> {}

/// The runtime token is simultaneously acquired elsewhere.
#[derive(Debug)]
pub struct RuntimeTokenError;

/// Creates a token with a fresh type that is checked for uniqueness at runtime.
#[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 {
                /// Acquires the token.
                ///
                /// # Panics
                ///
                /// Panics if the token is still acquired elsewhere.
                #[inline]
                pub fn acquire() -> Self {
                    Self::try_acquire().unwrap()
                }

                /// Attempts to acquire the token.
                ///
                /// Returns an error if the token is still acquired elsewhere.
                #[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,
                        ),
                    }
                }
            }

            // SAFETY: `$name` can only be constructed by flipping `ALIVE` from
            // `false` to `true`, which can only happen one at a time.
            // Therefore, only one `$name` can exist at a time. The token will
            // flip it back to `false` when it is dropped, which destroys the
            // unique value.
            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);
    }
}