Skip to content

Commit 86971ce

Browse files
authored
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: rust-lang/libs-team#198.
2 parents 48bd87a + 0332d7b commit 86971ce

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

core/src/cell.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2030,6 +2030,27 @@ impl<T> UnsafeCell<T> {
20302030
}
20312031

20322032
impl<T: ?Sized> UnsafeCell<T> {
2033+
/// Converts from `&mut T` to `&mut UnsafeCell<T>`.
2034+
///
2035+
/// # Examples
2036+
///
2037+
/// ```
2038+
/// # #![feature(unsafe_cell_from_mut)]
2039+
/// use std::cell::UnsafeCell;
2040+
///
2041+
/// let mut val = 42;
2042+
/// let uc = UnsafeCell::from_mut(&mut val);
2043+
///
2044+
/// *uc.get_mut() -= 1;
2045+
/// assert_eq!(*uc.get_mut(), 41);
2046+
/// ```
2047+
#[inline(always)]
2048+
#[unstable(feature = "unsafe_cell_from_mut", issue = "111645")]
2049+
pub const fn from_mut(value: &mut T) -> &mut UnsafeCell<T> {
2050+
// SAFETY: `UnsafeCell<T>` has the same memory layout as `T` due to #[repr(transparent)].
2051+
unsafe { &mut *(value as *mut T as *mut UnsafeCell<T>) }
2052+
}
2053+
20332054
/// Gets a mutable pointer to the wrapped value.
20342055
///
20352056
/// This can be cast to a pointer of any kind.

0 commit comments

Comments
 (0)