File tree 2 files changed +68
-33
lines changed
2 files changed +68
-33
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments