File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -168,6 +168,32 @@ pub struct S {
168
168
data : UnsafePinned <i32 >, // <!---- here
169
169
ptr_to_data : * mut i32 ,
170
170
}
171
+
172
+ impl S {
173
+ pub fn new () -> Self {
174
+ S { data : UnsafePinned :: new (42 ), ptr_to_data : ptr :: null_mut () }
175
+ }
176
+
177
+ pub fn get_data (self : Pin <& mut Self >) -> i32 {
178
+ // SAFETY: We're not moving anything.
179
+ let this = unsafe { Pin :: get_unchecked_mut (self ) };
180
+ if this . ptr_to_data. is_null () {
181
+ this . ptr_to_data = UnsafePinned :: raw_get_mut (ptr :: addr_of_mut! (this . data));
182
+ }
183
+ // SAFETY: if the pointer is non-null, then we are pinned and it points to the `data` field.
184
+ unsafe { this . ptr_to_data. read () }
185
+ }
186
+
187
+ pub fn set_data (self : Pin <& mut Self >, data : i32 ) {
188
+ // SAFETY: We're not moving anything.
189
+ let this = unsafe { Pin :: get_unchecked_mut (self ) };
190
+ if this . ptr_to_data. is_null () {
191
+ this . ptr_to_data = UnsafePinned :: raw_get_mut (ptr :: addr_of_mut! (this . data));
192
+ }
193
+ // SAFETY: if the pointer is non-null, then we are pinned and it points to the `data` field.
194
+ unsafe { this . ptr_to_data. write (data ) }
195
+ }
196
+ }
171
197
```
172
198
173
199
This lets the compiler know that mutable references to ` data ` might still have aliases, and so optimizations cannot assume that no aliases exist.
You can’t perform that action at this time.
0 commit comments