Skip to content

Commit 71fdb95

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 bc3b94a + ffacb88 commit 71fdb95

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1584,6 +1584,7 @@ symbols! {
15841584
unrestricted_attribute_tokens,
15851585
unsafe_block_in_unsafe_fn,
15861586
unsafe_cell,
1587+
unsafe_cell_from_mut,
15871588
unsafe_no_drop_flag,
15881589
unsafe_pin_internals,
15891590
unsize,

library/core/src/cell.rs

+21
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)