token-cell 3.0.0

A more convenient GhostCell
Documentation
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use ::core::{
    cell::UnsafeCell,
    ops::{Deref, DerefMut},
};

trait MapLikely<T> {
    type Output<U>;
    fn map_likely<U, F: FnOnce(T) -> U>(self, f: F) -> Self::Output<U>;
}
#[cold]
const fn cold() {}
impl<T, E> MapLikely<T> for Result<T, E> {
    type Output<U> = Result<U, E>;
    fn map_likely<U, F: FnOnce(T) -> U>(self, f: F) -> Self::Output<U> {
        match self {
            Ok(v) => Ok(f(v)),
            Err(e) => {
                cold();
                Err(e)
            }
        }
    }
}

use crate::monads::{TokenMap, TokenMapMut};

/// A token that isn't intrinsically tied to a scope.
///
/// Most token types aren't, but some like [`GhostToken`] are.
pub trait UnscopedToken: TokenTrait {
    /// Constructing a token may fail.
    type ConstructionError;

    /// Constructs a new Token.
    ///
    /// # Errors
    /// Some token implementations may chose to be constructible only once, or only while holding a given lock.
    fn try_new() -> Result<Self, Self::ConstructionError>;

    /// Constructs a new Token. This method may be used instead of [`UnscopedToken::try_new`] when .
    fn new() -> Self
    where
        Self: UnscopedToken<ConstructionError = core::convert::Infallible>,
    {
        let Ok(this) = Self::try_new();
        this
    }
}

pub use sealed::{False, True};
pub(crate) mod sealed {
    pub trait Boolean {}
    /// A type that represents `true`.
    pub struct True;
    /// A type that represents `false`.
    pub struct False;
    impl Boolean for True {}
    impl Boolean for False {}
}

/// A trait for tokens
pub trait TokenTrait: Sized {
    /// Whether or not comparison between two distinct token could yield `eq`.
    ///
    /// This can be the case for tokens that can be constructed with [`UnscopedToken`] an arbitrary amount of times,
    /// but aren't guaranteed to have unique identifiers distinguishing them:
    /// - Instances of the types created by [`unsafe_token`](crate::unsafe_token), for example, are indistinguishable at both compile and runtime;
    ///   accidentally using two distinct instances to gain access to a same cell could cause undefined behaviour if done simultaneously.
    /// - Instances of the types created by [`runtime_token`](crate::runtime_token) are identified by a cyclic counter (`u16`` by default);
    ///   while unlikely, you could create two distinct instances with a same internal id by overflowing the static counter used to construct them.
    type ComparisonMaySpuriouslyEq: sealed::Boolean;

    /// [`TokenTrait::with_token`] may fail, typically if construction failed.
    ///
    /// Some types, like [`GhostToken`](crate::ghost::GhostToken) are inconstructible with [`UnscopedToken`], but cannot fail to run, hence the distinction.
    type RunError;

    /// Lets a [`TokenCell`] keep track of the token.
    ///
    /// In most cases, this is a ZST in release mode.
    type Identifier;

    /// [`core::convert::Infallible`] unless [`TokenTrait::compare`] is fallible (ie. comparison is done at runtime).
    type ComparisonError;

    /// Rebrands the token, this is necessary for [`GhostToken`](crate::ghost::GhostToken) to function properly
    type Branded<'a>;

    /// Constructs a new, lifetime-branded Token, and provides it to the closure.
    ///
    /// This is especially useful for [`GhostToken`](crate::ghost::GhostToken), which can only be constructed that way, as they use lifetimes to obtain a unique brand.
    ///
    /// # Errors
    /// If construction failed, so will this.
    fn with_token<R, F: for<'a> FnOnce(Self::Branded<'a>) -> R>(f: F) -> Result<R, Self::RunError>;

    /// Returns the Token's identifier, which cells may store to allow comparison.
    fn identifier(&self) -> Self::Identifier;

    /// Allows the cell to compare its identifier to the Token.
    ///
    /// # Errors
    /// If a wrong token was mistakenly passed to the cell.
    fn compare(&self, id: &Self::Identifier) -> Result<(), Self::ComparisonError>;
}

