Skip to content

Commit 3318657

Browse files
committed
test Ref/RefMut protector interactions
1 parent c4c2716 commit 3318657

File tree

2 files changed

+68
-33
lines changed

2 files changed

+68
-33
lines changed

tests/run-pass/refcell.rs

-33
This file was deleted.
+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
use std::cell::{RefCell, Ref, RefMut};
2+
3+
fn main() {
4+
basic();
5+
ref_protector();
6+
ref_mut_protector();
7+
}
8+
9+
fn basic() {
10+
let c = RefCell::new(42);
11+
{
12+
let s1 = c.borrow();
13+
let _x: i32 = *s1;
14+
let s2 = c.borrow();
15+
let _x: i32 = *s1;
16+
let _y: i32 = *s2;
17+
let _x: i32 = *s1;
18+
let _y: i32 = *s2;
19+
}
20+
{
21+
let mut m = c.borrow_mut();
22+
let _z: i32 = *m;
23+
{
24+
let s: &i32 = &*m;
25+
let _x = *s;
26+
}
27+
*m = 23;
28+
let _z: i32 = *m;
29+
}
30+
{
31+
let s1 = c.borrow();
32+
let _x: i32 = *s1;
33+
let s2 = c.borrow();
34+
let _x: i32 = *s1;
35+
let _y: i32 = *s2;
36+
let _x: i32 = *s1;
37+
let _y: i32 = *s2;
38+
}
39+
}
40+
41+
// Adding a Stacked Borrows protector for `Ref` would break this
42+
fn ref_protector() {
43+
fn break_it(rc: &RefCell<i32>, r: Ref<'_, i32>) {
44+
// `r` has a shared reference, it is passed in as argument and hence
45+
// a protector is added that marks this memory as read-only for the entire
46+
// duration of this function.
47+
drop(r);
48+
// *oops* here we can mutate that memory.
49+
*rc.borrow_mut() = 2;
50+
}
51+
52+
let rc = RefCell::new(0);
53+
break_it(&rc, rc.borrow())
54+
}
55+
56+
fn ref_mut_protector() {
57+
fn break_it(rc: &RefCell<i32>, r: RefMut<'_, i32>) {
58+
// `r` has a shared reference, it is passed in as argument and hence
59+
// a protector is added that marks this memory as inaccessible for the entire
60+
// duration of this function
61+
drop(r);
62+
// *oops* here we can mutate that memory.
63+
*rc.borrow_mut() = 2;
64+
}
65+
66+
let rc = RefCell::new(0);
67+
break_it(&rc, rc.borrow_mut())
68+
}

0 commit comments

Comments
 (0)