core/mem/maybe_dangling.rs
1#![unstable(feature = "maybe_dangling", issue = "118166")]
2
3use crate::marker::StructuralPartialEq;
4use crate::{mem, ptr};
5
6/// Allows wrapped [references] and [boxes] to dangle.
7///
8/// That is, if a reference (or a `Box`) is wrapped in `MaybeDangling` (including when in a
9/// (nested) field of a compound type wrapped in `MaybeDangling`), it does not have to follow
10/// pointer aliasing rules or be dereferenceable.
11///
12/// This can be useful when the value can become dangling while the function holding it is still
13/// executing (particularly in concurrent code). As a somewhat absurd example, consider this code:
14///
15/// ```rust,no_run
16/// #![feature(box_as_ptr)]
17/// # use std::alloc::{dealloc, Layout};
18/// # use std::mem;
19///
20/// let mut boxed = Box::new(0_u32);
21/// let ptr = Box::as_mut_ptr(&mut boxed);
22///
23/// // Safety: the pointer comes from a box and thus was allocated before; `box` is not used afterwards
24/// unsafe { dealloc(ptr.cast(), Layout::new::<u32>()) };
25///
26/// mem::forget(boxed); // <-- this is UB!
27/// ```
28///
29/// Even though the `Box`'s destructor is not run (and thus we don't have a double free bug), this
30/// code is still UB. This is because when moving `boxed` into `forget`, its validity invariants
31/// are asserted, causing UB since the `Box` is dangling. The safety comment is as such wrong, as
32/// moving the `boxed` variable as part of the `forget` call *is* a use.
33///
34/// To fix this we could use `MaybeDangling`:
35///
36// FIXME: remove `no_run` once the semantics are actually implemented
37/// ```rust,no_run
38/// #![feature(maybe_dangling, box_as_ptr)]
39/// # use std::alloc::{dealloc, Layout};
40/// # use std::mem::{self, MaybeDangling};
41///
42/// let mut boxed = MaybeDangling::new(Box::new(0_u32));
43/// let ptr = Box::as_mut_ptr(boxed.as_mut());
44///
45/// // Safety: the pointer comes from a box and thus was allocated before; `box` is not used afterwards
46/// unsafe { dealloc(ptr.cast(), Layout::new::<u32>()) };
47///
48/// mem::forget(boxed); // <-- this is OK!
49/// ```
50///
51/// Note that the bit pattern must still be valid for the wrapped type. That is, [references]
52/// (and [boxes]) still must be aligned and non-null.
53///
54/// Additionally note that safe code can still assume that the inner value in a `MaybeDangling` is
55/// **not** dangling -- functions like [`as_ref`] and [`into_inner`] are safe. It is not sound to
56/// return a dangling reference in a `MaybeDangling` to safe code. However, it *is* sound
57/// to hold such values internally inside your code -- and there's no way to do that without
58/// this type. Note that other types can use this type and thus get the same effect; in particular,
59/// [`ManuallyDrop`] will use `MaybeDangling`.
60///
61/// Note that `MaybeDangling` doesn't prevent drops from being run, which can lead to UB if the
62/// drop observes a dangling value. If you need to prevent drops from being run use [`ManuallyDrop`]
63/// instead.
64///
65/// [references]: prim@reference
66/// [boxes]: ../../std/boxed/struct.Box.html
67/// [`into_inner`]: MaybeDangling::into_inner
68/// [`as_ref`]: MaybeDangling::as_ref
69/// [`ManuallyDrop`]: crate::mem::ManuallyDrop
70#[repr(transparent)]
71#[rustc_pub_transparent]
72#[derive(Debug, Copy, Clone, Default)]
73#[lang = "maybe_dangling"]
74#[ferrocene::prevalidated]
75pub struct MaybeDangling<P: ?Sized>(P);
76
77impl<P: ?Sized> MaybeDangling<P> {
78 /// Wraps a value in a `MaybeDangling`, allowing it to dangle.
79 #[ferrocene::prevalidated]
80 pub const fn new(x: P) -> Self
81 where
82 P: Sized,
83 {
84 MaybeDangling(x)
85 }
86
87 /// Returns a reference to the inner value.
88 ///
89 /// Note that this is UB if the inner value is currently dangling.
90 #[ferrocene::prevalidated]
91 pub const fn as_ref(&self) -> &P {
92 &self.0
93 }
94
95 /// Returns a mutable reference to the inner value.
96 ///
97 /// Note that this is UB if the inner value is currently dangling.
98 #[ferrocene::prevalidated]
99 pub const fn as_mut(&mut self) -> &mut P {
100 &mut self.0
101 }
102
103 /// Extracts the value from the `MaybeDangling` container.
104 ///
105 /// Note that this is UB if the inner value is currently dangling.
106 #[ferrocene::prevalidated]
107 pub const fn into_inner(self) -> P
108 where
109 P: Sized,
110 {
111 // FIXME: replace this with `self.0` when const checker can figure out that `self` isn't actually dropped
112 // SAFETY: this is equivalent to `self.0`
113 let x = unsafe { ptr::read(&self.0) };
114 mem::forget(self);
115 x
116 }
117}
118
119impl<T: ?Sized> StructuralPartialEq for MaybeDangling<T> {}