core/mem/manually_drop.rs
1#[cfg(not(feature = "ferrocene_subset"))]
2use crate::cmp::Ordering;
3#[cfg(not(feature = "ferrocene_subset"))]
4use crate::hash::{Hash, Hasher};
5use crate::marker::{Destruct, StructuralPartialEq};
6use crate::mem::MaybeDangling;
7use crate::ops::{Deref, DerefMut, DerefPure};
8use crate::ptr;
9
10/// A wrapper to inhibit the compiler from automatically calling `T`’s
11/// destructor. This wrapper is 0-cost.
12///
13/// `ManuallyDrop<T>` is guaranteed to have the same layout and bit validity as
14/// `T`, and is subject to the same layout optimizations as `T`. As a
15/// consequence, it has *no effect* on the assumptions that the compiler makes
16/// about its contents. For example, initializing a `ManuallyDrop<&mut T>` with
17/// [`mem::zeroed`] is undefined behavior. If you need to handle uninitialized
18/// data, use [`MaybeUninit<T>`] instead.
19///
20/// Note that accessing the value inside a `ManuallyDrop<T>` is safe. This means
21/// that a `ManuallyDrop<T>` whose content has been dropped must not be exposed
22/// through a public safe API. Correspondingly, `ManuallyDrop::drop` is unsafe.
23///
24/// # `ManuallyDrop` and drop order
25///
26/// Rust has a well-defined [drop order] of values. To make sure that fields or
27/// locals are dropped in a specific order, reorder the declarations such that
28/// the implicit drop order is the correct one.
29///
30/// It is possible to use `ManuallyDrop` to control the drop order, but this
31/// requires unsafe code and is hard to do correctly in the presence of
32/// unwinding.
33///
34/// For example, if you want to make sure that a specific field is dropped after
35/// the others, make it the last field of a struct:
36///
37/// ```
38/// struct Context;
39///
40/// struct Widget {
41/// children: Vec<Widget>,
42/// // `context` will be dropped after `children`.
43/// // Rust guarantees that fields are dropped in the order of declaration.
44/// context: Context,
45/// }
46/// ```
47///
48/// # Interaction with `Box`
49///
50/// Currently, if you have a `ManuallyDrop<T>`, where the type `T` is a `Box` or
51/// contains a `Box` inside, then dropping the `T` followed by moving the
52/// `ManuallyDrop<T>` is [considered to be undefined
53/// behavior](https://github.com/rust-lang/unsafe-code-guidelines/issues/245).
54/// That is, the following code causes undefined behavior:
55///
56/// ```no_run
57/// use std::mem::ManuallyDrop;
58///
59/// let mut x = ManuallyDrop::new(Box::new(42));
60/// unsafe {
61/// ManuallyDrop::drop(&mut x);
62/// }
63/// let y = x; // Undefined behavior!
64/// ```
65///
66/// This is [likely to change in the
67/// future](https://rust-lang.github.io/rfcs/3336-maybe-dangling.html). In the
68/// meantime, consider using [`MaybeUninit`] instead.
69///
70/// # Safety hazards when storing `ManuallyDrop` in a struct or an enum.
71///
72/// Special care is needed when all of the conditions below are met:
73/// * A struct or enum contains a `ManuallyDrop`.
74/// * The `ManuallyDrop` is not inside a `union`.
75/// * The struct or enum is part of public API, or is stored in a struct or an
76/// enum that is part of public API.
77/// * There is code that drops the contents of the `ManuallyDrop` field, and
78/// this code is outside the struct or enum's `Drop` implementation.
79///
80/// In particular, the following hazards may occur:
81///
82/// #### Storing generic types
83///
84/// If the `ManuallyDrop` contains a client-supplied generic type, the client
85/// might provide a `Box` as that type. This would cause undefined behavior when
86/// the struct or enum is later moved, as mentioned in the previous section. For
87/// example, the following code causes undefined behavior:
88///
89/// ```no_run
90/// use std::mem::ManuallyDrop;
91///
92/// pub struct BadOption<T> {
93/// // Invariant: Has been dropped if `is_some` is false.
94/// value: ManuallyDrop<T>,
95/// is_some: bool,
96/// }
97/// impl<T> BadOption<T> {
98/// pub fn new(value: T) -> Self {
99/// Self { value: ManuallyDrop::new(value), is_some: true }
100/// }
101/// pub fn change_to_none(&mut self) {
102/// if self.is_some {
103/// self.is_some = false;
104/// unsafe {
105/// // SAFETY: `value` hasn't been dropped yet, as per the invariant
106/// // (This is actually unsound!)
107/// ManuallyDrop::drop(&mut self.value);
108/// }
109/// }
110/// }
111/// }
112///
113/// // In another crate:
114///
115/// let mut option = BadOption::new(Box::new(42));
116/// option.change_to_none();
117/// let option2 = option; // Undefined behavior!
118/// ```
119///
120/// #### Deriving traits
121///
122/// Deriving `Debug`, `Clone`, `PartialEq`, `PartialOrd`, `Ord`, or `Hash` on
123/// the struct or enum could be unsound, since the derived implementations of
124/// these traits would access the `ManuallyDrop` field. For example, the
125/// following code causes undefined behavior:
126///
127/// ```no_run
128/// use std::mem::ManuallyDrop;
129///
130/// // This derive is unsound in combination with the `ManuallyDrop::drop` call.
131/// #[derive(Debug)]
132/// pub struct Foo {
133/// value: ManuallyDrop<String>,
134/// }
135/// impl Foo {
136/// pub fn new() -> Self {
137/// let mut temp = Self {
138/// value: ManuallyDrop::new(String::from("Unsafe rust is hard."))
139/// };
140/// unsafe {
141/// // SAFETY: `value` hasn't been dropped yet.
142/// ManuallyDrop::drop(&mut temp.value);
143/// }
144/// temp
145/// }
146/// }
147///
148/// // In another crate:
149///
150/// let foo = Foo::new();
151/// println!("{:?}", foo); // Undefined behavior!
152/// ```
153///
154/// [drop order]: https://doc.rust-lang.org/reference/destructors.html
155/// [`mem::zeroed`]: crate::mem::zeroed
156/// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
157/// [`MaybeUninit`]: crate::mem::MaybeUninit
158#[stable(feature = "manually_drop", since = "1.20.0")]
159#[lang = "manually_drop"]
160#[derive(Copy, Clone, Debug, Default)]
161#[repr(transparent)]
162#[rustc_pub_transparent]
163pub struct ManuallyDrop<T: ?Sized> {
164 value: MaybeDangling<T>,
165}
166
167impl<T> ManuallyDrop<T> {
168 /// Wrap a value to be manually dropped.
169 ///
170 /// # Examples
171 ///
172 /// ```rust
173 /// use std::mem::ManuallyDrop;
174 /// let mut x = ManuallyDrop::new(String::from("Hello World!"));
175 /// x.truncate(5); // You can still safely operate on the value
176 /// assert_eq!(*x, "Hello");
177 /// // But `Drop` will not be run here
178 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
179 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
180 /// # let _ = ManuallyDrop::into_inner(x);
181 /// ```
182 #[must_use = "if you don't need the wrapper, you can use `mem::forget` instead"]
183 #[stable(feature = "manually_drop", since = "1.20.0")]
184 #[rustc_const_stable(feature = "const_manually_drop", since = "1.32.0")]
185 #[inline(always)]
186 pub const fn new(value: T) -> ManuallyDrop<T> {
187 ManuallyDrop { value: MaybeDangling::new(value) }
188 }
189
190 /// Extracts the value from the `ManuallyDrop` container.
191 ///
192 /// This allows the value to be dropped again.
193 ///
194 /// # Examples
195 ///
196 /// ```rust
197 /// use std::mem::ManuallyDrop;
198 /// let x = ManuallyDrop::new(Box::new(()));
199 /// let _: Box<()> = ManuallyDrop::into_inner(x); // This drops the `Box`.
200 /// ```
201 #[stable(feature = "manually_drop", since = "1.20.0")]
202 #[rustc_const_stable(feature = "const_manually_drop", since = "1.32.0")]
203 #[inline(always)]
204 pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
205 // Cannot use `MaybeDangling::into_inner` as that does not yet have the desired semantics.
206 // SAFETY: We know this is a valid `T`. `slot` will not be dropped.
207 unsafe { (&raw const slot).cast::<T>().read() }
208 }
209
210 /// Takes the value from the `ManuallyDrop<T>` container out.
211 ///
212 /// This method is primarily intended for moving out values in drop.
213 /// Instead of using [`ManuallyDrop::drop`] to manually drop the value,
214 /// you can use this method to take the value and use it however desired.
215 ///
216 /// Whenever possible, it is preferable to use [`into_inner`][`ManuallyDrop::into_inner`]
217 /// instead, which prevents duplicating the content of the `ManuallyDrop<T>`.
218 ///
219 /// # Safety
220 ///
221 /// This function semantically moves out the contained value without preventing further usage,
222 /// leaving the state of this container unchanged.
223 /// It is your responsibility to ensure that this `ManuallyDrop` is not used again.
224 ///
225 #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"]
226 #[stable(feature = "manually_drop_take", since = "1.42.0")]
227 #[rustc_const_unstable(feature = "const_manually_drop_take", issue = "148773")]
228 #[inline]
229 pub const unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
230 // SAFETY: we are reading from a reference, which is guaranteed
231 // to be valid for reads.
232 unsafe { ptr::read(slot.value.as_ref()) }
233 }
234}
235
236impl<T: ?Sized> ManuallyDrop<T> {
237 /// Manually drops the contained value.
238 ///
239 /// This is exactly equivalent to calling [`ptr::drop_in_place`] with a
240 /// pointer to the contained value. As such, unless the contained value is a
241 /// packed struct, the destructor will be called in-place without moving the
242 /// value, and thus can be used to safely drop [pinned] data.
243 ///
244 /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead.
245 ///
246 /// # Safety
247 ///
248 /// This function runs the destructor of the contained value. Other than changes made by
249 /// the destructor itself, the memory is left unchanged, and so as far as the compiler is
250 /// concerned still holds a bit-pattern which is valid for the type `T`.
251 ///
252 /// However, this "zombie" value should not be exposed to safe code, and this function
253 /// should not be called more than once. To use a value after it's been dropped, or drop
254 /// a value multiple times, can cause Undefined Behavior (depending on what `drop` does).
255 /// This is normally prevented by the type system, but users of `ManuallyDrop` must
256 /// uphold those guarantees without assistance from the compiler.
257 ///
258 /// [pinned]: crate::pin
259 #[stable(feature = "manually_drop", since = "1.20.0")]
260 #[inline]
261 #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
262 pub const unsafe fn drop(slot: &mut ManuallyDrop<T>)
263 where
264 T: [const] Destruct,
265 {
266 // SAFETY: we are dropping the value pointed to by a mutable reference
267 // which is guaranteed to be valid for writes.
268 // It is up to the caller to make sure that `slot` isn't dropped again.
269 unsafe { ptr::drop_in_place(slot.value.as_mut()) }
270 }
271}
272
273#[stable(feature = "manually_drop", since = "1.20.0")]
274#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
275impl<T: ?Sized> const Deref for ManuallyDrop<T> {
276 type Target = T;
277 #[inline(always)]
278 fn deref(&self) -> &T {
279 self.value.as_ref()
280 }
281}
282
283#[stable(feature = "manually_drop", since = "1.20.0")]
284#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
285impl<T: ?Sized> const DerefMut for ManuallyDrop<T> {
286 #[inline(always)]
287 fn deref_mut(&mut self) -> &mut T {
288 self.value.as_mut()
289 }
290}
291
292#[unstable(feature = "deref_pure_trait", issue = "87121")]
293unsafe impl<T: ?Sized> DerefPure for ManuallyDrop<T> {}
294
295#[stable(feature = "manually_drop", since = "1.20.0")]
296impl<T: ?Sized + Eq> Eq for ManuallyDrop<T> {}
297
298#[stable(feature = "manually_drop", since = "1.20.0")]
299impl<T: ?Sized + PartialEq> PartialEq for ManuallyDrop<T> {
300 fn eq(&self, other: &Self) -> bool {
301 self.value.as_ref().eq(other.value.as_ref())
302 }
303}
304
305#[stable(feature = "manually_drop", since = "1.20.0")]
306impl<T: ?Sized> StructuralPartialEq for ManuallyDrop<T> {}
307
308#[cfg(not(feature = "ferrocene_subset"))]
309#[stable(feature = "manually_drop", since = "1.20.0")]
310impl<T: ?Sized + Ord> Ord for ManuallyDrop<T> {
311 fn cmp(&self, other: &Self) -> Ordering {
312 self.value.as_ref().cmp(other.value.as_ref())
313 }
314}
315
316#[cfg(not(feature = "ferrocene_subset"))]
317#[stable(feature = "manually_drop", since = "1.20.0")]
318impl<T: ?Sized + PartialOrd> PartialOrd for ManuallyDrop<T> {
319 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
320 self.value.as_ref().partial_cmp(other.value.as_ref())
321 }
322}
323
324#[cfg(not(feature = "ferrocene_subset"))]
325#[stable(feature = "manually_drop", since = "1.20.0")]
326impl<T: ?Sized + Hash> Hash for ManuallyDrop<T> {
327 fn hash<H: Hasher>(&self, state: &mut H) {
328 self.value.as_ref().hash(state);
329 }
330}