From ba8eb7608ea6520238a1d587197a795e9dc7147a Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 12 Nov 2018 19:30:35 +0100 Subject: [PATCH] add an interesting demo for &mut being unique --- .../mut_exclusive_violation1.rs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 tests/compile-fail/stacked_borrows/mut_exclusive_violation1.rs diff --git a/tests/compile-fail/stacked_borrows/mut_exclusive_violation1.rs b/tests/compile-fail/stacked_borrows/mut_exclusive_violation1.rs new file mode 100644 index 000000000000..255e35b14558 --- /dev/null +++ b/tests/compile-fail/stacked_borrows/mut_exclusive_violation1.rs @@ -0,0 +1,29 @@ +fn demo_mut_advanced_unique(our: &mut i32) -> i32 { + unknown_code_1(&*our); + + // This "re-asserts" uniqueness of the reference: After writing, we know + // our tag is at the top of the stack. + *our = 5; + + unknown_code_2(); + + // We know this will return 5 + *our +} + +// Now comes the evil context +use std::ptr; + +static mut LEAK: *mut i32 = ptr::null_mut(); + +fn unknown_code_1(x: &i32) { unsafe { + LEAK = x as *const _ as *mut _; +} } + +fn unknown_code_2() { unsafe { + *LEAK = 7; //~ ERROR does not exist on the stack +} } + +fn main() { + assert_eq!(demo_mut_advanced_unique(&mut 0), 5); +}