Skip to content

Commit b032a15

Browse files
authored
Rollup merge of #75250 - RalfJung:uninit-const-ptr, r=oli-obk
make MaybeUninit::as_(mut_)ptr const I think it was just an oversight that they are not const yet. I also changed their implementation as the old one created references to uninitialized memory.^^
2 parents 255434d + ec5d78d commit b032a15

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

Diff for: library/core/src/mem/maybe_uninit.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -405,9 +405,11 @@ impl<T> MaybeUninit<T> {
405405
/// (Notice that the rules around references to uninitialized data are not finalized yet, but
406406
/// until they are, it is advisable to avoid them.)
407407
#[stable(feature = "maybe_uninit", since = "1.36.0")]
408+
#[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
408409
#[inline(always)]
409-
pub fn as_ptr(&self) -> *const T {
410-
unsafe { &*self.value as *const T }
410+
pub const fn as_ptr(&self) -> *const T {
411+
// `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
412+
self as *const _ as *const T
411413
}
412414

413415
/// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
@@ -442,9 +444,11 @@ impl<T> MaybeUninit<T> {
442444
/// (Notice that the rules around references to uninitialized data are not finalized yet, but
443445
/// until they are, it is advisable to avoid them.)
444446
#[stable(feature = "maybe_uninit", since = "1.36.0")]
447+
#[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
445448
#[inline(always)]
446-
pub fn as_mut_ptr(&mut self) -> *mut T {
447-
unsafe { &mut *self.value as *mut T }
449+
pub const fn as_mut_ptr(&mut self) -> *mut T {
450+
// `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
451+
self as *mut _ as *mut T
448452
}
449453

450454
/// Extracts the value from the `MaybeUninit<T>` container. This is a great way

0 commit comments

Comments
 (0)