Skip to content

Commit e98f367

Browse files
committed
add fixed code example
1 parent bfb8c4b commit e98f367

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

text/0000-unsafe-aliased.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,32 @@ pub struct S {
168168
data: UnsafePinned<i32>, // <!---- here
169169
ptr_to_data: *mut i32,
170170
}
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+
}
171197
```
172198

173199
This lets the compiler know that mutable references to `data` might still have aliases, and so optimizations cannot assume that no aliases exist.

0 commit comments

Comments
 (0)