Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation about the memory layout of UnsafeCell<T> #101717

Merged
merged 4 commits into from
Oct 16, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
expand documentation on type conversion w.r.t. UnsafeCell
  • Loading branch information
Pointerbender committed Sep 14, 2022
commit 13bc0996ddb64919feefb256ad9468087333121d
31 changes: 30 additions & 1 deletion library/core/src/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1811,7 +1811,36 @@ impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
///
/// [`.get_mut()`]: `UnsafeCell::get_mut`
///
/// `UnsafeCell<T>` has the same in-memory representation as its inner type `T`.
/// `UnsafeCell<T>` has the same in-memory representation as its inner type `T`. A consequence
/// of this guarantee is that it is possible to convert between `T` and `UnsafeCell<T>`.
/// However, it is only valid to obtain a `*mut T` pointer or `&mut T` reference to the
/// contents of an `UnsafeCell<T>` through [`.get()`], [`.raw_get()`] or [`.get_mut()`], e.g.:
Pointerbender marked this conversation as resolved.
Show resolved Hide resolved
///
/// ```rust
/// use std::cell::UnsafeCell;
///
/// let mut x: UnsafeCell<u32> = UnsafeCell::new(5);
/// let p1: &UnsafeCell<u32> = &x;
/// // using `.get()` is okay:
/// unsafe {
/// // SAFETY: there exist no other references to the contents of `x`
/// let p2: &mut u32 = &mut *p1.get();
/// };
/// // using `.raw_get()` is also okay:
/// unsafe {
/// // SAFETY: there exist no other references to the contents of `x` in this scope
/// let p2: &mut u32 = &mut *UnsafeCell::raw_get(p1 as *const _);
/// };
/// // using `.get_mut()` is always safe:
/// let p2: &mut u32 = x.get_mut();
/// // but the following is not allowed!
/// // let p2: &mut u32 = unsafe {
/// // let t: *mut u32 = &x as *const _ as *mut u32;
/// // &mut *t
/// // };
/// ```
///
/// [`.raw_get()`]: `UnsafeCell::raw_get`
///
Pointerbender marked this conversation as resolved.
Show resolved Hide resolved
/// # Examples
///
Expand Down