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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! Manual memory management, with a reasonable API and fewer footguns
//!
//! [`Ptr`] is a halfway house between `Box` and `*mut T`.
//! See its documentation for the details of the API.
//!
//! We aim to reproduce roughly the division of responsibility
//! (between programmer and compiler)
//! found in C.
//!
//! ### Caller responsibilities
//!
//!  * Knowing which data is still live, freeing it as and when needed,
//!    and not freeing it too soon.
//!    Not accessing freed data.
//!
//!  * Not defeating the library's anti-alias protections.
//!    In particular: holding a suitable singleton ([`NoAliasSingleton`])
//!    which each `Ptr` belongs to
//!    (even though there is nothing in the API
//!    eg, lifetimes, to link them).
//!
//! ### Library responsibilities
//!
//!  * Following Rust's aliasing rules,
//!    which are (for our purposes) stricter than C's.
//!    This library aims to prevent accidental creation
//!    of overlapping `&mut`, for example.
//!
//!  * Threadsafety; `Send` and `Sync`.
//!    (The caller must still make sure not to free an object
//!    that another thread may be using, of course.)
//!
//!  * Soundness in the face of panics, including panics from methods
//!    of the contained type `T`, eg `T`'s `Drop` impl.
//!
//!  * "`Drop` footguns", and the like, which lurk in Unsafe Rust.
//!
//! ### Soundness
//!
//! This library aims to be sound in the usual Rust sense.
//! That is, you should not be able to produce UB
//! without calling `unsafe` functions and writing buggy code.
//!
//! **However**, it is impossible to use this library
//! without making calls to unsafe functions.
//! And the invariants and rules for the unsafe entrypoints,
//! are more global, and arguably harder to uphold,
//! than is usual for a Rust API.
//!
//! In practice this means that in a real program,
//! memory-safety is likely to depend on the correctness
//! of much nominally "safe" code.
//! The rules have been chosen pragmatically,
//! to minimise the proportion of the caller that needs
//! to be *actually marked* with `unsafe`.
//! But in practice, much of a caller's code
//! will be able to violate invariants and cause UB.
//!
//! You cannot sensibly pass `Ptr` to naive, safe, code.
//! If you want to provide a conventionally safe and sound API,
//! you must wrap up your entire data structure,
//! hiding all of this library's types.

#[cfg(test)]
mod test;

use std::collections::HashSet;
use std::fmt::{self, Debug, Display};
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;

//---------- public types ----------

/// **Pointer to manually-memory-managed `T`**
///
/// `Ptr<T>` usually refers to an item on the heap, like `Box<T>`.
/// It can be made from `T` with [`Ptr::new_heap()`],
/// or [`From<Box>`](#impl-From%3CBox%3CT%3E%3E-for-Ptr%3CT%3E).
/// It is then freed again with [`.free_heap()`](Ptr::free_heap).
///
/// To access the contained data use,
/// [`Ptr::borrow()`]
/// and
/// [`borrow_mut()`](Ptr::borrow_mut).
///
/// To mutably access the data of more than one node at once,
/// use
/// [`IsTokenMut::multi_static`]
/// or
/// [`IsTokenMut::multi_dynamic`].
/// To avoid runtime aliasing checks, and take manual control of aliasing,
/// you can
/// [`.borrow_mut()`](Ptr::borrow_mut()) with
/// [`TokenMut::new_unchecked()`];
/// or,
/// `p`[`.as_ptr()`](Ptr::as_ptr)[`.as_ref()`](NonNull::as_ref())
/// /
/// `p`[`.as_ptr()`](Ptr::as_ptr)[`.as_mut()`](NonNull::as_mut()).
///
/// This type is `Copy`.  Copying it (or, indeed, cloning it)
/// does not copy the underlying data.
/// Nor is there any reference counting or garbage collection.
///
/// Ensuring that `Ptr`s are freed at the right time is up to the caller,
/// But aliasing, and other Rust unsafe footguns,
/// are (largely) handled by the library.
/// See the [module-level documentation](crate).
pub struct Ptr<T: ?Sized> {
    /// # SAFETY
    ///
    /// Invariants (only while valid, but we can rely on them
    /// since our caller is not allowed to call any of our methods
    /// on an invalid Ptr):
    ///
    ///  * Always points to a valid T on the heap: was `Box<T>`.
    ///  * All references given out are compatible with the borrow
    ///   of the `NoAliasSingleton` (possibly via `IsTokenRef`
    ///   or `IsTokenMut`.
    //
    // Variance: covariant, which is right according to the rules (see
    // docs for NonNull) since we *do* provide the usual shared XOR
    // mutable.
    ptr: NonNull<T>,
}

