Skip to main content

Crate maybe_dangling

Crate maybe_dangling 

Source
Expand description

§::maybe-dangling

MaybeDangling<T> in stable Rust, as per https://github.com/rust-lang/rfcs/pull/3336

Repository Latest version Documentation MSRV License CI no_std compatible

For context, MaybeDangling<T>, is like ManuallyDrop<T>, insofar it does not carry aliasing/dereferenceable-ity properties w.r.t. the T it contains. Notably, it means it is allowed to:

  1. have some expired value inside of them, such as T = &'expired …,
  2. be fed to a function that does not inspect its value (such as ::core::mem::forget()),
  3. exhibit well-defined behavior (no UB!).

Moreover, contrary to ManuallyDrop<T>, MaybeDangling<T> does not forgo T’s drop glue.

Another way to look at it is to say that:

  1. there is MaybeDangling<T>, which is a core primitive type, equivalent to T in almost every aspect (notably, it carries its very same drop glue), except in its lack of T’s default implicit dereferenceable-ity-and-lack-of-aliasing semantics (wherein T’s validity invariants mandates that these semantics be active, and remain true, upon every time the type is so much as “looked at” (this includes “inert” assignments or calling functions on it, even a no-op one such as mem::forget())).

    MaybeDangling<T> forgos and loosens this requirement, expecting “only” as a safety invariant that the safety (and thus, validity) invariants of its inner T be upheld upon actual use of T’s API, e.g., upon Deref{,Mut} of this wrapper.

    Notably, this includes, in a wildly dangerous, maybe even footgunny way, its drop glue, at least whenever mem::needs_drop::<T>().

  2. In order to fix this last remark, another type is offered by the stdlib, ManuallyDrop<T>, which not only features the very same loose lack-of-dereferenceable-ity-and-lack-of-aliasing semantics of MaybeDangling<T>, but it also fully disables the inherent/built-in (implicit) drop glue of the overall type. If drop of its inner T is desired, it can be achieved by doing so explicitly, through ManuallyDrop::into_inner() or ManuallyDrop::drop{,_in_place}().

See the docs of ::core::mem::MaybeDangling for more info about all this.

Currently, whilst MaybeDangling<T> is indeed offered by the stdlib, it is gated behind an unstable feature. This crate offers a polyfill of this, achieved by:

  1. wrapping ManuallyDrop<T>
  2. manually implementing Drop on it to call ManuallyDrop::drop().

This does come with one small potential ergonomic issue compared to the stdlib’s, related to dropck.

Read the docs of this crate’s MaybeDangling<T> for more info about this.

§References

Macros§

drop_in_place
Safe API around MaybeDangling::drop_in_place(), which performs the mandatory ::core::mem::forget() on the given var.

Structs§

MaybeDangling
Like ManuallyDrop but for having drop glue. This wrapper is 0-cost.