Skip to content

Commit

Permalink
Rollup merge of #75454 - ltratt:option_optimisation_guarantees, r=dto…
Browse files Browse the repository at this point in the history
…lnay

Explicitly document the size guarantees that Option makes.

Triggered by a discussion on wg-unsafe-code-guidelines about which layouts of `Option<T>` one can guarantee are optimised to a single pointer.

CC @RalfJung
  • Loading branch information
RalfJung authored Sep 26, 2020
2 parents fd15e61 + 9bac577 commit 1e62382
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,23 @@
//! }
//! ```
//!
//! This usage of [`Option`] to create safe nullable pointers is so
//! common that Rust does special optimizations to make the
//! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers
//! in Rust are stored as efficiently as any other pointer type.
//! # Representation
//!
//! Rust guarantees to optimize the following types `T` such that
//! [`Option<T>`] has the same size as `T`:
//!
//! * [`Box<U>`]
//! * `&U`
//! * `&mut U`
//! * `fn`, `extern "C" fn`
//! * [`num::NonZero*`]
//! * [`ptr::NonNull<U>`]
//! * `#[repr(transparent)]` struct around one of the types in this list.
//!
//! It is further guaranteed that, for the cases above, one can
//! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
//! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
//! is undefined behaviour).
//!
//! # Examples
//!
Expand Down

0 comments on commit 1e62382

Please sign in to comment.