unsafe impl<T: Sync + ?Sized> Sync for Ptr<T> {}
unsafe impl<T: Send + ?Sized> Send for Ptr<T> {}

/// Singleton, used for compile-time alias checking
///
/// You'll need one owned one of these, from
/// [`NoAliasSingleton::init()`].
///
/// Typically, instead of passing `&mut NoAliasSingleton`
/// to your own sub-functions,
/// you'll pass [`TokenMut`] (or [`TokenRef`],
/// which can be obtained (and copied)
/// with
/// [`IsTokenRef::token_ref`]
/// and
/// [`IsTokenMut::token_mut`].
///
/// Those token types are zero-sized types,
/// so they incur no runtime cost,
/// even if the compiler can't figure out that
/// they aren't ever used.
///
/// (`NoAliasSingleton` is a ZST too,
/// but of course `&mut NoAliasSingleton` isn't.)
#[derive(Debug)] // Not Clone or Copy
#[non_exhaustive] // unsafe to construct
pub struct NoAliasSingleton {
}

/// `&`[`NoAliasSingleton`], but zero-sized
///
/// We don't actually ever need to look at the data for the singleton.
/// So the actual pointer is redundant, and, here, absent.
#[derive(Debug, Clone, Copy)]
pub struct TokenRef<'a>(
    PhantomData<&'a NoAliasSingleton>,
);

/// `&mut` [`NoAliasSingleton`], but zero-sized
///
/// See [`TokenRef`]
#[derive(Debug)]
pub struct TokenMut<'a>(
    PhantomData<&'a mut NoAliasSingleton>,
);

impl<'a> TokenMut<'a> {
    /// Allows borrowing on the caller's recognisance
    ///
    /// This will let you call
    /// [`Ptr::borrow()`]/[`borrow_mut()`](Ptr::borrow_mut)
    /// multiple times, retaining and using all the resulting references.
    ///
    /// For another approach,
    /// see [`Ptr::as_ptr()`].
    ///
    /// # SAFETY
    ///
    /// The calls to `borrow[_mut]` that this enables must not violate
    /// Rust's rules.  Checking that is up to you.
    ///
    /// So, all of the `Ptr` you `borrow_mut` must be distinct,
    /// and they must be distinct from your `borrow`s.
    /// Violating this rule is instant undefined behaviour,
    /// even if you never read or write the resulting reference(s).
    /// 
    /// Also, it is up to you to make sure you don't free the data to soon.
    pub unsafe fn new_unchecked() -> Self { TokenMut(PhantomData) }
}

//---------- IsTokenRef and IsTokenMut traits ----------

/// Token-like: `&self` implies `&NoAliasSingleton`
///
/// Implemented for `NoAliasSingleton` and the ZST reference tokens,
/// and `&`-references to them.
pub unsafe trait IsTokenRef<'a>: Sized + Sealed {
    /// Obtains a new ZST token from something that might be a real object.
    #[inline]
    fn token_ref(self) -> TokenRef<'a> {
        TokenRef(PhantomData)
    }
}

/// Token-like: `&mut self` implies `&mut NoAliasSingleton`
///
/// Implemented for `NoAliasSingleton` and `TokenMut`,
/// and `&mut`-references to them.
pub unsafe trait IsTokenMut<'a>: IsTokenRef<'a> + Sized + Sealed {
    /// Obtains a new ZST token from something that might be a real object.
    #[inline]
    fn token_mut<'r>(self) -> TokenMut<'r> where 'a: 'r {
        TokenMut(PhantomData)
    }

