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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use std::{
    fmt::{self, Display},
    marker::PhantomData,
    ptr::NonNull,
};

use crate::{
    pointer_trait::{AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, PK_MutReference},
    sabi_types::RRef,
};

/// Equivalent to `&'a mut T`,
/// which allows a few more operations without causing Undefined Behavior.
///
/// # Purpose
///
/// This type is used as the `&mut self` parameter in abi_stable trait objects
/// because it can be soundly transmuted
/// to point to other smaller but compatible types, then back to the original type.
///
/// This crate is tested with [miri] to detect bugs in unsafe code,
/// which implements the  [Stacked Borrows model].
/// Because that model forbids `&mut T` to `&mut ()`  to `&mut T` transmutes
/// (when `T` isn't zero-sized),
/// it required defining `RMut` to allow a mutable-reference-like type that can be transmuted.
///
/// # Example
///
/// This example demonstrates how a simple `&mut dyn Any`-like type can be implemented.
///
/// ```rust
/// use abi_stable::{marker_type::ErasedObject, std_types::UTypeId, RMut};
///
/// fn main() {
///     let mut value = WithTypeId::new(5u32);
///     let mut clone = value.clone();
///     let mut erased = value.erase();
///
///     assert_eq!(WithTypeId::downcast::<i32>(erased.reborrow()), None);
///     assert_eq!(WithTypeId::downcast::<bool>(erased.reborrow()), None);
///     assert_eq!(
///         WithTypeId::downcast::<u32>(erased.reborrow()),
///         Some(&mut clone)
///     );
/// }
///
/// // `#[repr(C))]` with a trailing `T` field is required for soundly transmuting from
/// // `RMut<'a, WithTypeId<T>>` to `RMut<'a, WithTypeId<ErasedObject>>`.
/// #[repr(C)]
/// #[derive(Debug, PartialEq, Clone)]
/// struct WithTypeId<T> {
///     type_id: UTypeId,
///     value: T,
/// }
///
/// impl<T> WithTypeId<T> {
///     pub fn new(value: T) -> Self
///     where
///         T: 'static,
///     {
///         Self {
///             type_id: UTypeId::new::<T>(),
///             value,
///         }
///     }
///
///     pub fn erase(&mut self) -> RMut<'_, WithTypeId<ErasedObject>> {
///         unsafe { RMut::new(self).transmute::<WithTypeId<ErasedObject>>() }
///     }
/// }
///
/// impl WithTypeId<ErasedObject> {
///     pub fn downcast<T>(this: RMut<'_, Self>) -> Option<&mut WithTypeId<T>>
///     where
///         T: 'static,
///     {
///         if this.get().type_id == UTypeId::new::<T>() {
///             // safety: we checked that type parameter was `T`
///             unsafe { Some(this.transmute_into_mut::<WithTypeId<T>>()) }
///         } else {
///             None
///         }
///     }
/// }
///
///
/// ```
///
/// <span id="type-prefix-exp"></span>
/// # Type Prefix
///
/// A type parameter `U` is considered a prefix of `T` in all of these cases:
///
/// - `U` is a zero-sized type with an alignment equal or lower than `T`
///
/// - `U` is a `#[repr(transparent)]` wrapper over `T`
///
/// - `U` and `T` are both `#[repr(C)]` structs,
/// in which `T` starts with the fields of `U` in the same order,
/// and `U` has an alignment equal to or lower than `T`.
///
/// Please note that it can be unsound to transmute a non-local
/// type if it has private fields,
/// since it may assume it was constructed in a particular way.
///
/// [Stacked Borrows model]:
/// https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md
///
/// [miri]: https://github.com/rust-lang/miri
///
#[repr(transparent)]
#[derive(StableAbi)]
#[sabi(bound(T:'a))]
pub struct RMut<'a, T> {
    ref_: NonNull<T>,
    _marker: PhantomData<crate::utils::MutRef<'a, T>>,
}

impl<'a, T> Display for RMut<'a, T>
where
    T: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(self.get(), f)
    }
}

unsafe impl<'a, T> Sync for RMut<'a, T> where &'a T: Sync {}

unsafe impl<'a, T> Send for RMut<'a, T> where &'a T: Send {}

