1 // Demonstrate that "rogue" `DerefMut` impls for `&T` are not allowed.
3 // https://github.com/rust-lang/rust/issues/66544
6 use std::marker::PhantomPinned;
7 use std::ops::DerefMut;
10 struct MyType<'a>(Cell<Option<&'a mut MyType<'a>>>, PhantomPinned);
12 impl<'a> DerefMut for &'a MyType<'a> {
14 fn deref_mut(&mut self) -> &mut MyType<'a> {
15 self.0.take().unwrap()
20 let mut unpinned = MyType(Cell::new(None), PhantomPinned);
21 let bad_addr = &unpinned as *const MyType<'_> as usize;
22 let p = Box::pin(MyType(Cell::new(Some(&mut unpinned)), PhantomPinned));
24 // p_ref is okay: it does not point to the bad_addr
25 let mut p_ref: Pin<&MyType<'_>> = p.as_ref();
26 assert_ne!(bad_addr, &*p_ref as *const _ as usize);
28 // but p_mut does point to bad_addr! this is unsound
29 let p_mut: Pin<&mut MyType<'_>> = p_ref.as_mut();
30 assert_eq!(bad_addr, &*p_mut as *const _ as usize);