    /// Obtains a new ZST token from a borrow that might be of a real object.
    #[inline]
    fn as_mut<'r, 's: 'r>(&'s mut self) -> TokenMut<'r> where 'a: 'r {
        TokenMut(PhantomData)
    }

    /// Borrows from a small, fixed, number of multiple `Ptr`
    ///
    /// Call
    /// [`.borrow`](MultiStatic::borrow)
    /// and
    /// [`.borrow_mut`](MultiStatic::borrow)
    /// to obtain real references from multiple `Ptr`s.
    ///
    /// A `MultiStatic` embodies the values of the `Ptr`s
    /// which have been borrowed already.
    /// Runtime checks are done by a simple search,
    /// O(n^2) time and O(n) space in the number of borrows.
    fn multi_static<'r>(self) -> MultiStatic<'r, ()> where 'a: 'r {
        MultiStatic {
            tok: self.token_mut(),
            l: (),
        }
    }

    /// Borrows from an unknown number of `Ptr` with dynamic runtime checking
    ///
    /// Call
    /// [`.borrow`](MultiDynamic::borrow)
    /// and
    /// [`.borrow_mut`](MultiDynamic::borrow)
    /// to obtain real references from multiple `Ptr`s
    ///
    /// `MultiDynamic` contains two `HashSet`s
    /// tracking which `Ptr`s have been borrowed already.
    /// Borrowing uses O(n) space, on the heap, and O(n) time.
    fn multi_dynamic<'r>(self) -> MultiDynamic<'r> where 'a: 'r {
        MultiDynamic {
            _tok: self.token_mut(),
            ref_given: HashSet::new(),
            mut_given: HashSet::new(),
        }
    }
}

mod sealed { pub trait Sealed {} }
use sealed::Sealed;

unsafe impl<'a> IsTokenRef<'a> for &'a     NoAliasSingleton {}
unsafe impl<'a> IsTokenRef<'a> for &'a mut NoAliasSingleton {}
unsafe impl<'a> IsTokenMut<'a> for &'a mut NoAliasSingleton {}
unsafe impl<'a> IsTokenRef<'a> for TokenRef<'a> {}
unsafe impl<'a> IsTokenRef<'a> for TokenMut<'a> {}
unsafe impl<'a> IsTokenMut<'a> for TokenMut<'a> {}

unsafe impl<'o, 'i: 'o, 'j: 'o> IsTokenRef<'o> for &'i     TokenRef<'j> {}
unsafe impl<'o, 'i: 'o, 'j: 'o> IsTokenRef<'o> for &'i     TokenMut<'j> {}
unsafe impl<'o, 'i: 'o, 'j: 'o> IsTokenRef<'o> for &'i mut TokenMut<'j> {}
unsafe impl<'o, 'i: 'o, 'j: 'o> IsTokenMut<'o> for &'i mut TokenMut<'j> {}

impl Sealed for &    NoAliasSingleton {}
impl Sealed for &mut NoAliasSingleton {}
impl Sealed for      TokenRef<'_> {}
impl Sealed for      TokenMut<'_> {}
impl Sealed for &    TokenRef<'_> {}
impl Sealed for &    TokenMut<'_> {}
impl Sealed for &mut TokenMut<'_> {}

//---------- principal API for borrowing etc. ----------

impl<T: ?Sized> Clone for Ptr<T> { fn clone(&self) -> Self { *self } }
impl<T: ?Sized> Copy for Ptr<T> {}

impl<T: ?Sized> Ptr<T> {
    /// Makes a new `Ptr`, moving the `T` to a new heap allocation
    pub fn new_heap(t: T) -> Self
    where T: Sized
    {
        Box::new(t).into()
    }

    /// Borrows the contained data, immutably
    #[inline]
    pub fn borrow<'a>(self, tok: impl IsTokenRef<'a>) -> &'a T {
        let _ = tok;
        unsafe {
            // SAFETY
            //
            // Points to a valid T by our invariant.
            // There can be no concurrent &mut T
            // because that would imply a concurrent `&mut NoAliasSingleton`.
            self.ptr.as_ref()
        }
    }

    /// Borrows the contained data, mutably
    #[inline]
    pub fn borrow_mut<'a>(mut self, tok: impl IsTokenMut<'a>) -> &'a mut T {
        let _ = tok;
        unsafe {
            // SAFETY
            //
            // Points to a valid T by our invariant.
            // There can be no other concurrent &T or &mut T
            // because that would imply a concurrent `&NoAliasSingleton`.
            self.ptr.as_mut()
        }
    }

    /// Returns the raw data pointer
    ///
    /// Useful if you want to compare pointers, or something.
    ///
    /// If `Ptr` was made with `new_heap` or `From<Box<_>>`,
    /// this pointer has the same properties as `Box`'s.
    /// But of course many copies may exist.
    ///
    /// # Obtaining references
    ///
    /// You may call
    /// [`.as_ref()`](NonNull::as_ref)
    /// or
    /// [`.as_mut()`](NonNull::as_mut)
    /// on the returned `NonNull`,
    /// to get `&T` or `&mut T`.
    ///
    /// This is sound iff there are no conflicting borrows,
    /// and you know you won't be freeing the data too soon.
    /// If you do this, you take responsibility
    /// for following Rust's aliasing rules.
    ///
    /// This approach is semantically equivalent to using
    /// [`TokenMut::new_unchecked()`].
    pub fn as_ptr(self) -> NonNull<T> {
        self.ptr
    }

    /// Frees a `Ptr` that was made with `new_heap`
    ///
    /// The contained `T` is dropped.
    /// To keep it, use [`.free_heap_return()`](Ptr::free_heap_return).
    ///
    /// # SAFETY
    ///
    /// `self` must have come from `new_heap` (or `From<Box>`)
    /// and be the only remaining copy of this `Ptr`
    /// (or the only one which will be used).
    ///
    /// All copies of `self` will be invalidated.
    /// It is your responsibility to ensure
    /// that none of them will be used.
    /// ("used" means passed to any method in this library.)
    ///
    /// The compiler will check that no borrows are live.
    #[inline]
    pub unsafe fn free_heap<'a>(self, tok: impl IsTokenMut<'a>) {
        let _t: Box<T> = unsafe { self.into_box(tok) };
    }

    /// Frees a `Ptr` that was made with `new_heap` and returns the `T`
    ///
    /// If `T` is not `Sized`,
    /// you must use [`free_heap`](Ptr::free_heap) (discarding `T`)
    /// or [`into_box`](Ptr::into_box) (leaving it on the heap).
    ///
    /// # SAFETY
    ///
    /// The same rules as [`free_heap`](Ptr::free_heap) apply.
    #[inline]
    pub unsafe fn free_heap_return<'a>(self, tok: impl IsTokenMut<'a>) -> T
    where T: Sized
    {
        let t: Box<T> = unsafe { self.into_box(tok) };
        *t
    }

    /// Converts a `Ptr` that was made with `new_heap` into a `Box<T>`
    ///
    /// # SAFETY
    ///
    /// The same rules as [`free_heap`](Ptr::free_heap) apply.
    #[inline]
    pub unsafe fn into_box<'a>(self, tok: impl IsTokenMut<'a>) -> Box<T> {
        let _ = tok;
        let t: Box<T> = unsafe {
            // SAFETY
            //
            // Points to a valid T that came from Box by our invariant.
            // There can be no other concurrent borrows
            // (see safety comment for borrow_mut).
            //
            // We rely on the caller promising that no-one else
            // is going to do this.
            Box::from_raw(self.ptr.as_ptr())
        };
        t
    }

    /// Make a new `Ptr` out of a raw pointer
    ///
    /// # SAFETY
    ///
    /// It is up to you to ensure that the pointer is valid for `T`,
    /// dereferencable, and has appropriate lifespan.
    pub unsafe fn from_raw(t: NonNull<T>) -> Self {
        Ptr { ptr: t }
    }
}

impl NoAliasSingleton {
    /// Initialises, by creating the singleton for alias checking
    ///
    /// # SAFETY
    ///
    /// There must be only one `NoAliasSingleton` used with each `Ptr`.
    ///
    /// That is, it is unsound to use the same `Ptr` (or any copy of it)
    /// with `TokenMut`es derived from
    /// two (or more) different `NoAliasSingleton`s.
    ///
    /// The easiest way to do this is to have only one `NoAliasSingleton`.
    ///
    /// If this rule is violated, `borrow` and `borrow_mut` can be instant-UB.
    //
    // I haven't been able to think of a practical safe API,
    // but one only needs about 1 call to init_unchecked.
    pub unsafe fn init() -> Self { NoAliasSingleton {} }
}

//---------- stack ----------

/// A `Ptr` borrowed from stack data
pub struct Borrowed<'t, T: ?Sized> {
    ptr: Ptr<T>,
    /// Variance and borrowing:
    ///
    life: PhantomData<&'t T>,
}