shared_impls! {
    mod=static_ref_impls
    new_type=RMut['a][T],
    original_type=AAAA,
    deref_approach=(method = get),
}

impl<'a, T> RMut<'a, T> {
    /// Constructs this RMut from a mutable reference
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut foo = 3;
    /// let mut rmut = RMut::new(&mut foo);
    /// *rmut.get_mut() += 10;
    ///
    /// assert_eq!(*rmut.get(), 13);
    /// assert_eq!(foo, 13);
    ///
    /// ```
    #[inline(always)]
    pub fn new(ref_: &'a mut T) -> Self {
        unsafe {
            Self {
                ref_: NonNull::new_unchecked(ref_),
                _marker: PhantomData,
            }
        }
    }

    /// Constructs this RMut from a raw pointer.
    ///
    /// # Safety
    ///
    /// You must ensure that the raw pointer is valid for the `'a` lifetime,
    /// points to a fully initialized and aligned `T`,
    /// and that this is the only active pointer to that value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut foo = 3u32;
    /// // safety:
    /// // `&mut foo` is casted to a pointer to a compatible type (`u32` to `i32`),
    /// // `rmut` is only used for the lifetime of foo,
    /// // and is the only active pointer to `foo` while it's used.
    /// let mut rmut = unsafe { RMut::from_raw((&mut foo) as *mut u32 as *mut i32) };
    /// *rmut.get_mut() -= 4;
    ///
    /// assert_eq!(*rmut.get(), -1);
    /// assert_eq!(foo, !0);
    ///
    /// ```
    #[inline(always)]
    pub const unsafe fn from_raw(ref_: *mut T) -> Self
    where
        T: 'a,
    {
        Self {
            ref_: unsafe { NonNull::new_unchecked(ref_) },
            _marker: PhantomData,
        }
    }

    /// Reborrows this `RMut`, with a shorter lifetime.
    ///
    /// This allows passing an `RMut` to functions multiple times,
    /// but with a shorter lifetime argument.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut foo = 3;
    /// let mut rmut = RMut::new(&mut foo);
    ///
    /// assert_eq!(mutate(rmut.reborrow()), 6);
    /// assert_eq!(mutate(rmut.reborrow()), 12);
    /// assert_eq!(mutate(rmut.reborrow()), 24);
    ///
    /// // last use of rmut, so it can be moved instead of being reborrowed.
    /// assert_eq!(mutate(rmut), 48);
    ///
    /// fn mutate(mut rmut: RMut<'_, u32>) -> u32 {
    ///     *rmut.get_mut() *= 2;
    ///     rmut.get_copy()
    /// }
    ///
    /// ```
    #[inline(always)]
    pub fn reborrow(&mut self) -> RMut<'_, T> {
        RMut {
            ref_: self.ref_,
            _marker: PhantomData,
        }
    }

    /// Reborrows this `RMut` into a shared reference.
    ///
    /// Note that because the reference reborrows this `RMut<'a, T>`
    /// its lifetime argument is strictly smaller.
    /// To turn an `RMut<'a, T>` into a `&'a T` (with the same lifetime argument)
    /// you can use [`into_ref`](#method.into_ref).
    ///
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 89;
    /// let rmut = RMut::new(&mut val);
    ///
    /// assert_eq!(rmut.get(), &89);
    ///
    /// ```
    ///
    /// ### Lifetimes
    ///
    /// This demonstrates when `into_ref` works, but `get` doesn't.
    ///
    /// ```rust
    /// # use abi_stable::RMut;
    /// fn stuff<'a>(x: RMut<'a, i32>) -> &'a i32 {
    ///     x.into_ref()
    /// }
    /// ```
    ///
    /// This doesn't compile, because `get` reborrows `foo`.
    /// ```compile_fail
    /// # use abi_stable::RMut;
    /// fn stuff<'a>(foo: RMut<'a, i32>) -> &'a i32 {
    ///     foo.get()
    /// }
    /// ```
    #[inline(always)]
    pub const fn get(&self) -> &T {
        unsafe { crate::utils::deref!(self.ref_.as_ptr()) }
    }

    /// Copies the value that this `RMut` points to.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = "hello";
    /// let mut rmut = RMut::new(&mut val);
    ///
    /// *rmut.get_mut() = "world";
    ///
    /// assert_eq!(rmut.get_copy(), "world");
    ///
    /// ```
    #[inline(always)]
    pub const fn get_copy(&self) -> T
    where
        T: Copy,
    {
        unsafe { *(self.ref_.as_ptr() as *const T) }
    }

    /// Converts this `RMut<'a, T>` into a `&'a T`
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 89;
    ///
    /// assert_eq!(mutate(RMut::new(&mut val)), &44);
    ///
    /// fn mutate(mut rmut: RMut<'_, u32>) -> &u32 {
    ///     *rmut.get_mut() /= 2;
    ///     rmut.into_ref()
    /// }
    ///
    /// ```
    ///
    #[inline(always)]
    pub const fn into_ref(self) -> &'a T {
        unsafe { crate::utils::deref!(self.ref_.as_ptr()) }
    }

    /// Reborrows this `RMut` into a mutable reference.
    ///
    /// Note that because the mutable reference reborrows this `RMut<'a, T>`
    /// its lifetime argument is strictly smaller.
    /// To turn an `RMut<'a, T>` into a `&'a mut T` (with the same lifetime argument)
    /// you can use [`into_mut`](#method.into_mut).
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 89;
    /// let mut rmut = RMut::new(&mut val);
    ///
    /// assert_eq!(rmut.get_mut(), &mut 89);
    ///
    /// *rmut.get_mut() += 10;
    ///
    /// assert_eq!(rmut.get_mut(), &mut 99);
    ///
    /// ```
    ///
    /// ### Lifetimes
    ///
    /// This demonstrates when `into_mut` works, but `get_mut` doesn't.
    ///
    /// ```rust
    /// # use abi_stable::RMut;
    /// fn stuff<'a>(x: RMut<'a, i32>) -> &'a mut i32 {
    ///     x.into_mut()
    /// }
    /// ```
    ///
    /// This doesn't compile, because `get_mut` reborrows `foo`.
    /// ```compile_fail
    /// # use abi_stable::RMut;
    /// fn stuff<'a>(mut foo: RMut<'a, i32>) -> &'a mut i32 {
    ///     foo.get_mut()
    /// }
    /// ```
    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        unsafe { &mut *self.ref_.as_ptr() }
    }

    /// Converts this `RMut<'a, T>` into a `&'a mut T`
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 13;
    ///
    /// let rmut = RMut::new(&mut val);
    ///
    /// assert_eq!(rmut.get(), &13);
    ///
    /// *rmut.into_mut() += 8;
    ///
    /// assert_eq!(val, 21);
    ///
    /// ```
    #[inline(always)]
    pub fn into_mut(self) -> &'a mut T {
        unsafe { &mut *self.ref_.as_ptr() }
    }

    /// Reborrows this `RMut` as a const raw pointer.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 34;
    /// let rmut = RMut::new(&mut val);
    ///
    /// unsafe {
    ///     assert_eq!(*rmut.as_ptr(), 34);
    /// }
    /// ```
    #[inline]
    pub const fn as_ptr(&self) -> *const T {
        self.ref_.as_ptr()
    }

    /// Reborrows this `RMut` as a mutable raw pointer.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 34;
    /// let mut rmut = RMut::new(&mut val);
    ///
    /// unsafe {
    ///     rmut.as_mut_ptr().write(7);
    ///
    ///     *rmut.as_mut_ptr() *= 2;
    ///
    ///     assert_eq!(val, 14);
    /// }
    /// ```
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.ref_.as_ptr()
    }

    /// Converts this `RMut<'a, T>` into a `*mut T`
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 89;
    /// let rmut = RMut::new(&mut val);
    ///
    /// unsafe {
    ///     let ptr = rmut.into_raw();
    ///
    ///     ptr.write(27);
    ///
    ///     *ptr += 2;
    ///
    ///     assert_eq!(val, 29);
    /// }
    /// ```
    #[inline]
    pub const fn into_raw(self) -> *mut T {
        self.ref_.as_ptr()
    }

    /// Transmutes this `RMut<'a, T>` to a `*mut U`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = Direction::Up;
    /// let rmut = RMut::new(&mut val);
    ///
    /// assert_eq!(rmut.get(), &Direction::Up);
    ///
    /// let ptr = rmut.transmute_into_raw::<u8>();
    ///
    /// unsafe {
    ///     assert_eq!(*ptr, 2);
    ///     *ptr = 3;
    /// }
    ///
    /// assert_eq!(val, Direction::Down);
    ///
    /// #[repr(u8)]
    /// #[derive(Debug, PartialEq)]
    /// enum Direction {
    ///     Left = 0,
    ///     Right = 1,
    ///     Up = 2,
    ///     Down = 3,
    /// }
    ///
    /// ```
    #[inline(always)]
    pub const fn transmute_into_raw<U>(self) -> *mut U {
        self.ref_.as_ptr() as *mut U
    }

    /// Transmutes this `RMut<'a, T>` to a `&'a mut U`.
    ///
    /// # Safety
    ///
    /// Either of these must be the case:
    ///
    /// - [`U` is a prefix of `T`](#type-prefix-exp)
    ///
    /// - `RMut<'a, U>` was the original type of this `RMut<'a, T>`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val = 13u8;
    /// let rmut = RMut::new(&mut val);
    ///
    /// assert_eq!(rmut.get(), &13);
    ///
    /// unsafe {
    ///     *rmut.transmute_into_mut::<i8>() = -1;
    /// }
    ///
    /// assert_eq!(val, 255);
    ///
    /// ```
    #[inline(always)]
    pub unsafe fn transmute_into_mut<U>(self) -> &'a mut U
    where
        U: 'a,
    {
        unsafe { &mut *(self.ref_.as_ptr() as *mut U) }
    }

    /// Transmutes this `RMut<'a, T>` to a `RMut<'a,U>`.
    ///
    /// # Safety
    ///
    /// Either of these must be the case:
    ///
    /// - [`U` is a prefix of `T`](#type-prefix-exp)
    ///
    /// - `RMut<'a, U>` was the original type of this `RMut<'a, T>`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::RMut;
    ///
    /// let mut val: [u32; 3] = [2, 3, 0];
    /// let mut rmut = RMut::new(&mut val);
    ///
    /// unsafe {
    ///     // safety:
    ///     // it's sound to transmute mutable references of arrays into shorter arrays.
    ///     //
    ///     // The `.reborrow()` prevents the `rmut` from being consumed.
    ///     compute_next(rmut.reborrow().transmute::<[u32; 2]>());
    ///     assert_eq!(rmut.get_copy(), [3, 5, 0]);
    ///
    ///     compute_next(rmut.reborrow().transmute::<[u32; 2]>());
    ///     assert_eq!(rmut.get_copy(), [5, 8, 0]);
    ///
    ///     // last use of `rmut`, so no need to reborrow
    ///     compute_next(rmut.transmute::<[u32; 2]>());
    /// }
    ///
    /// assert_eq!(val, [8, 13, 0]);
    ///
    /// fn compute_next(rmut: RMut<'_, [u32; 2]>) {
    ///     let [v0, v1] = rmut.into_mut();
    ///     let next = *v0 + *v1;
    ///     *v0 = std::mem::replace(v1, next);
    /// }
    /// ```
    #[inline(always)]
    pub const unsafe fn transmute<U>(self) -> RMut<'a, U>
    where
        U: 'a,
    {
        unsafe { RMut::from_raw(self.ref_.as_ptr() as *mut U) }
    }

    /// Reborrows this `RMut<'a, T>` into an `RRef<'_, T>`
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::{RMut, RRef};
    ///
    /// let mut val = 77;
    /// let rmut = RMut::new(&mut val);
    ///
    /// for _ in 0..10 {
    ///     assertion(rmut.as_rref());
    /// }
    ///
    /// fn assertion(rref: RRef<'_, u32>) {
    ///     assert_eq!(rref.get_copy(), 77);
    /// }
    /// ```
    #[inline(always)]
    #[allow(clippy::needless_lifetimes)]
    pub const fn as_rref<'r>(&'r self) -> RRef<'r, T> {
        unsafe { RRef::from_raw(self.ref_.as_ptr()) }
    }

    /// Converts this `RMut<'a, T>` to an `RRef<'_, T>`
    ///
    /// # Example
    ///
    /// ```rust
    /// use abi_stable::{RMut, RRef};
    ///
    /// let mut val = 0;
    /// let rmut = RMut::new(&mut val);
    ///
    /// assertion(rmut.into_rref());
    ///
    /// fn assertion(rref: RRef<'_, u32>) {
    ///     assert_eq!(rref.get_copy(), 0);
    /// }
    /// ```
    #[inline(always)]
    pub const fn into_rref(self) -> RRef<'a, T> {
        unsafe { RRef::from_raw(self.ref_.as_ptr()) }
    }
}

