File tree Expand file tree Collapse file tree 2 files changed +77
-0
lines changed Expand file tree Collapse file tree 2 files changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ [package ]
2
+ name = " x-pin-experiments"
3
+ version = " 0.1.0"
4
+ edition = " 2021"
5
+
6
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7
+
8
+ [dependencies ]
9
+ rand = " 0.8.5"
Original file line number Diff line number Diff line change
1
+ use rand:: prelude:: * ;
2
+
3
+ fn main ( ) {
4
+ selfref1 ( ) ;
5
+ }
6
+
7
+ fn selfref1 ( ) {
8
+ let mut first = SelfRef1 :: new ( 0 ) ;
9
+ println ! ( "It's OK: {}" , first. b( ) ) ;
10
+ let second = std:: mem:: replace ( first. as_mut ( ) , * SelfRef1 :: new ( 2 ) ) ;
11
+ println ! ( "Ooops: {}" , first. b( ) ) ;
12
+ println ! ( "Ooops: {}" , second. b( ) ) ;
13
+ }
14
+
15
+ #[ derive( Debug ) ]
16
+ struct SelfRef1 {
17
+ a : [ char ; 3 ] ,
18
+ b : * const char ,
19
+ }
20
+
21
+ impl SelfRef1 {
22
+ fn new ( n : usize ) -> Box < Self > {
23
+ let mut selfref = Box :: new ( Self {
24
+ a : [ 'a' , 'b' , 'c' ] ,
25
+ b : std:: ptr:: null ( ) ,
26
+ } ) ;
27
+ selfref. b = & selfref. a [ n] as * const _ ;
28
+ selfref
29
+ }
30
+
31
+ fn b ( & self ) -> & char {
32
+ unsafe { & * self . b }
33
+ }
34
+ }
35
+
36
+ // =======================================================
37
+ use std:: pin:: Pin ;
38
+
39
+ fn selfref2 ( ) {
40
+ let mut first = SelfRef2 :: new ( 0 ) ;
41
+ println ! ( "It's OK: {}" , first. b( ) ) ;
42
+ let mut second = SelfRef2 :: new ( 2 ) ;
43
+ std:: mem:: swap ( & mut first, & mut second) ;
44
+ println ! ( "Ooops: {}" , first. b( ) ) ;
45
+ }
46
+
47
+ #[ derive( Debug ) ]
48
+ struct SelfRef2 {
49
+ a : [ char ; 3 ] ,
50
+ b : * const char ,
51
+ _pin : std:: marker:: PhantomPinned ,
52
+ }
53
+
54
+ impl SelfRef2 {
55
+ fn new ( n : usize ) -> Pin < Box < Self > > {
56
+ let mut selfref = Box :: pin ( Self {
57
+ a : [ 'a' , 'b' , 'c' ] ,
58
+ b : std:: ptr:: null ( ) ,
59
+ _pin : std:: marker:: PhantomPinned ,
60
+ } ) ;
61
+ //selfref.b = &selfref.a[n] as *const _;
62
+ selfref
63
+ }
64
+
65
+ fn b ( & self ) -> & char {
66
+ unsafe { & * self . b }
67
+ }
68
+ }
You can’t perform that action at this time.
0 commit comments