impl<'t, T: ?Sized> Borrowed<'t, T> {
    /// Obtain a `Ptr` from borrowed data
    ///
    /// Derefs to `Ptr<T>`.
    ///
    /// Call [`.retained()`](Borrowed::retained)
    /// at the point(s) where it is OK for the `Ptr`s to become invalid.
    ///
    /// # SAFETY
    ///
    /// You must ensure that the `Ptr` (and all its copies) is only used
    /// while the `Borrowed` still exists.
    ///
    /// The lifetime cannot be completely checked by the compiler,
    /// and Rust's drop behaviour can cause the `Ptr` be invalidated
    /// (for example, by the underlying `T` being dropped, or reborrowed)
    /// earlier than you might expect.
    ///
    /// Using `retained` is recommended:
    /// it will ensure that `Ptr`s are still live at that point.
    ///
    /// ## Unwinding
    ///
    /// Not that `Borrowed` comes with exciting hazards
    /// in the presence of panics:
    /// a typical use is to take a stack item,
    /// link it temporarily into a data structure.
    ///
    /// If an unwind occurs before the item is unlinked again,
    /// the data structure can be corrupted.
    /// It is the responsibility of the user to avoid this situation.
    ///
    /// (Note that use of `Ptr` without `Borrowed` does also come with
    /// hazards in the face of unwinding,
    /// but those are typically just memory leaks.)
    pub unsafe fn new(t: &mut T) -> Self {
        Borrowed {
            ptr: Ptr::from_raw(NonNull::from(t)),
            life: PhantomData,
        }
    }

    /// Prove that a `Borrowed` is still live.
    ///
    /// This function is a no-op, in itself.
    ///
    /// But calling it assures that the lifetime of the `Borrow`
    /// extends at least this far.
    pub fn retained(&self) {
    }
}

impl<'t, T> Deref for Borrowed<'t, T> {
    type Target = Ptr<T>;
    fn deref(&self) -> &Ptr<T> { &self.ptr }
}

//---------- helpful impls ----------

impl<T: ?Sized> From<Box<T>> for Ptr<T> {
    fn from(b: Box<T>) -> Ptr<T> {
        let ptr = Box::into_raw(b);
        let ptr = unsafe {
            // SAFETY
            // Box.into_raw() guarantees it's not null
            NonNull::new_unchecked(ptr)
        };
        Ptr { ptr }
    }
}

/// Convenience trait for working with `Option<Ptr<_>>`
pub trait OptionPtrExt<T: ?Sized> {
    /// Returns the pointer, which will be null iff `self` is `None`
    fn as_ptr(self) -> Option<*mut T>;
}
impl<T: ?Sized> OptionPtrExt<T> for Option<Ptr<T>> {
    fn as_ptr(self) -> Option<*mut T> {
        self.map(|p| p.ptr.as_ptr())
    }
}

impl<T: ?Sized> Debug for Ptr<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Ptr").field(&self.ptr).finish()
    }
}

//---------- multi-borrowing, runtime-checked ----------

/// Conflicting borrows occurred
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct BorrowConflictError;

impl Display for BorrowConflictError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "conflicting borrows attempted")
    }
}
impl std::error::Error for BorrowConflictError {}

type BorrowResult<T> = Result<T, BorrowConflictError>;

/// Tracker for multiple borrows (dynamic)
///
/// Returned from [`IsTokenMut::multi_dynamic`].
pub struct MultiDynamic<'a> {
    _tok: TokenMut<'a>,
    ref_given: HashSet<NonNull<()>>,
    mut_given: HashSet<NonNull<()>>,
}

impl<'a> MultiDynamic<'a> {
    /// Borrow `p` immutably
    ///
    /// If `p` has already been mutably borrowed, returns `Err`.
    #[inline]
    pub fn borrow<'r, T>(&mut self, p: Ptr<T>) -> BorrowResult<&'r T>
    where 'a: 'r
    {
        self.borrow_inner_check(p.ptr.cast())?;
        Ok(unsafe { p.ptr.as_ref() })
    }

    fn borrow_inner_check(&mut self, p: NonNull<()>) -> BorrowResult<()> {
        if self.mut_given.contains(&p) {
            return Err(BorrowConflictError)
        }
        self.ref_given.insert(p);
        Ok(())
    }