unsafe impl<'a, T> AsPtr for RMut<'a, T> {
    #[inline(always)]
    fn as_ptr(&self) -> *const T {
        self.ref_.as_ptr() as *const T
    }
    #[inline(always)]
    fn as_rref(&self) -> RRef<'_, T> {
        unsafe { RRef::from_raw(self.ref_.as_ptr() as *const T) }
    }
}

unsafe impl<'a, T> AsMutPtr for RMut<'a, T> {
    #[inline(always)]
    fn as_mut_ptr(&mut self) -> *mut T {
        self.ref_.as_ptr()
    }

    #[inline(always)]
    fn as_rmut(&mut self) -> RMut<'_, T> {
        self.reborrow()
    }
}

unsafe impl<'a, T> GetPointerKind for RMut<'a, T> {
    type Kind = PK_MutReference;

    type PtrTarget = T;
}

unsafe impl<'a, T, U> CanTransmuteElement<U> for RMut<'a, T>
where
    U: 'a,
{
    type TransmutedPtr = RMut<'a, U>;

    #[inline(always)]
    unsafe fn transmute_element_(self) -> Self::TransmutedPtr {
        unsafe { self.transmute() }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn construction_test() {
        unsafe {
            let val: *mut i32 = &mut 3;
            let mut rmut = RMut::from_raw(val);
            *rmut.get_mut() += 5;
            assert_eq!(rmut.get_copy(), 8);
        }
        {
            let val = &mut 3;
            let mut rmut = RMut::new(val);
            *rmut.get_mut() += 5;
            assert_eq!(rmut.get_copy(), 8);
        }
    }

    #[test]
    fn access() {
        let mut num = 5;
        let mut mutref = RMut::new(&mut num);

        assert_eq!(*mutref.get_mut(), 5);
        *mutref.get_mut() = 21;

        assert_eq!(*mutref.get(), 21);
        assert_eq!(mutref.get_copy(), 21);
        assert_eq!(*mutref.reborrow().into_ref(), 21);

        *mutref.reborrow().into_mut() = 34;

        unsafe {
            assert_eq!(*mutref.as_ptr(), 34);

            *mutref.as_mut_ptr() = 55;

            assert_eq!(*mutref.reborrow().into_raw(), 55);
            *mutref.reborrow().into_raw() = 89;
        }
        assert_eq!(num, 89);
    }

    #[test]
    fn transmutes() {
        let mut num = 0u8;

        unsafe {
            let ptr = RMut::new(&mut num).transmute_into_raw::<Enum>();
            assert_eq!(*ptr, Enum::Foo);

            ptr.write(Enum::Bar);
            assert_eq!(*ptr, Enum::Bar);
            assert_eq!(num, 1);
        }
        unsafe {
            let mref = RMut::new(&mut num).transmute_into_mut::<Enum>();
            assert_eq!(*mref, Enum::Bar);

            *mref = Enum::Qux;
            assert_eq!(*mref, Enum::Qux);
            assert_eq!(num, 2);
        }
        unsafe {
            let mut rmut = RMut::new(&mut num).transmute::<Enum>();
            assert_eq!(rmut, RMut::new(&mut Enum::Qux));

            *rmut.get_mut() = Enum::Foo;
            assert_eq!(*rmut.get(), Enum::Foo);
            assert_eq!(num, 0);
        }
        unsafe {
            let mut rmut: RMut<'_, Enum> = RMut::new(&mut num).transmute_element_();
            assert_eq!(rmut, RMut::new(&mut Enum::Foo));

            *rmut.get_mut() = Enum::Bar;
            assert_eq!(*rmut.get(), Enum::Bar);
            assert_eq!(num, 1);
        }
    }

    #[test]
    fn as_rtype_test() {
        let mut num = 0u8;
        let mut rmut = RMut::new(&mut num);

        assert_eq!(rmut.as_rref(), RRef::new(&0));
        assert_eq!(rmut.reborrow().into_rref(), RRef::new(&0));

        assert_eq!(rmut.as_rmut(), RMut::new(&mut 0));
    }

    #[derive(Debug, PartialEq)]
    #[repr(u8)]
    enum Enum {
        Foo = 0,
        Bar = 1,
        Qux = 2,
    }
}