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 a conversion from &mut T to &mut UnsafeCell<T> #111654

Merged
merged 1 commit into from
May 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1583,6 +1583,7 @@ symbols! {
unrestricted_attribute_tokens,
unsafe_block_in_unsafe_fn,
unsafe_cell,
unsafe_cell_from_mut,
unsafe_no_drop_flag,
unsafe_pin_internals,
unsize,
Expand Down
21 changes: 21 additions & 0 deletions library/core/src/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2030,6 +2030,27 @@ impl<T> UnsafeCell<T> {
}

impl<T: ?Sized> UnsafeCell<T> {
/// Converts from `&mut T` to `&mut UnsafeCell<T>`.
///
/// # Examples
///
/// ```
/// # #![feature(unsafe_cell_from_mut)]
/// use std::cell::UnsafeCell;
///
/// let mut val = 42;
/// let uc = UnsafeCell::from_mut(&mut val);
///
/// *uc.get_mut() -= 1;
/// assert_eq!(*uc.get_mut(), 41);
/// ```
#[inline(always)]
#[unstable(feature = "unsafe_cell_from_mut", issue = "111645")]
pub const fn from_mut(value: &mut T) -> &mut UnsafeCell<T> {
// SAFETY: `UnsafeCell<T>` has the same memory layout as `T` due to #[repr(transparent)].
unsafe { &mut *(value as *mut T as *mut UnsafeCell<T>) }
}

/// Gets a mutable pointer to the wrapped value.
///
/// This can be cast to a pointer of any kind.
Expand Down