Skip to main content

maybe_dangling/
maybe_dangling.rs

1// This used to be `crate::ManuallyDrop` (i.e., with `MaybeDangling` semantics in it),
2// but we can directly use the one from stdlib
3use ::core::mem::ManuallyDrop;
4
5/// Like [`ManuallyDrop`] but for having `drop` glue. This wrapper is 0-cost.
6///
7/// In other words, a [`MaybeDangling<T>`] is just like `T`, but
8/// for having been stripped of aliasing/`dereferenceable`-ity properties.
9///
10/// Its usage should be quite rare and advanced: if you are intending to keep
11/// hold of a potentially dangling / exhausted value, chances are you won't
12/// want implicit/automatic drop glue of it without having previously checked
13/// for lack of exhaustion ⚠️.
14///
15/// That is, it is strongly advisable to be using [`ManuallyDrop<T>`] instead!
16///
17/// ### Opting into unstable `#[may_dangle]` and the `dropck_eyepatch`
18///
19/// Ironically, for this drop glue to be as smooth as it should be, the unstable
20/// `#[may_dangle]` feature is needed.
21///
22/// But by virtue of being unstable, it cannot be offered by this crate on
23/// stable Rust.
24///
25/// For the adventurous `nightly` users, you can enable the
26/// `nightly-dropck_eyepatch` Cargo feature to opt into the usage of the
27/// [eponymous `rustc` feature][RFC-1327] so as to get the `Drop` implementation
28/// amended accordingly.
29///
30/// Explanation:
31///
32/// <details class="custom"><summary><span class="summary-box"><span>Click to show</span></span></summary>
33///
34/// #### What does it mean to have a "dangling `T`"?
35///
36/// Note that the terminology of a "dangling `T`" can be a bit hard to
37/// visualize. The idea is to consider some `'dangling` lifetime (_e.g._,
38/// some `&'dangling` borrow), to then imagine different type definitions
39/// involving it.
40///
41/// For instance:
42///
43///  1. `T = &'dangling str`
44///  2. `T = PrintOnDrop<&'dangling str>`,
45///  3. `T = Box<&'dangling str>`,
46///  4. `T = (u8, Box<PrintOnDrop<&'dangling str>>)`,
47///  5. `T = &mut PrintOnDrop<&'dangling str>`,
48///
49/// The key idea is that there are three categories of types here:
50///
51///   1. The types with no drop glue at all, _i.e._, types for which
52///      `mem::needs_drop::<T>()` returns `false`: types 1. and 5.
53///
54///      Such types _should be allowed_ to go out of scope at a point
55///      where their lifetime may be `'dangling`.
56///
57///   2. The types with drop glue known not to involve a dereference of
58///      the `&'dangling` reference: type 3.
59///
60///      Such types _can be allowed_ to go out of scope (and thus, run
61///      their drop glue) at a point where their lifetime may be
62///      `'dangling`.
63///
64///   3. The types with drop glue (potentially) involving a dereference
65///      of the `&'dangling` reference: types 2. and 4.
66///
67///      Such types _should never be allowed_ to go out of scope at a
68///      point where their lifetime may be `'dangling`.
69///
70/// Notice how a useful distinction thus revolves around the presence
71/// of drop glue or lack thereof, to determine whether we are in the
72/// first category, or the other two. On the other hand, whether a type
73/// _directly_ implements `Drop`, such as `Box` or `PrintOnDrop`, or
74/// does not (wrapper types containing it, such as `String` w.r.t. the
75/// `Drop` implementation of the underlying `Vec<u8>`, or `(u8, Box<...>)`
76/// in the fourth example type above), is not enough information to
77/// distinguish between the two, as
78///
79///   - types 2. and 3. both implement `Drop`, and yet belong to different
80///     categories,
81///
82///   - type 4. does not implement `Drop`, and yet belongs to the same
83///     category as type 2.
84///
85/// See the [`drop_bounds` lint] for more info.
86///
87/// The distinction between the second and third category is whether a generic
88/// type, when dropped,
89///
90/// 1. merely drops its inner `T` (like `Box<T>` does) and
91///
92/// 2. makes it known to the [drop checker] that it does so.
93///
94/// If a type violates either restriction, either by unconditionally using any
95/// other API of `T`, like `PrintOnDrop<T: Debug>` does, or by not making
96/// it known to the drop checker that it merely drops its inner `T`, it will
97/// belong to category 3, which can't be allowed to compile.
98///
99/// Making it known to the drop checker that `T` is merely dropped requires
100/// the unstable [`#[may_dangle]`][RFC-1327] attribute.
101/// The drop checker does not know the implementation details of any
102/// `Drop` implementation.
103/// It can't statically analyse how `T` is used in the destructor.
104/// Instead, drop check requires every generic argument to strictly
105/// outlive the wrapper type to guarantee soundness.
106/// This can be overly restrictive when merely dropping `T`, making it
107/// impossible to have `Drop` implementations where `T` might be dangling,
108/// even if dropping a dangling `T` would be sound in the given context.
109/// Hence the `#[may_dangle]` attribute is required to manually and _unsafely_
110/// tell drop check that `T` is merely dropped in the generic type's
111/// destructor, relaxing the drop checker in situations where its soundness
112/// requirements are overly restrictive.
113/// With the `nightly-dropck_eyepatch` feature enabled, <code>[MaybeDangling]\<T\></code>
114/// uses `#[may_dangle]` under the hood to let drop check know that it won't
115/// access the potentially dangling `T` (_e.g._, the `str` behind
116/// `T = &'dangling str`) in its destructor, [*unless*][dropck-generics] `T`'s
117/// `'dangling` lifetime is involved in transitive drop glue, _i.e._:
118///   - whenever `T` implements `Drop` (without `#[may_dangle]`);
119///   - or whenever `T` transitively owns some field with drop glue involving
120///     `'dangling`.
121///
122/// With that context in mind, let's look at examples for the three categories:
123///
124/// #### Category 1: `T` has no drop glue (_e.g._, `T = &'dangling str`)
125///
126/// Since `T` does not have drop glue (`mem::needs_drop::<T>()` returns `false`),
127/// the drop checker will allow this to compile, even though the reference
128/// dangles when `v` gets dropped:
129///
130/// ```
131/// # #[cfg(feature = "nightly-dropck_eyepatch")]
132/// # {
133/// use ::maybe_dangling::MaybeDangling;
134///
135/// fn main() {
136///     let s: String = "I will dangle".into();
137///     let v = MaybeDangling::new(&s);
138///     drop(s); // <- makes `&s` dangle
139/// } // <- `v` dropped here, despite containing a `&'dangling s` reference!
140/// # }
141/// ```
142///
143/// #### Category 2: `T` has drop glue known not to involve `'dangling` (_e.g._, `T = Box<&'dangling str>`)
144///
145/// Now that `T` is has drop glue, it must be executed when `v` is dropped.
146/// `Box<&'dangling str>`'s `Drop` implementation is known not to involve
147/// `'dangling`, so it is safe for `&'dangling str` to dangle when the `Box`
148/// is dropped:
149///
150/// ```
151/// # #![cfg_attr(feature = "nightly-dropck_eyepatch", feature(dropck_eyepatch))]
152/// # #[cfg(feature = "nightly-dropck_eyepatch")]
153/// # {
154/// use ::maybe_dangling::MaybeDangling;
155///
156/// fn main() {
157///     let s: String = "I will dangle".into();
158///     let v = MaybeDangling::new(Box::new(&s));
159///     drop(s); // <- makes `&s` dangle
160/// } // <- `v`, and thus `Box(&s)` dropped here
161/// # }
162/// ```
163///
164/// #### Category 3: `T` has drop glue (potentially) involving `'dangling` (_e.g._, `T = PrintOnDrop<&'dangling str>`)
165///
166/// Like the second category, `T` now has drop glue.
167/// But unlike category 2., `T` now has drop glue either involving `'dangling`
168/// or not informing the drop checker that `'dangling` is unused.
169/// Let's look at an example where `'dangling` is involved in drop glue:
170///
171/// ```compile_fail
172/// use ::maybe_dangling::MaybeDangling;
173///
174/// use ::std::fmt::Debug;
175///
176/// struct PrintOnDrop<T: Debug>(T);
177///
178/// impl<T: Debug> Drop for PrintOnDrop<T> {
179///     fn drop(&mut self) {
180///          println!("Using the potentially dangling `T` in our destructor: {:?}", self.0);
181///     }
182/// }
183///
184/// fn main() {
185///     let s: String = "I will dangle".into();
186///     let v = MaybeDangling::new(PrintOnDrop(&s));
187///     drop(s); // <- makes `&s` dangle
188/// } // <- `v`, and thus `PrintOnDrop(&s)` dropped here, causing a use-after-free ! ⚠️
189/// ```
190///
191/// The example above should never be allowed to compile as `PrintOnDrop`
192/// will dereference `&'dangling str`, which points to a `str` that already
193/// got dropped and invalidated, causing undefined behavior.
194///
195/// An example for a type where `'dangling` is not involved in any drop glue
196/// but does not relax the drop checker with `#[may_dangle]` would be:
197///
198/// ```compile_fail
199/// use ::maybe_dangling::MaybeDangling;
200///
201/// struct MerelyDrop<T>(T);
202///
203/// impl<T> Drop for MerelyDrop<T> {
204///     fn drop(&mut self) {
205///          println!("Not using the potentially dangling `T` in our destructor");
206///     }
207/// }
208///
209/// fn main() {
210///     let s: String = "I will dangle".into();
211///     let v = MaybeDangling::new(MerelyDrop(&s));
212///     drop(s); // <- makes `&s` dangle
213/// } // <- `v`, and thus `MerelyDrop(&s)` dropped here
214/// ```
215///
216/// To amend the example above and move from category 3. to category 2. and
217/// make it compile, `#[may_dangle]` can be applied to `T` in `MerelyDrop`'s
218/// `Drop` implementation:
219///
220/// ```
221/// # #![cfg_attr(feature = "nightly-dropck_eyepatch", feature(dropck_eyepatch))]
222/// # #[cfg(feature = "nightly-dropck_eyepatch")]
223/// # {
224/// #![feature(dropck_eyepatch)]
225///
226/// use ::maybe_dangling::MaybeDangling;
227///
228/// struct MerelyDrop<T>(T);
229///
230/// unsafe impl<#[may_dangle] T> Drop for MerelyDrop<T> {
231///     fn drop(&mut self) {
232///          println!("Not using the potentially dangling `T` in our destructor");
233///     }
234/// }
235///
236/// fn main() {
237///     let s: String = "I will dangle".into();
238///     let v = MaybeDangling::new(MerelyDrop(&s));
239///     drop(s); // <- makes `&s` dangle
240/// } // <- `v`, and thus `MerelyDrop(&s)` dropped here
241/// # }
242/// ```
243///
244/// Note that the `Drop` implementation is _unsafe_ now, as we are still free
245/// to use the dangling `T` in the destructor.
246/// We only pinky-swear to the drop checker that we won't.
247///
248/// </details>
249///
250/// #### Summary: when is a `MaybeDangling<...'dangling...>` allowed to go out of scope
251///
252/// This table summarises which of the categories shown above can be compiled, with
253/// or without the `nightly-dropck_eyepatch` feature enabled:
254///
255/// | `MaybeDangling<T>`<br/><br/>`where T` | With `nightly-dropck_eyepatch` | Without `nightly-dropck_eyepatch` |
256/// | --- | --- | --- |
257/// | has no drop glue<br/>_e.g._<br/>`T = &'dangling str` | ✅ | ❌ |
258/// | has drop glue known not to involve `'dangling`<br/>_e.g._<br/>`T = Box<&'dangling str>` | ✅ | ❌ |
259/// | has drop glue (potentially) involving `'dangling`<br/>_e.g._<br/>`T = PrintOnDrop<&'dangling str>` | ❌ | ❌ |
260///
261/// [RFC-1327]: https://rust-lang.github.io/rfcs/1327-dropck-param-eyepatch.html
262/// [`drop_bounds` lint]: https://doc.rust-lang.org/1.71.0/nightly-rustc/rustc_lint/traits/static.DROP_BOUNDS.html#explanation
263/// [drop checker]: https://doc.rust-lang.org/1.71.0/nomicon/dropck.html
264/// [dropck-generics]: https://doc.rust-lang.org/1.71.0/nomicon/phantom-data.html#generic-parameters-and-drop-checking
265#[repr(transparent)]
266pub struct MaybeDangling<T> {
267    value: ManuallyDrop<T>,
268    #[cfg(feature = "nightly-dropck_eyepatch")]
269    #[allow(nonstandard_style)]
270    // disables `#[may_dangle]` for `T` invovled in transitive drop glue
271    _owns_T: ::core::marker::PhantomData<T>,
272}
273
274impl<T> MaybeDangling<T> {
275    pub const fn new(value: T) -> MaybeDangling<T> {
276        Self {
277            value: ManuallyDrop::new(value),
278            #[cfg(feature = "nightly-dropck_eyepatch")]
279            _owns_T: ::core::marker::PhantomData,
280        }
281    }
282
283    /// Extracts the value from the `MaybeDangling` container.
284    ///
285    /// See [`::core::mem::ManuallyDrop::into_inner()`] for more info.
286    #[inline]
287    pub fn into_inner(slot: MaybeDangling<T>) -> T {
288        #![allow(unsafe_code)]
289        // Safety: this is the defuse inherent drop glue pattern.
290        unsafe { ManuallyDrop::take(&mut ManuallyDrop::new(slot).value) }
291    }
292
293    /// Akin to [`ManuallyDrop::drop()`]: it drops the inner value **in-place**. Raw & `unsafe`
294    /// version of [`drop_in_place!`].
295    ///
296    /// [`drop_in_place!`]: `crate::drop_in_place!`
297    ///
298    /// `Pin` code can rely on this guarantee: [an example](https://docs.rs/droppable_pin).
299    ///
300    /// # Safety
301    ///
302    /// This API is `unsafe` and wildly dangerous. It is very strongly advisable to use
303    /// [`drop_in_place!`] instead.
304    ///
305    /// Indeed, since [`MaybeDangling`] does have embedded drop glue, the moment this function
306    /// returns the only thing that ought to be done is immediately [`::core::mem::forget()`]ting it
307    /// (or wrapping it in a [`ManuallyDrop`]), lest it be dropped implicitly (_e.g._, because of
308    /// some panic), resulting un double-drop unsoundness 😱.
309    ///
310    /// As a matter of fact, this very function needs to feature an abort-on-panic guard to
311    /// handle this problem internally.
312    #[allow(unsafe_code)]
313    pub unsafe fn drop_in_place(this: &mut MaybeDangling<T>) {
314        struct PanicOnDrop();
315        impl Drop for PanicOnDrop {
316            fn drop(&mut self) {
317                panic!("aborting for soundness");
318            }
319        }
320        let _guard = PanicOnDrop();
321        // Unwind-safety: if this unwinds, the `_guard` is dropped, which panics, resulting in a
322        // nested panic which causes the process to abort.
323        unsafe {
324            ManuallyDrop::drop(&mut this.value);
325        }
326        ::core::mem::forget(_guard);
327    }
328}
329
330// The main difference with `ManuallyDrop`: automatic drop glue!
331cfg_select! {
332    feature = "nightly-dropck_eyepatch" => {
333        #[allow(unsafe_code)]
334        unsafe impl<#[may_dangle] T> Drop for MaybeDangling<T> {
335            fn drop(&mut self) {
336                unsafe {
337                    ManuallyDrop::drop(&mut self.value)
338                }
339            }
340        }
341    },
342
343    _ => {
344        impl<T> Drop for MaybeDangling<T> {
345            fn drop(&mut self) {
346                #![allow(unsafe_code)]
347                unsafe {
348                    ManuallyDrop::drop(&mut self.value)
349                }
350            }
351        }
352    },
353}
354
355impl<T> ::core::ops::DerefMut for MaybeDangling<T> {
356    #[inline]
357    fn deref_mut(&mut self) -> &mut T {
358        #[expect(non_local_definitions)]
359        impl<T> ::core::ops::Deref for MaybeDangling<T> {
360            type Target = T;
361
362            #[inline]
363            fn deref(self: &Self) -> &T {
364                let Self { value, .. } = self;
365                value
366            }
367        }
368
369        let Self { value, .. } = self;
370        value
371    }
372}
373
374impl<T: Default> Default for MaybeDangling<T> {
375    #[inline]
376    fn default() -> Self {
377        Self::new(T::default())
378    }
379}
380
381impl<T: Clone> Clone for MaybeDangling<T> {
382    fn clone(self: &Self) -> Self {
383        Self::new(T::clone(self))
384    }
385
386    fn clone_from(self: &mut Self, source: &Self) {
387        T::clone_from(self, source)
388    }
389}
390
391/// Safe API around [`MaybeDangling::drop_in_place()`], which performs the mandatory
392/// [`::core::mem::forget()`] on the given var.
393///
394/// Equivalent to doing <code>[drop]::\<[MaybeDangling]\>\($var\)</code>, but for not moving the
395/// given `$var` before doing so (important with, for instance, `Pin` stuff).
396///
397///   - Using [`MaybeDangling::drop_in_place()`] directly is so wildly dangerous that it is
398///     discouraged.
399///
400///   - Using [`ManuallyDrop`] alongside [`ManuallyDrop::drop()`] is significantly less dangerous
401///     w.r.t. double-dropping, but alas just as dangerous w.r.t. leaking when dealing with the
402///     `Pin` contract for which a lack of drop in certain cases is just as unsound.
403///
404/// Remark: this macro requires the given `$var` binding to have been declared `mut`able.
405///
406/// # Example
407///
408/// Imagine, as a library author, wanting to offer the following kind of API:
409///
410/// ```rust
411/// # fn stuff() {}
412/// pub use ::core;
413/// # pub extern crate maybe_dangling; /*
414/// pub use ::maybe_dangling;
415/// # */
416///
417/// macro_rules! my_droppable_pin {(
418///     let mut $var:ident = pin!($value:expr);
419/// ) => (
420///     let mut pinned_value = $crate::maybe_dangling::MaybeDangling::new($value);
421///     macro_rules! drop_it {() => (
422///         $crate::maybe_dangling::drop_in_place!(pinned_value);
423///     )}
424///     #[allow(unused_mut)]
425///     let mut $var = unsafe {
426///         $crate::core::pin::Pin::new_unchecked(&mut *pinned_value)
427///     };
428/// )}
429///
430/// fn main() {
431///     use ::core::{marker::PhantomPinned, pin::*};
432///
433///     my_droppable_pin! {
434///         let mut p = pin!(PhantomPinned);
435///     }
436///     let _: Pin<&mut PhantomPinned> = p.as_mut(); // properly pinned!
437///     for i in 0.. {
438///         if i == 5 {
439///             drop_it!(); // drops the `PhantomPinned` in-place, abiding by the drop guarantee.
440///             // stuff runs after `PhantomPinned` has been dropped, rather than before.
441///             stuff();
442///             break;
443///         }
444///     }
445/// }
446/// ```
447#[macro_export]
448macro_rules! drop_in_place {
449    ( $var:ident $(,)? ) => {
450        // guard against `$var` not being a place (e.g., some `const` or `static mut` or whatnot).
451        _ = &raw const $var;
452        unsafe {
453            $crate::MaybeDangling::drop_in_place(&mut $var);
454        }
455        $crate::ඞ::core::mem::forget($var);
456    };
457}