Skip to content

Commit 75e471a

Browse files
committed
Add MaybeUninit::drop.
ManuallyDrop's documentation tells the user to use MaybeUninit instead when handling uninitialized data. However, the main functionality of ManuallyDrop (drop) was not available directly on MaybeUninit. Adding it makes it easier to switch from one to the other.
1 parent 7bc0bf7 commit 75e471a

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

library/core/src/mem/maybe_uninit.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::any::type_name;
22
use crate::fmt;
33
use crate::intrinsics;
44
use crate::mem::ManuallyDrop;
5+
use crate::ptr;
56

67
/// A wrapper type to construct uninitialized instances of `T`.
78
///
@@ -573,6 +574,28 @@ impl<T> MaybeUninit<T> {
573574
}
574575
}
575576

577+
/// Drops the contained value in place.
578+
///
579+
/// If you have ownership of the `MaybeUninit`, it is preferable to use
580+
/// [`assume_init`] instead, which prevents duplicating the content.
581+
///
582+
/// # Safety
583+
///
584+
/// Calling this when the content is not yet fully initialized causes undefined
585+
/// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
586+
/// is in an initialized state.
587+
///
588+
/// This function runs the destructor of the contained value in place.
589+
/// Afterwards, the memory is considered uninitialized again, but remains unmodified.
590+
///
591+
/// [`assume_init`]: MaybeUninit::assume_init
592+
#[unstable(feature = "maybe_uninit_extra", issue = "63567")]
593+
pub unsafe fn drop(&mut self) {
594+
// SAFETY: the caller must guarantee that `self` is initialized.
595+
// Dropping the value in place is safe if that is the case.
596+
unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
597+
}
598+
576599
/// Gets a shared reference to the contained value.
577600
///
578601
/// This can be useful when we want to access a `MaybeUninit` that has been

0 commit comments

Comments
 (0)