2020-01-08 05:39:38 -06:00
|
|
|
// Demonstrate that "rogue" `DerefMut` impls for `&T` are not allowed.
|
|
|
|
//
|
|
|
|
// https://github.com/rust-lang/rust/issues/66544
|
|
|
|
|
|
|
|
use std::cell::Cell;
|
|
|
|
use std::marker::PhantomPinned;
|
|
|
|
use std::ops::DerefMut;
|
|
|
|
use std::pin::Pin;
|
|
|
|
|
|
|
|
struct MyType<'a>(Cell<Option<&'a mut MyType<'a>>>, PhantomPinned);
|
|
|
|
|
2020-01-08 13:10:59 -06:00
|
|
|
impl<'a> DerefMut for &'a MyType<'a> {
|
2020-04-22 07:18:22 -05:00
|
|
|
//~^ ERROR E0751
|
2020-01-08 05:39:38 -06:00
|
|
|
fn deref_mut(&mut self) -> &mut MyType<'a> {
|
2020-04-21 14:11:32 -05:00
|
|
|
self.0.take().unwrap()
|
2020-01-08 05:39:38 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let mut unpinned = MyType(Cell::new(None), PhantomPinned);
|
|
|
|
let bad_addr = &unpinned as *const MyType<'_> as usize;
|
|
|
|
let p = Box::pin(MyType(Cell::new(Some(&mut unpinned)), PhantomPinned));
|
|
|
|
|
|
|
|
// p_ref is okay: it does not point to the bad_addr
|
|
|
|
let mut p_ref: Pin<&MyType<'_>> = p.as_ref();
|
|
|
|
assert_ne!(bad_addr, &*p_ref as *const _ as usize);
|
|
|
|
|
|
|
|
// but p_mut does point to bad_addr! this is unsound
|
|
|
|
let p_mut: Pin<&mut MyType<'_>> = p_ref.as_mut();
|
|
|
|
assert_eq!(bad_addr, &*p_mut as *const _ as usize);
|
|
|
|
|
|
|
|
println!("oh no!");
|
|
|
|
}
|