Skip to content

Commit ba8eb76

Browse files
committed
add an interesting demo for &mut being unique
1 parent 5a801c0 commit ba8eb76

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
fn demo_mut_advanced_unique(our: &mut i32) -> i32 {
2+
unknown_code_1(&*our);
3+
4+
// This "re-asserts" uniqueness of the reference: After writing, we know
5+
// our tag is at the top of the stack.
6+
*our = 5;
7+
8+
unknown_code_2();
9+
10+
// We know this will return 5
11+
*our
12+
}
13+
14+
// Now comes the evil context
15+
use std::ptr;
16+
17+
static mut LEAK: *mut i32 = ptr::null_mut();
18+
19+
fn unknown_code_1(x: &i32) { unsafe {
20+
LEAK = x as *const _ as *mut _;
21+
} }
22+
23+
fn unknown_code_2() { unsafe {
24+
*LEAK = 7; //~ ERROR does not exist on the stack
25+
} }
26+
27+
fn main() {
28+
assert_eq!(demo_mut_advanced_unique(&mut 0), 5);
29+
}

0 commit comments

Comments
 (0)