ghost-cell 0.2.6

Compile-time zero-cost borrow-checking of aliased references
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
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
//! The `GhostBorrowMut` trait, which allows mutably borrowing multiple `GhostCell`s simultaneously.
//!
//! This module implement the `GhostBorrowMut` trait for:
//!
//! -   A slice of `GhostCell`s.
//! -   An array of `GhostCell`s of any size.
//! -   A tuple of `GhostCell`s of up to 12 elements.
//! -   A tuple of references to `GhostCell`s of up to 12 elements.
//!
//! #   Performance
//!
//! In general borrowing is free of cost, however a special-case is necessary for an array or tuple of references, as
//! then the references may alias.
//!
//! #   Zero-Sized Type Handling
//!
//! While purely in terms of memory it is sound to obtain two mutable references to a given Zero-Sized Type (ZST)
//! instance, since no memory reads or writes will actually be performed, this is not supported by `GhostBorrowMut`.
//!
//! As noted by @wackbytes in [issue #32](https://github.com/matthieu-m/ghost-cell/issues/32) the problem is that
//! certain ZSTs encode capabilities, for example, `GhostToken` does. Obtaining two mutable references to a given
//! `GhostToken` then allow mutably borrowing the same `GhostCell` twice, which easily leads to unsoundness.
//!
//! Unfortunately, there is no easy way to distinguish between a ZST with special capabilities associated to it, and a
//! ZST without such special capabilities. Therefore, for soundness reasons, all ZSTs must be treated as potentially
//! having special capabilities. As a result, `GhostBorrowMut` does not allow borrowing the same ZST mutably twice.
//!
//! #   Experimental
//!
//! The feature is experimental, to enable, use the feature "experimental-multiple-mutable-borrows".

use core::{convert::Infallible, mem, ptr};

use crate::ghost_cell::*;

/// An error signifying that two `GhostCell`s that need to be distinct were actually the same cell.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub struct GhostAliasingError;

// For uniformity, if anyone wants it. Can't do
// impl<T> From<Infallible> for T
// because of conflicting implementations.
impl From<Infallible> for GhostAliasingError {
    fn from(_: Infallible) -> Self {
        unreachable!("Infallible cannot be constructed")
    }
}

/// A trait for implementing multiple borrows for any number of arguments, using a `GhostToken<'a, 'brand>`.
///
/// Implemented for a mixture of tuple and array types.
///
/// #   Experimental
///
/// The feature is experimental, to enable, use the feature "experimental-multiple-mutable-borrows".
pub trait GhostBorrowMut<'a, 'brand> {
    /// The references you get as a result.
    ///
    /// For example, if `Self` is `(&'a GhostCell<'brand, T0>, &'a GhostCell<'brand, T1>)` then `Result` is
    /// `(&'a mut T0, &'a mut T1)`.
    type Result;

    /// The error case.
    ///
    /// Use a never type such as `!` or `Infallible` if an error is impossible, and `GhostAliasingError` otherwise.
    type Error: Into<GhostAliasingError>;

    /// Borrows any number of `GhostCell`s mutably at the same time.
    ///
    /// If any of them are the same `GhostCell`, returns `Error`.
    ///
    /// #   Performance
    ///
    /// In general, borrowing should be free of cost if possible. This can be ascertained by checking the error type:
    /// if it is a never type, then the operation is infallible, indicating no run-time check is necessary.
    ///
    /// If the operation is not infallible, then a runtime check is necessary, in which case the unchecked version of
    /// the operation may be used if performance matters and the caller is certain of the absence of problems.
    ///
    /// #   Example
    ///
    /// ```rust
    /// use ghost_cell::{GhostToken, GhostCell, GhostBorrowMut};
    ///
    /// let value = GhostToken::new(|mut token| {
    ///     let cell1 = GhostCell::new(42);
    ///     let cell2 = GhostCell::new(47);
    ///
    ///     let (reference1, reference2): (&mut i32, &mut i32)
    ///         = (&cell1, &cell2).borrow_mut(&mut token).unwrap();
    ///     *reference1 = 33;
    ///     *reference2 = 34;
    ///     // here we stop mutating, so the token isn't mutably borrowed anymore, and we can read again
    ///
    ///     (*cell1.borrow(&token), *cell2.borrow(&token))
    /// });
    ///
    /// assert_eq!((33, 34), value);
    /// ```
    fn borrow_mut(self, token: &'a mut GhostToken<'brand>) -> Result<Self::Result, Self::Error>;