/// Common ways to interract with a [`TokenCell`].
///
/// Note that while many functions document fallihle behaviours, this behaviour is only reachable for tokens that perform runtime check. These are identifiable by their [`TokenTrait::ComparisonError`] type not being [`core::convert::Infallible`].
pub trait UnsafeTokenCellTrait<T: ?Sized, Token: TokenTrait<ComparisonMaySpuriouslyEq = True>>:
    Sync
{
    /// Attempts to construct a guard which [`Deref`]s to the inner data,
    /// but also allows recovering the `Token`.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    ///
    /// If such an error is ever raised, it should be treated as a high priority bug in your application,
    /// as that would indicate that the safety requirement was not met, but was detected before Undefined Behaviour
    /// could be triggered.
    unsafe fn try_guard<'l>(
        &'l self,
        token: &'l Token,
    ) -> Result<TokenGuard<'l, T, Token>, Token::ComparisonError>;

    /// Attempts to borrow the inner data.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    unsafe fn try_borrow<'l>(&'l self, token: &'l Token) -> Result<&'l T, Token::ComparisonError>;

    /// Attempts to construct a guard which [`DerefMut`]s to the inner data,
    /// but also allows recovering the `Token`.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    unsafe fn try_guard_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<TokenGuardMut<'l, T, Token>, Token::ComparisonError>;

    /// Attempts to borrow the inner data mutably.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    unsafe fn try_borrow_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<&'l mut T, Token::ComparisonError>;

    /// Borrows the inner data, panicking if the wrong token was used as key.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    unsafe fn borrow<'l>(&'l self, token: &'l Token) -> &'l T
    where
        Token::ComparisonError: core::fmt::Debug,
    {
        self.try_borrow(token).unwrap()
    }

    /// Borrows the inner data mutably, panicking if the wrong token was used as key.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    unsafe fn borrow_mut<'l>(&'l self, token: &'l mut Token) -> &'l mut T
    where
        Token::ComparisonError: core::fmt::Debug,
    {
        self.try_borrow_mut(token).unwrap()
    }

    /// Constructs a lazy computation that can then be applied using the token.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    unsafe fn map<'a, U, F: FnOnce(TokenGuard<'a, T, Token>) -> U>(
        &'a self,
        f: F,
    ) -> TokenMap<'a, T, U, F, Self, Token, True> {
        TokenMap {
            cell: self,
            f,
            marker: core::marker::PhantomData,
        }
    }

    /// Constructs a lazy computation that can then be applied using the token.
    ///
    /// # Safety
    /// `token` must refer to the _exact same_ instance of `Token` as that which was used to call [`Self::new`].
    unsafe fn map_mut<'a, U, F: FnOnce(TokenGuardMut<'a, T, Token>) -> U>(
        &'a self,
        f: F,
    ) -> TokenMapMut<'a, T, U, F, Self, Token, True> {
        TokenMapMut {
            cell: self,
            f,
            marker: core::marker::PhantomData,
        }
    }
}

/// Common ways to interract with a [`TokenCell`].
///
/// Note that while many functions document fallihle behaviours, this behaviour is only reachable for tokens that perform runtime check. These are identifiable by their [`TokenTrait::ComparisonError`] type not being [`core::convert::Infallible`].
pub trait TokenCellTrait<T: ?Sized, Token: TokenTrait<ComparisonMaySpuriouslyEq = False>> {
    /// Attempts to construct a guard which [`Deref`]s to the inner data,
    /// but also allows recovering the `Token`.
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    fn try_guard<'l>(
        &'l self,
        token: &'l Token,
    ) -> Result<TokenGuard<'l, T, Token>, Token::ComparisonError>;

    /// Attempts to borrow the inner data.
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    fn try_borrow<'l>(&'l self, token: &'l Token) -> Result<&'l T, Token::ComparisonError>;

    /// Attempts to construct a guard which [`DerefMut`]s to the inner data,
    /// but also allows recovering the `Token`.
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    fn try_guard_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<TokenGuardMut<'l, T, Token>, Token::ComparisonError>;

    /// Attempts to borrow the inner data mutably.
    ///
    /// # Errors
    /// If the token provides runtime checking and detects that `self` was constructed with another token.
    fn try_borrow_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<&'l mut T, Token::ComparisonError>;

    /// Borrows the inner data, panicking if the wrong token was used as key.
    fn borrow<'l>(&'l self, token: &'l Token) -> &'l T
    where
        Token::ComparisonError: core::fmt::Debug,
    {
        self.try_borrow(token).unwrap()
    }

    /// Borrows the inner data mutably, panicking if the wrong token was used as key.
    fn borrow_mut<'l>(&'l self, token: &'l mut Token) -> &'l mut T
    where
        Token::ComparisonError: core::fmt::Debug,
    {
        self.try_borrow_mut(token).unwrap()
    }

    /// Constructs a lazy computation that can then be applied using the token.
    fn map<'a, U, F: FnOnce(TokenGuard<'a, T, Token>) -> U>(
        &'a self,
        f: F,
    ) -> TokenMap<'a, T, U, F, Self, Token, False> {
        TokenMap {
            cell: self,
            f,
            marker: core::marker::PhantomData,
        }
    }

    /// Constructs a lazy computation that can then be applied using the token.
    fn map_mut<'a, U, F: FnOnce(TokenGuardMut<'a, T, Token>) -> U>(
        &'a self,
        f: F,
    ) -> TokenMapMut<'a, T, U, F, Self, Token, False> {
        TokenMapMut {
            cell: self,
            f,
            marker: core::marker::PhantomData,
        }
    }
}

