]> git.lizzy.rs Git - rust.git/commitdiff
add an interesting run-pass stacked borrows example
authorRalf Jung <post@ralfj.de>
Tue, 5 Nov 2019 10:05:02 +0000 (11:05 +0100)
committerRalf Jung <post@ralfj.de>
Tue, 5 Nov 2019 10:05:02 +0000 (11:05 +0100)
tests/run-pass/stacked-borrows/stacked-borrows.rs
tests/run-pass/stacked-borrows/stacked-borrows.stderr [new file with mode: 0644]

index afa364e8564381a910287d92f187474027169ffa..fe6a9a54d4f34ad0afeed535e887e50cda3b708e 100644 (file)
@@ -11,6 +11,7 @@ fn main() {
     direct_mut_to_const_raw();
     two_raw();
     shr_and_raw();
+    disjoint_mutable_subborrows();
 }
 
 // Make sure that reading from an `&mut` does, like reborrowing to `&`,
@@ -138,3 +139,31 @@ fn shr_and_raw() { /* unsafe {
     *y2 += 1;
     // TODO: Once this works, add compile-fail test that tries to read from y1 again.
 } */ }
+
+fn disjoint_mutable_subborrows() {
+    struct Foo {
+        a: String,
+        b: Vec<u32>,
+    }
+
+    unsafe fn borrow_field_a<'a>(this:*mut Foo) -> &'a mut String {
+        &mut (*this).a
+    }
+
+    unsafe fn borrow_field_b<'a>(this:*mut Foo) -> &'a mut Vec<u32> {
+        &mut (*this).b
+    }
+
+    let mut foo = Foo {
+        a: "hello".into(),
+        b: vec![0,1,2],
+    };
+
+    let ptr = &mut foo as *mut Foo;
+
+    let a = unsafe{ borrow_field_a(ptr) };
+    let b = unsafe{ borrow_field_b(ptr) };
+    b.push(4);
+    a.push_str(" world");
+    dbg!(a,b);
+}
diff --git a/tests/run-pass/stacked-borrows/stacked-borrows.stderr b/tests/run-pass/stacked-borrows/stacked-borrows.stderr
new file mode 100644 (file)
index 0000000..4493d45
--- /dev/null
@@ -0,0 +1,7 @@
+[$DIR/stacked-borrows.rs:168] a = "hello world"
+[$DIR/stacked-borrows.rs:168] b = [
+    0,
+    1,
+    2,
+    4,
+]