Skip to content

Commit 1e62382

Browse files
authored
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
2 parents fd15e61 + 9bac577 commit 1e62382

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

library/core/src/option.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,23 @@
7070
//! }
7171
//! ```
7272
//!
73-
//! This usage of [`Option`] to create safe nullable pointers is so
74-
//! common that Rust does special optimizations to make the
75-
//! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers
76-
//! in Rust are stored as efficiently as any other pointer type.
73+
//! # Representation
74+
//!
75+
//! Rust guarantees to optimize the following types `T` such that
76+
//! [`Option<T>`] has the same size as `T`:
77+
//!
78+
//! * [`Box<U>`]
79+
//! * `&U`
80+
//! * `&mut U`
81+
//! * `fn`, `extern "C" fn`
82+
//! * [`num::NonZero*`]
83+
//! * [`ptr::NonNull<U>`]
84+
//! * `#[repr(transparent)]` struct around one of the types in this list.
85+
//!
86+
//! It is further guaranteed that, for the cases above, one can
87+
//! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
88+
//! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
89+
//! is undefined behaviour).
7790
//!
7891
//! # Examples
7992
//!

0 commit comments

Comments
 (0)