    /// Borrows any number of `GhostCell`s at the same time, infallibly.
    ///
    /// #   Safety
    ///
    /// The caller guarantees that the various `GhostCell`s do not alias.
    unsafe fn borrow_mut_unchecked(self, token: &'a mut GhostToken<'brand>) -> Self::Result;
}

impl<'a, 'brand, T> GhostBorrowMut<'a, 'brand> for &'a [GhostCell<'brand, T>] {
    type Result = &'a mut [T];
    type Error = Infallible;

    fn borrow_mut(self, token: &'a mut GhostToken<'brand>) -> Result<Self::Result, Self::Error> {
        //  Safety:
        //  -   All cells are adjacent in memory, hence distinct from one another.
        Ok(unsafe { self.borrow_mut_unchecked(token) })
    }

    unsafe fn borrow_mut_unchecked(self, _: &'a mut GhostToken<'brand>) -> Self::Result {
        //  Safety:
        //  -   Exclusive access to the `GhostToken` ensures exclusive access to the cells' content, if unaliased.
        //  -   `GhostCell` is `repr(transparent)`, hence `T` and `GhostCell<T>` have the same memory representation.
        //  -   All cells are adjacent in memory, hence distinct from one another.
        #[allow(mutable_transmutes)]
        mem::transmute::<Self, Self::Result>(self)
    }
}

impl<'a, 'brand, T, const N: usize> GhostBorrowMut<'a, 'brand> for &'a [GhostCell<'brand, T>; N] {
    type Result = &'a mut [T; N];
    type Error = Infallible;

    fn borrow_mut(self, token: &'a mut GhostToken<'brand>) -> Result<Self::Result, Self::Error> {
        //  Safety:
        //  -   All cells are adjacent in memory, hence distinct from one another.
        Ok(unsafe { self.borrow_mut_unchecked(token) })
    }

    unsafe fn borrow_mut_unchecked(self, _: &'a mut GhostToken<'brand>) -> Self::Result {
        //  Safety:
        //  -   Exclusive access to the `GhostToken` ensures exclusive access to the cells' content, if unaliased.
        //  -   `GhostCell` is `repr(transparent)`, hence `T` and `GhostCell<T>` have the same memory representation.
        //  -   All cells are adjacent in memory, hence distinct from one another.
        #[allow(mutable_transmutes)]
        mem::transmute::<Self, Self::Result>(self)
    }
}

