about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMara Bos <m-ou.se@m-ou.se>2020-09-08 19:01:05 +0200
committerMara Bos <m-ou.se@m-ou.se>2020-09-08 19:01:05 +0200
commit75e471ade9ea6095eef6cd4ef35cfc0b8bfc9410 (patch)
tree4eb3a350829ec425c51d7fa45201f1e863c2fb76
parent7bc0bf72545f5d6ac6d9639391da875d5e147d9a (diff)
downloadrust-75e471ade9ea6095eef6cd4ef35cfc0b8bfc9410.tar.gz
rust-75e471ade9ea6095eef6cd4ef35cfc0b8bfc9410.zip
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.
-rw-r--r--library/core/src/mem/maybe_uninit.rs23
1 files changed, 23 insertions, 0 deletions
diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs
index b64abf68c5e..e826ec0a5e3 100644
--- a/library/core/src/mem/maybe_uninit.rs
+++ b/library/core/src/mem/maybe_uninit.rs
@@ -2,6 +2,7 @@ use crate::any::type_name;
 use crate::fmt;
 use crate::intrinsics;
 use crate::mem::ManuallyDrop;
+use crate::ptr;
 
 /// A wrapper type to construct uninitialized instances of `T`.
 ///
@@ -573,6 +574,28 @@ impl<T> MaybeUninit<T> {
         }
     }
 
+    /// Drops the contained value in place.
+    ///
+    /// If you have ownership of the `MaybeUninit`, it is preferable to use
+    /// [`assume_init`] instead, which prevents duplicating the content.
+    ///
+    /// # Safety
+    ///
+    /// Calling this when the content is not yet fully initialized causes undefined
+    /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
+    /// is in an initialized state.
+    ///
+    /// This function runs the destructor of the contained value in place.
+    /// Afterwards, the memory is considered uninitialized again, but remains unmodified.
+    ///
+    /// [`assume_init`]: MaybeUninit::assume_init
+    #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
+    pub unsafe fn drop(&mut self) {
+        // SAFETY: the caller must guarantee that `self` is initialized.
+        // Dropping the value in place is safe if that is the case.
+        unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
+    }
+
     /// Gets a shared reference to the contained value.
     ///
     /// This can be useful when we want to access a `MaybeUninit` that has been