diff options
| author | Ralf Jung <post@ralfj.de> | 2020-09-26 12:58:12 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-09-26 12:58:12 +0200 |
| commit | 1e62382a4f4a5db37f3fc034c18e1d89d4e2e00d (patch) | |
| tree | 21eb5fe647cab3530631fde9f6d98a681bbcdcc8 | |
| parent | fd15e6180d9c48b4f1157e44cdaff6e901e5f854 (diff) | |
| parent | 9bac5774d7b452b2227c9fb77a4c6de3f432ee55 (diff) | |
| download | rust-1e62382a4f4a5db37f3fc034c18e1d89d4e2e00d.tar.gz rust-1e62382a4f4a5db37f3fc034c18e1d89d4e2e00d.zip | |
Rollup merge of #75454 - ltratt:option_optimisation_guarantees, r=dtolnay
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
| -rw-r--r-- | library/core/src/option.rs | 21 |
1 files changed, 17 insertions, 4 deletions
diff --git a/library/core/src/option.rs b/library/core/src/option.rs index b1589008be0..0cfb4af59b9 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -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 //! |