impl<'a, 'brand, T: ?Sized, const N: usize> GhostBorrowMut<'a, 'brand> for [&'a GhostCell<'brand, T>; N] {
    type Result = [&'a mut T; N];
    type Error = GhostAliasingError;

    fn borrow_mut(self, token: &'a mut GhostToken<'brand>) -> Result<Self::Result, Self::Error> {
        check_distinct(self.map(get_span))?;

        //  Safety:
        //  -   The cells were checked to be distinct.
        Ok(unsafe { self.borrow_mut_unchecked(token) })
    }

    unsafe fn borrow_mut_unchecked(self, _: &'a mut GhostToken<'brand>) -> Self::Result {
        //  Safety:
        //  -   Exclusive access to the `GhostToken` ensures exclusive access to the cells' content, if unaliased.
        //  -   The caller guarantees the cells are not aliased.
        //  -   `[&'a GhostCell<'brand, T>; N]` and `[&'a mut T; N]` have the same size.
        //  -   `[&'a GhostCell<'brand, T>; N]` implements `Copy`, so no `mem::forget` is needed.
        //  -   We can't use `mem::transmute`, because of https://github.com/rust-lang/rust/issues/61956.
        ptr::read(&self as *const _ as *const Self::Result)
    }
}

macro_rules! last {
    () => {};
    ($head:ident $(,)?) => {
        $head
    };
    ($head:ident, $($tail:ident),+ $(,)?) => {
        last!($($tail),+)
    };
}

macro_rules! generate_public_instance {
    ( $($name:ident),* ; $($type_letter:ident),* ) => {
        impl<'a, 'brand, $($type_letter: ?Sized,)*> GhostBorrowMut<'a, 'brand>
            for ( $(&'a GhostCell<'brand, $type_letter>, )* )
        {
            type Result = ( $(&'a mut $type_letter, )* );
            type Error = GhostAliasingError;

            fn borrow_mut(self, token: &'a mut GhostToken<'brand>) -> Result<Self::Result, Self::Error> {
                let ($($name,)*) = self;

                check_distinct([ $( get_span($name), )* ])?;

                //  Safety:
                //  -   The cells were checked to be distinct.
                Ok(unsafe { self.borrow_mut_unchecked(token) })
            }

            unsafe fn borrow_mut_unchecked(self, _: &'a mut GhostToken<'brand>) -> Self::Result {
                let ($($name,)*) = self;

                //  Safety:
                //  -   Exclusive access to the `GhostToken` ensures exclusive access to the cells' content, if unaliased.
                //  -   The caller guarantees the cells are not aliased.
                ( $( &mut * $name.as_ptr(),)* )
            }
        }

        impl<'a, 'brand, $($type_letter,)*> GhostBorrowMut<'a, 'brand>
            for &'a ( $(GhostCell<'brand, $type_letter>, )* )
        where
            last!( $($type_letter),* ): ?Sized
        {
            type Result = &'a mut ( $($type_letter, )* );
            type Error = Infallible;

            fn borrow_mut(self, token: &'a mut GhostToken<'brand>) -> Result<Self::Result, Self::Error> {
                //  Safety:
                //  -   All cells are adjacent in memory, hence distinct from one another.
                Ok(unsafe { self.borrow_mut_unchecked(token) })
            }

            unsafe fn borrow_mut_unchecked(self, _: &'a mut GhostToken<'brand>) -> Self::Result {
                //  Safety:
                //  -   Exclusive access to the `GhostToken` ensures exclusive access to the cells' content, if unaliased.
                //  -   `GhostCell` is `repr(transparent)`, hence `T` and `GhostCell<T>` have the same memory representation.
                //  -   All cells are adjacent in memory, hence distinct from one another.
                #[allow(mutable_transmutes)]
                core::mem::transmute::<Self, Self::Result>(self)
            }
        }
    };
}

generate_public_instance!(a ; T0);
generate_public_instance!(a, b ; T0, T1);
generate_public_instance!(a, b, c ; T0, T1, T2);
generate_public_instance!(a, b, c, d ; T0, T1, T2, T3);
generate_public_instance!(a, b, c, d, e ; T0, T1, T2, T3, T4);
generate_public_instance!(a, b, c, d, e, f ; T0, T1, T2, T3, T4, T5);
generate_public_instance!(a, b, c, d, e, f, g ; T0, T1, T2, T3, T4, T5, T6);
generate_public_instance!(a, b, c, d, e, f, g, h ; T0, T1, T2, T3, T4, T5, T6, T7);
generate_public_instance!(a, b, c, d, e, f, g, h, i ; T0, T1, T2, T3, T4, T5, T6, T7, T8);
generate_public_instance!(a, b, c, d, e, f, g, h, i, j ; T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
generate_public_instance!(a, b, c, d, e, f, g, h, i, j, k ; T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TA);
generate_public_instance!(a, b, c, d, e, f, g, h, i, j, k, l ; T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TA, TB);

//
//  Implementation
//

//  Returns the _inclusive_ range of memory covered by the value.
//
//  #   Why an inclusive range?
//
//  -   Dynamically-sized types (DST) require checking for memory range overlap, not just pointer equality.
//  -   If a value is at the very edge of the memory range, then one-past-the-end would overflow (and wrap around); an
//      inclusive range has no wrap around issue.
fn get_span<T: ?Sized>(value: &T) -> (usize, usize) {
    let value_size = mem::size_of_val(value);

    let offset = if value_size == 0 { 0 } else { value_size - 1 };

    let start = value as *const T as *const u8 as usize;

    (start, start + offset)
}

//  Returns `Ok(())` if the inclusive ranges do not overlap, and `Err(GhostAliasingError)` otherwise.
//
//  Assumes that the ranges are _inclusive_.
fn check_distinct<const N: usize>(mut array: [(usize, usize); N]) -> Result<(), GhostAliasingError> {
    //  Sort slices by their start pointer.
    array.sort_unstable_by_key(|t| t.0);

    //  Overlap can then be detected by whether the end of a slice overtakes the start of the next slice.
    for window in array.windows(2) {
        //  Safety:
        //  -   `window` is guaranteed to have exactly 2 elements.
        let (left, right) = unsafe { (window.get_unchecked(0), window.get_unchecked(1)) };

        //  Due to ranges being _inclusive_, we need >=, not >.
        if left.1 >= right.0 {
            return Err(GhostAliasingError);
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn multiple_borrows_tuple() {
        let value = GhostToken::new(|mut token| {
            let cell1 = GhostCell::new(42);
            let cell2 = GhostCell::new(47);
            let cell3 = GhostCell::new(7);
            let cell4 = GhostCell::new(9);

            let (reference1, reference2, reference3, reference4): (&mut i32, &mut i32, &mut i32, &mut i32) =
                (&cell1, &cell2, &cell3, &cell4).borrow_mut(&mut token).unwrap();
            *reference1 = 33;
            *reference2 = 34;
            *reference3 = 35;
            *reference4 = 36;

            // here we stop mutating, so the token isn't mutably borrowed anymore, and we can read again
            (*cell1.borrow(&token), *cell2.borrow(&token), *cell3.borrow(&token))
        });
        assert_eq!((33, 34, 35), value);
    }

    #[test]
    #[should_panic]
    fn multiple_borrows_tuple_aliased() {
        GhostToken::new(|mut token| {
            let cell1 = GhostCell::new(42);
            let cell2 = GhostCell::new(47);
            let cell3 = GhostCell::new(7);
            let _: (&mut i32, &mut i32, &mut i32, &mut i32) =
                (&cell1, &cell2, &cell3, &cell2).borrow_mut(&mut token).unwrap();
        });
    }

    #[test]
    fn multiple_borrows_tuple_ref() {
        let value = GhostToken::new(|mut token| {
            let cell1 = GhostCell::new(42);
            let cell2 = GhostCell::new(47);
            let cell3 = GhostCell::new(7);
            let cell4 = GhostCell::new(9);
            let tuple = (cell1, cell2, cell3, cell4);

            let reference: &mut (i32, i32, i32, i32) = tuple.borrow_mut(&mut token).unwrap();
            reference.0 = 33;
            reference.1 = 34;
            reference.2 = 35;
            reference.3 = 36;

            // here we stop mutating, so the token isn't mutably borrowed anymore, and we can read again
            (
                *tuple.0.borrow(&token),
                *tuple.1.borrow(&token),
                *tuple.2.borrow(&token),
            )
        });
        assert_eq!((33, 34, 35), value);
    }

    #[test]
    fn multiple_borrows_array_ref() {
        let value = GhostToken::new(|mut token| {
            let cell1 = GhostCell::new(42);
            let cell2 = GhostCell::new(47);
            let cell3 = GhostCell::new(7);
            let cell4 = GhostCell::new(9);
            let array = [cell1, cell2, cell3, cell4];

            let reference: &mut [i32; 4] = array.borrow_mut(&mut token).unwrap();
            reference[0] = 33;
            reference[1] = 34;
            reference[2] = 35;
            reference[3] = 36;

            // here we stop mutating, so the token isn't mutably borrowed anymore, and we can read again
            (
                *array[0].borrow(&token),
                *array[1].borrow(&token),
                *array[2].borrow(&token),
            )
        });
        assert_eq!((33, 34, 35), value);
    }

    #[test]
    #[should_panic]
    fn multiple_borrows_single_slice_overlap() {
        GhostToken::new(|mut token| {
            let mut array = [3, 7];
            let cell_of_slice = &*GhostCell::from_mut(&mut array[..]);
            let slice_of_cells = cell_of_slice.as_slice_of_cells();
            let second_cell = &slice_of_cells[1];

            let _ = (second_cell, cell_of_slice).borrow_mut(&mut token).unwrap();
        });
    }

    #[test]
    #[should_panic]
    fn multiple_borrows_single_array_overlap() {
        GhostToken::new(|mut token| {
            let cell_of_array = GhostCell::new([3, 7]);
            let slice_of_cells = (&cell_of_array as &GhostCell<[i32]>).as_slice_of_cells();
            let second_cell = &slice_of_cells[1];

            let _ = (second_cell, &cell_of_array).borrow_mut(&mut token).unwrap();
        });
    }

    //  Trait suitable for testing the mutable borrowing of trait objects
    trait Store {
        type Item;

        fn get(&self) -> Self::Item;

        fn set(&mut self, x: Self::Item);
    }

    impl Store for i32 {
        type Item = Self;

        fn get(&self) -> Self::Item {
            *self
        }

        fn set(&mut self, x: Self::Item) {
            *self = x;
        }
    }

    #[test]
    fn multiple_borrows_tuple_unsized() {
        let value = GhostToken::new(|mut token| {
            let mut data1 = 42;
            let mut data2 = [47];
            let mut data3 = 7;
            let mut data4 = [9];

            let cell1 = &*GhostCell::from_mut(&mut data1 as &mut dyn Store<Item = i32>);
            let cell2 = &*GhostCell::from_mut(&mut data2 as &mut [i32]);
            let cell3 = &*GhostCell::from_mut(&mut data3 as &mut dyn Store<Item = i32>);
            let cell4 = &*GhostCell::from_mut(&mut data4 as &mut [i32]);

            let (reference1, reference2, reference3, reference4) =
                (cell1, cell2, cell3, cell4).borrow_mut(&mut token).unwrap();
            reference1.set(7);
            reference3.set(42);
            mem::swap(&mut reference2[0], &mut reference4[0]);

            (reference1.get(), reference2[0], reference3.get(), reference4[0])
        });
        assert_eq!((7, 9, 42, 47), value);
    }

    #[test]
    fn multiple_borrows_array_unsized_slice() {
        let value = GhostToken::new(|mut token| {
            let mut data1 = [42];
            let mut data2 = [47];
            let mut data3 = [7];
            let mut data4 = [9];

            let cell1 = &*GhostCell::from_mut(&mut data1 as &mut [i32]);
            let cell2 = &*GhostCell::from_mut(&mut data2 as &mut [i32]);
            let cell3 = &*GhostCell::from_mut(&mut data3 as &mut [i32]);
            let cell4 = &*GhostCell::from_mut(&mut data4 as &mut [i32]);
            let array = [cell1, cell2, cell3, cell4];

            let reference: [&mut [i32]; 4] = array.borrow_mut(&mut token).unwrap();
            reference[0][0] = 33;
            reference[1][0] = 34;
            reference[2][0] = 35;
            reference[3][0] = 36;

            (
                array[0].borrow(&token)[0],
                array[1].borrow(&token)[0],
                array[2].borrow(&token)[0],
            )
        });
        assert_eq!((33, 34, 35), value);
    }

    #[test]
    fn multiple_borrows_array_unsized_dyn_trait() {
        let value = GhostToken::new(|mut token| {
            let mut data1 = 42;
            let mut data2 = 47;
            let mut data3 = 7;
            let mut data4 = 9;

            let cell1 = &*GhostCell::from_mut(&mut data1 as &mut dyn Store<Item = i32>);
            let cell2 = &*GhostCell::from_mut(&mut data2 as &mut dyn Store<Item = i32>);
            let cell3 = &*GhostCell::from_mut(&mut data3 as &mut dyn Store<Item = i32>);
            let cell4 = &*GhostCell::from_mut(&mut data4 as &mut dyn Store<Item = i32>);
            let array = [cell1, cell2, cell3, cell4];

            let reference: [&mut dyn Store<Item = i32>; 4] = array.borrow_mut(&mut token).unwrap();
            reference[0].set(33);
            reference[1].set(34);
            reference[2].set(35);
            reference[3].set(36);

            (
                array[0].borrow(&token).get(),
                array[1].borrow(&token).get(),
                array[2].borrow(&token).get(),
            )
        });
        assert_eq!((33, 34, 35), value);
    }

    #[test]
    #[should_panic]
    fn multiple_borrows_tuple_unsized_aliased() {
        GhostToken::new(|mut token| {
            let mut data1 = 42;
            let mut data2 = [47];
            let mut data3 = 7;

            let cell1 = &*GhostCell::from_mut(&mut data1 as &mut dyn Store<Item = i32>);
            let cell2 = &*GhostCell::from_mut(&mut data2 as &mut [i32]);
            let cell3 = &*GhostCell::from_mut(&mut data3 as &mut dyn ToString);

            let _: (&mut dyn Store<Item = i32>, &mut [i32], &mut dyn ToString, &mut [i32]) =
                (cell1, cell2, cell3, cell2).borrow_mut(&mut token).unwrap();
        });
    }

    #[test]
    #[should_panic]
    fn multiple_borrows_array_unsized_slice_aliased() {
        GhostToken::new(|mut token| {
            let mut data1 = [42];
            let mut data2 = [47];
            let mut data3 = [7];

            let cell1 = &*GhostCell::from_mut(&mut data1 as &mut [i32]);
            let cell2 = &*GhostCell::from_mut(&mut data2 as &mut [i32]);
            let cell3 = &*GhostCell::from_mut(&mut data3 as &mut [i32]);
            let array = [cell1, cell2, cell3, cell2];

            let _: [&mut [i32]; 4] = array.borrow_mut(&mut token).unwrap();
        });
    }

    #[test]
    #[should_panic]
    fn multiple_borrows_array_unsized_dyn_trait_aliased() {
        GhostToken::new(|mut token| {
            let mut data1 = 42;
            let mut data2 = 47;
            let mut data3 = 7;

            let cell1 = &*GhostCell::from_mut(&mut data1 as &mut dyn Store<Item = i32>);
            let cell2 = &*GhostCell::from_mut(&mut data2 as &mut dyn Store<Item = i32>);
            let cell3 = &*GhostCell::from_mut(&mut data3 as &mut dyn Store<Item = i32>);
            let array = [cell1, cell2, cell3, cell2];

            let _: [&mut dyn Store<Item = i32>; 4] = array.borrow_mut(&mut token).unwrap();
        });
    }

    #[test]
    fn check_distinct() {
        //  Small array.
        GhostToken::new(|mut token| {
            let cells = [
                GhostCell::new(1),
                GhostCell::new(2),
                GhostCell::new(3),
                GhostCell::new(4),
                GhostCell::new(5),
                GhostCell::new(6),
            ];

            //  No aliasing.
            let tuple1 = (&cells[0], &cells[1], &cells[2], &cells[3], &cells[4], &cells[5]);
            assert!(tuple1.borrow_mut(&mut token).is_ok());

            //  Aliasing at start/end.
            let tuple2 = (&cells[0], &cells[1], &cells[2], &cells[3], &cells[4], &cells[0]);
            assert!(tuple2.borrow_mut(&mut token).is_err());
        });

        //  Big array.
        GhostToken::new(|mut token| {
            let cells = [
                GhostCell::new(1),
                GhostCell::new(2),
                GhostCell::new(3),
                GhostCell::new(4),
                GhostCell::new(5),
                GhostCell::new(6),
                GhostCell::new(7),
                GhostCell::new(8),
                GhostCell::new(9),
                GhostCell::new(10),
                GhostCell::new(11),
                GhostCell::new(12),
            ];

            //  No aliasing.
            let tuple1 = (
                &cells[0], &cells[1], &cells[2], &cells[3], &cells[4], &cells[5], &cells[6], &cells[7], &cells[8],
                &cells[9], &cells[10], &cells[11],
            );
            assert!(tuple1.borrow_mut(&mut token).is_ok());

            //  Aliasing at start/end.
            let tuple2 = (
                &cells[0], &cells[1], &cells[2], &cells[3], &cells[4], &cells[5], &cells[6], &cells[7], &cells[8],
                &cells[9], &cells[10], &cells[0],
            );
            assert!(tuple2.borrow_mut(&mut token).is_err());

            //  Aliasing at the start.
            let tuple3 = (
                &cells[0], &cells[0], &cells[1], &cells[3], &cells[4], &cells[5], &cells[6], &cells[7], &cells[8],
                &cells[9], &cells[10], &cells[11],
            );
            assert!(tuple3.borrow_mut(&mut token).is_err());

            //  Aliasing at the end.
            let tuple4 = (
                &cells[0], &cells[1], &cells[2], &cells[3], &cells[4], &cells[5], &cells[6], &cells[7], &cells[8],
                &cells[9], &cells[10], &cells[10],
            );
            assert!(tuple4.borrow_mut(&mut token).is_err());

            //  Aliasing in the middle.
            let tuple5 = (
                &cells[0], &cells[1], &cells[2], &cells[3], &cells[4], &cells[5], &cells[5], &cells[7], &cells[8],
                &cells[9], &cells[10], &cells[11],
            );
            assert!(tuple5.borrow_mut(&mut token).is_err());
        });
    }

    #[test]
    fn check_distinct_zst() {
        //  Check that ZSTs are never considered distincts.
        GhostToken::new(|mut token| {
            let zst = GhostCell::new(());

            let tuple = (&zst, &zst);
            assert!(tuple.borrow_mut(&mut token).is_err());
        });
    }

    #[test]
    fn check_distinct_inner_zst() {
        //  Check that an inner ZST is not considered distinct from its outer instance.
        GhostToken::new(|mut token| {
            let outer = GhostCell::new((1, (), 2));
            let (_, inner, _) = outer.as_tuple_of_cells();

            let tuple = (&outer, inner);
            assert!(tuple.borrow_mut(&mut token).is_err());
        });
    }
} // mod tests