Rollup merge of #111654 - JoJoJet:unsafe-cell-from-mut-lib, r=joshtriplett

Add a conversion from `&mut T` to `&mut UnsafeCell<T>`

Provides a safe way of downgrading an exclusive reference into an alias-able `&UnsafeCell<T>` reference.

ACP: https://github.com/rust-lang/libs-team/issues/198.
This commit is contained in:
Dylan DPC 2023-05-17 11:13:57 +05:30 committed by GitHub
commit 71fdb95272
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View File

@ -1584,6 +1584,7 @@
unrestricted_attribute_tokens,
unsafe_block_in_unsafe_fn,
unsafe_cell,
unsafe_cell_from_mut,
unsafe_no_drop_flag,
unsafe_pin_internals,
unsize,

View File

@ -2030,6 +2030,27 @@ pub const fn into_inner(self) -> 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.