Skip to content

Commit 9f0b99b

Browse files
committed
Auto merge of #1036 - RalfJung:stacked-borrows-test, r=RalfJung
add an interesting run-pass stacked borrows example
2 parents f74054f + 99282ef commit 9f0b99b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

tests/run-pass/stacked-borrows/stacked-borrows.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ fn main() {
1111
direct_mut_to_const_raw();
1212
two_raw();
1313
shr_and_raw();
14+
disjoint_mutable_subborrows();
1415
}
1516

1617
// Make sure that reading from an `&mut` does, like reborrowing to `&`,
@@ -138,3 +139,31 @@ fn shr_and_raw() { /* unsafe {
138139
*y2 += 1;
139140
// TODO: Once this works, add compile-fail test that tries to read from y1 again.
140141
} */ }
142+
143+
fn disjoint_mutable_subborrows() {
144+
struct Foo {
145+
a: String,
146+
b: Vec<u32>,
147+
}
148+
149+
unsafe fn borrow_field_a<'a>(this:*mut Foo) -> &'a mut String {
150+
&mut (*this).a
151+
}
152+
153+
unsafe fn borrow_field_b<'a>(this:*mut Foo) -> &'a mut Vec<u32> {
154+
&mut (*this).b
155+
}
156+
157+
let mut foo = Foo {
158+
a: "hello".into(),
159+
b: vec![0,1,2],
160+
};
161+
162+
let ptr = &mut foo as *mut Foo;
163+
164+
let a = unsafe{ borrow_field_a(ptr) };
165+
let b = unsafe{ borrow_field_b(ptr) };
166+
b.push(4);
167+
a.push_str(" world");
168+
dbg!(a,b);
169+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[$DIR/stacked-borrows.rs:168] a = "hello world"
2+
[$DIR/stacked-borrows.rs:168] b = [
3+
0,
4+
1,
5+
2,
6+
4,
7+
]

0 commit comments

Comments
 (0)