/// A guard that allows immutably borrowing the cell's value, as well as its token.
pub struct TokenGuard<'a, T: ?Sized, Token: TokenTrait> {
    cell: &'a TokenCell<T, Token>,
    token: &'a Token,
}
impl<'a, T: ?Sized, Token: TokenTrait> TokenGuard<'a, T, Token> {
    /// Reborrows the token immutably.
    pub const fn token(&self) -> &Token {
        self.token
    }
}
impl<'a, T: ?Sized, Token: TokenTrait> Deref for TokenGuard<'a, T, Token> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        unsafe { &*self.cell.inner.get() }
    }
}

/// A guard that allows mutably borrowing the cell's value, as well as its token.
pub struct TokenGuardMut<'a, T: ?Sized, Token: TokenTrait> {
    cell: &'a TokenCell<T, Token>,
    token: &'a mut Token,
}
impl<'a, T: ?Sized, Token: TokenTrait> TokenGuardMut<'a, T, Token> {
    /// Reborrows the token immutably.
    pub const fn token(&self) -> &Token {
        self.token
    }
    /// Reborrows the token mutably.
    #[rustversion::attr(since(1.83), const)]
    pub fn token_mut(&mut self) -> &mut Token {
        self.token
    }
}
impl<'a, T: ?Sized, Token: TokenTrait> Deref for TokenGuardMut<'a, T, Token> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        unsafe { &*self.cell.inner.get() }
    }
}
impl<'a, T, Token: TokenTrait> core::ops::DerefMut for TokenGuardMut<'a, T, Token> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.cell.inner.get() }
    }
}

/// A Cell that shifts the management of access permissions to its inner value onto a `Token`.
pub struct TokenCell<T: ?Sized, Token: TokenTrait> {
    token_id: Token::Identifier,
    inner: UnsafeCell<T>,
}
impl<T: ?Sized, Token: TokenTrait> TokenCell<T, Token> {
    /// While cells are typically behind immutable references,
    /// obtaining a mutable reference to one is still proof of unique access.
    #[rustversion::attr(since(1.83), const)]
    pub fn get_mut(&mut self) -> &mut T {
        self.inner.get_mut()
    }
}
impl<T: Sized, Token: TokenTrait> TokenCell<T, Token> {
    /// Unwraps the value from the cell.
    ///
    /// Full ownership of the cell is sufficient proof that the inner value can be recovered.
    pub fn into_inner(self) -> T {
        self.inner.into_inner()
    }
}
impl<T: ?Sized, Token: TokenTrait> Deref for TokenCell<T, Token> {
    type Target = UnsafeCell<T>;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}
impl<T: ?Sized, Token: TokenTrait> DerefMut for TokenCell<T, Token> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

unsafe impl<T: ?Sized, Token: TokenTrait> Sync for TokenCell<T, Token> {}

impl<T: ?Sized, Token: TokenTrait<ComparisonMaySpuriouslyEq = True>> UnsafeTokenCellTrait<T, Token>
    for TokenCell<T, Token>
{
    unsafe fn try_guard<'l>(
        &'l self,
        token: &'l Token,
    ) -> Result<TokenGuard<'l, T, Token>, <Token as TokenTrait>::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| TokenGuard { cell: self, token })
    }
    unsafe fn try_borrow<'l>(&'l self, token: &'l Token) -> Result<&'l T, Token::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| unsafe { &*self.inner.get() })
    }
    unsafe fn try_guard_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<TokenGuardMut<'l, T, Token>, <Token as TokenTrait>::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| TokenGuardMut { cell: self, token })
    }

    unsafe fn try_borrow_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<&'l mut T, Token::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| unsafe { &mut *self.inner.get() })
    }
}

impl<T: ?Sized, Token: TokenTrait<ComparisonMaySpuriouslyEq = False>> TokenCellTrait<T, Token>
    for TokenCell<T, Token>
{
    fn try_guard<'l>(
        &'l self,
        token: &'l Token,
    ) -> Result<TokenGuard<'l, T, Token>, <Token as TokenTrait>::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| TokenGuard { cell: self, token })
    }
    fn try_borrow<'l>(&'l self, token: &'l Token) -> Result<&'l T, Token::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| unsafe { &*self.inner.get() })
    }
    fn try_guard_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<TokenGuardMut<'l, T, Token>, <Token as TokenTrait>::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| TokenGuardMut { cell: self, token })
    }

    fn try_borrow_mut<'l>(
        &'l self,
        token: &'l mut Token,
    ) -> Result<&'l mut T, Token::ComparisonError> {
        token
            .compare(&self.token_id)
            .map_likely(move |_| unsafe { &mut *self.inner.get() })
    }
}

impl<T, Token: TokenTrait> TokenCell<T, Token> {
    //// Constructs a new [`TokenCell`] keyed by `token`.
    ///
    /// All calls to [`UnsafeTokenCellTrait`] or [`TokenCellTrait`]'s methods on the returned value MUST use the same instance of `token`
    /// as passed to this constructor.
    pub fn new(value: T, token: &Token) -> Self {
        TokenCell {
            inner: UnsafeCell::new(value),
            token_id: token.identifier(),
        }
    }
}