    /// Borrow `p` mutably
    ///
    /// If `p` has already been borrowed, returns `Err`.
    #[inline]
    pub fn borrow_mut<'r, T>(&mut self, mut p: Ptr<T>)
                             -> BorrowResult<&'r mut T>
    where 'a: 'r
    {
        self.borrow_mut_inner_check(p.ptr.cast())?;
        Ok(unsafe { p.ptr.as_mut() })
    }

    fn borrow_mut_inner_check(&mut self, p: NonNull<()>) -> BorrowResult<()> {
        if self.ref_given.contains(&p) {
            return Err(BorrowConflictError)
        }
        if !self.mut_given.insert(p) {
            return Err(BorrowConflictError)
        }
        Ok(())
    }
}

//---------- multi-borrowing ----------

/// Tracker for multiple borrows (static)
///
/// Returned from [`IsTokenMut::multi_static`].
pub struct MultiStatic<'a, L> {
    tok: TokenMut<'a>,
    l: L,
}

fn forbid_alias(this: *const (), new: NonNull<()>) -> BorrowResult<()> {
    if this == new.as_ptr() { return Err(BorrowConflictError) }
    Ok(())
}

mod multi_static {
    use super::*;
    pub unsafe trait MultiStaticList {
        fn alias_check_ref(&self, p: NonNull<()>) -> BorrowResult<()>;
        fn alias_check_mut(&self, p: NonNull<()>) -> BorrowResult<()>;
    }
}
use multi_static::MultiStaticList;

unsafe impl MultiStaticList for () {
    fn alias_check_ref(&self, _: NonNull<()>) -> BorrowResult<()> {
        Ok(())
    }
    fn alias_check_mut(&self, _: NonNull<()>) -> BorrowResult<()> {
        Ok(())
    }
}
unsafe impl<L: MultiStaticList> MultiStaticList for (L, *const ()) {
    fn alias_check_ref(&self, p: NonNull<()>) -> BorrowResult<()> {
        self.0.alias_check_ref(p)
    }
    fn alias_check_mut(&self, p: NonNull<()>) -> BorrowResult<()> {
        forbid_alias(self.1, p)?;
        self.0.alias_check_mut(p)
    }
}
unsafe impl<L: MultiStaticList> MultiStaticList for (L, NonNull<()>) {
    fn alias_check_ref(&self, p: NonNull<()>) -> BorrowResult<()> {
        forbid_alias(self.1.as_ptr(), p)?;
        self.0.alias_check_ref(p)
    }
    fn alias_check_mut(&self, p: NonNull<()>) -> BorrowResult<()> {
        forbid_alias(self.1.as_ptr(), p)?;
        self.0.alias_check_mut(p)
    }
}

impl<'a, L: MultiStaticList> MultiStatic<'a, L> {
    /// Borrows `p` immutably
    ///
    /// Returns the requested borrow, `&T`,
    /// and `MultiStatic` that can be used for further borrowing.
    ///
    /// If `p` has already been mutably borrowed, returns `Err`.
    pub fn borrow<'r, T>(self, p: Ptr<T>) -> Result<
        (&'r T, MultiStatic<'a, (L, *const ())>),
        Self
    >
    where 'a: 'r
    {
        match self.l.alias_check_ref(p.ptr.cast()) {
            Err(BorrowConflictError) => Err(self),
            Ok(()) => Ok((
                unsafe { p.ptr.as_ref() },
                MultiStatic {
                    tok: self.tok,
                    l: (self.l, p.ptr.cast().as_ptr()),
                }
            ))
        }
    }

    /// Borrows `p` mutably
    ///
    /// Returns the requested borrow, `&mut T`,
    /// and `MultiStatic` that can be used for further borrowing.
    ///
    /// If `p` has already been borrowed, returns `Err`.
    pub fn borrow_mut<'r, T>(self, mut p: Ptr<T>) -> Result<
        (&'r mut T, MultiStatic<'a, (L, NonNull<()>)>),
        Self
    >
    where 'a: 'r
    {
        match self.l.alias_check_mut(p.ptr.cast()) {
            Err(BorrowConflictError) => Err(self),
            Ok(()) => Ok((
                unsafe { p.ptr.as_mut() },
                MultiStatic {
                    tok: self.tok,
                    l: (self.l, p.ptr.cast()),
                },
            ))
        }
    }
}