mod.rs - source
Description: Source of the Rust file `library/core/src/mem/mod.rs`.

#
core/mem/
mod.rs

    1//! Basic functions for dealing with memory.
    2//!
    3//! This module contains functions for querying the size and alignment of
    4//! types, initializing and manipulating memory.
    5
    6#![stable(feature = "rust1", since = "1.0.0")]
    7
    8use crate::alloc::Layout;
    9use crate::clone::TrivialClone;
    10use crate::marker::{Destruct, DiscriminantKind};
    11use crate::panic::const_assert;
    12use crate::{clone, cmp, fmt, hash, intrinsics, ptr};
    13
    14mod manually_drop;
    15#[stable(feature = "manually_drop", since = "1.20.0")]
    16pub use manually_drop::ManuallyDrop;
    17
    18mod maybe_uninit;
    19#[stable(feature = "maybe_uninit", since = "1.36.0")]
    20pub use maybe_uninit::MaybeUninit;
    21
    22mod maybe_dangling;
    23#[unstable(feature = "maybe_dangling", issue = "118166")]
    24pub use maybe_dangling::MaybeDangling;
    25
    26mod transmutability;
    27#[unstable(feature = "transmutability", issue = "99571")]
    28pub use transmutability::{Assume, TransmuteFrom};
    29
    30mod drop_guard;
    31#[unstable(feature = "drop_guard", issue = "144426")]
    32pub use drop_guard::DropGuard;
    33
    34// This one has to be a re-export (rather than wrapping the underlying intrinsic) so that we can do
    35// the special magic "types have equal size" check at the call site.
    36#[stable(feature = "rust1", since = "1.0.0")]
    37#[doc(inline)]
    38pub use crate::intrinsics::transmute;
    39
    40#[unstable(feature = "type_info", issue = "146922")]
    41pub mod type_info;
    42
    43/// Takes ownership and "forgets" about the value **without running its destructor**.
    44///
    45/// Any resources the value manages, such as heap memory or a file handle, will linger
    46/// forever in an unreachable state. However, it does not guarantee that pointers
    47/// to this memory will remain valid.
    48///
    49/// * If you want to leak memory, see [`Box::leak`].
    50/// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`].
    51/// * If you want to dispose of a value properly, running its destructor, see
    52///   [`mem::drop`].
    53///
    54/// # Safety
    55///
    56/// `forget` is not marked as `unsafe`, because Rust's safety guarantees
    57/// do not include a guarantee that destructors will always run. For example,
    58/// a program can create a reference cycle using [`Rc`][rc], or call
    59/// [`process::exit`][exit] to exit without running destructors. Thus, allowing
    60/// `mem::forget` from safe code does not fundamentally change Rust's safety
    61/// guarantees.
    62///
    63/// That said, leaking resources such as memory or I/O objects is usually undesirable.
    64/// The need comes up in some specialized use cases for FFI or unsafe code, but even
    65/// then, [`ManuallyDrop`] is typically preferred.
    66///
    67/// Because forgetting a value is allowed, any `unsafe` code you write must
    68/// allow for this possibility. You cannot return a value and expect that the
    69/// caller will necessarily run the value's destructor.
    70///
    71/// [rc]: ../../std/rc/struct.Rc.html
    72/// [exit]: ../../std/process/fn.exit.html
    73///
    74/// # Examples
    75///
    76/// The canonical safe use of `mem::forget` is to circumvent a value's destructor
    77/// implemented by the `Drop` trait. For example, this will leak a `File`, i.e. reclaim
    78/// the space taken by the variable but never close the underlying system resource:
    79///
    80/// ```no_run
    81/// use std::mem;
    82/// use std::fs::File;
    83///
    84/// let file = File::open("foo.txt").unwrap();
    85/// mem::forget(file);
    86/// ```
    87///
    88/// This is useful when the ownership of the underlying resource was previously
    89/// transferred to code outside of Rust, for example by transmitting the raw
    90/// file descriptor to C code.
    91///
    92/// # Relationship with `ManuallyDrop`
    93///
    94/// While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone.
    95/// [`ManuallyDrop`] should be used instead. Consider, for example, this code:
    96///
    97/// ```
    98/// use std::mem;
    99///
    100/// let mut v = vec![65, 122];
    101/// // Build a `String` using the contents of `v`
    102/// let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) };
    103/// // leak `v` because its memory is now managed by `s`
    104/// mem::forget(v);  // ERROR - v is invalid and must not be passed to a function
    105/// assert_eq!(s, "Az");
    106/// // `s` is implicitly dropped and its memory deallocated.
    107/// ```
    108///
    109/// There are two issues with the above example:
    110///
    111/// * If more code were added between the construction of `String` and the invocation of
    112///   `mem::forget()`, a panic within it would cause a double free because the same memory
    113///   is handled by both `v` and `s`.
    114/// * After calling `v.as_mut_ptr()` and transmitting the ownership of the data to `s`,
    115///   the `v` value is invalid. Even when a value is just moved to `mem::forget` (which won't
    116///   inspect it), some types have strict requirements on their values that
    117///   make them invalid when dangling or no longer owned. Using invalid values in any
    118///   way, including passing them to or returning them from functions, constitutes
    119///   undefined behavior and may break the assumptions made by the compiler.
    120///
    121/// Switching to `ManuallyDrop` avoids both issues:
    122///
    123/// ```
    124/// use std::mem::ManuallyDrop;
    125///
    126/// let v = vec![65, 122];
    127/// // Before we disassemble `v` into its raw parts, make sure it
    128/// // does not get dropped!
    129/// let mut v = ManuallyDrop::new(v);
    130/// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak.
    131/// let (ptr, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity());
    132/// // Finally, build a `String`.
    133/// let s = unsafe { String::from_raw_parts(ptr, len, cap) };
    134/// assert_eq!(s, "Az");
    135/// // `s` is implicitly dropped and its memory deallocated.
    136/// ```
    137///
    138/// `ManuallyDrop` robustly prevents double-free because we disable `v`'s destructor
    139/// before doing anything else. `mem::forget()` doesn't allow this because it consumes its
    140/// argument, forcing us to call it only after extracting anything we need from `v`. Even
    141/// if a panic were introduced between construction of `ManuallyDrop` and building the
    142/// string (which cannot happen in the code as shown), it would result in a leak and not a
    143/// double free. In other words, `ManuallyDrop` errs on the side of leaking instead of
    144/// erring on the side of (double-)dropping.
    145///
    146/// Also, `ManuallyDrop` prevents us from having to "touch" `v` after transferring the
    147/// ownership to `s` — the final step of interacting with `v` to dispose of it without
    148/// running its destructor is entirely avoided.
    149///
    150/// [`Box`]: ../../std/boxed/struct.Box.html
    151/// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak
    152/// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw
    153/// [`mem::drop`]: drop
    154/// [ub]: ../../reference/behavior-considered-undefined.html
    155#[inline]
    156#[rustc_const_stable(feature = "const_forget", since = "1.46.0")]
    157#[stable(feature = "rust1", since = "1.0.0")]
    158#[rustc_diagnostic_item = "mem_forget"]
    159pub const fn forget<T>(t: T) {
    160    let _ = ManuallyDrop::new(t);
    161}
    162
    163/// Like [`forget`], but also accepts unsized values.
    164///
    165/// While Rust does not permit unsized locals since its removal in [#111942] it is
    166/// still possible to call functions with unsized values from a function argument
    167/// or place expression.
    168///
    169/// ```rust
    170/// #![feature(unsized_fn_params, forget_unsized)]
    171/// #![allow(internal_features)]
    172///
    173/// use std::mem::forget_unsized;
    174///
    175/// pub fn in_place() {
    176///     forget_unsized(*Box::<str>::from("str"));
    177/// }
    178///
    179/// pub fn param(x: str) {
    180///     forget_unsized(x);
    181/// }
    182/// ```
    183///
    184/// This works because the compiler will alter these functions to pass the parameter
    185/// by reference instead. This trick is necessary to support `Box<dyn FnOnce()>: FnOnce()`.
    186/// See [#68304] and [#71170] for more information.
    187///
    188/// [#111942]: https://github.com/rust-lang/rust/issues/111942
    189/// [#68304]: https://github.com/rust-lang/rust/issues/68304
    190/// [#71170]: https://github.com/rust-lang/rust/pull/71170
    191#[inline]
    192#[unstable(feature = "forget_unsized", issue = "none")]
    193pub fn forget_unsized<T: ?Sized>(t: T) {
    194    intrinsics::forget(t)
    195}
    196
    197/// Returns the size of a type in bytes.
    198///
    199/// More specifically, this is the offset in bytes between successive elements
    200/// in an array with that item type including alignment padding. Thus, for any
    201/// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
    202///
    203/// In general, the size of a type is not stable across compilations, but
    204/// specific types such as primitives are.
    205///
    206/// The following table gives the size for primitives.
    207///
    208/// Type | `size_of::<Type>()`
    209/// ---- | ---------------
    210/// () | 0
    211/// bool | 1
    212/// u8 | 1
    213/// u16 | 2
    214/// u32 | 4
    215/// u64 | 8
    216/// u128 | 16
    217/// i8 | 1
    218/// i16 | 2
    219/// i32 | 4
    220/// i64 | 8
    221/// i128 | 16
    222/// f32 | 4
    223/// f64 | 8
    224/// char | 4
    225///
    226/// Furthermore, `usize` and `isize` have the same size.
    227///
    228/// The types [`*const T`], `&T`, [`Box<T>`], [`Option<&T>`], and `Option<Box<T>>` all have
    229/// the same size. If `T` is `Sized`, all of those types have the same size as `usize`.
    230///
    231/// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
    232/// have the same size. Likewise for `*const T` and `*mut T`.
    233///
    234/// # Size of `#[repr(C)]` items
    235///
    236/// The `C` representation for items has a defined layout. With this layout,
    237/// the size of items is also stable as long as all fields have a stable size.
    238///
    239/// ## Size of Structs
    240///
    241/// For `struct`s, the size is determined by the following algorithm.
    242///
    243/// For each field in the struct ordered by declaration order:
    244///
    245/// 1. Add the size of the field.
    246/// 2. Round up the current size to the nearest multiple of the next field's [alignment].
    247///
    248/// Finally, round the size of the struct to the nearest multiple of its [alignment].
    249/// The alignment of the struct is usually the largest alignment of all its
    250/// fields; this can be changed with the use of `repr(align(N))`.
    251///
    252/// Unlike `C`, zero sized structs are not rounded up to one byte in size.
    253///
    254/// ## Size of Enums
    255///
    256/// Enums that carry no data other than the discriminant have the same size as C enums
    257/// on the platform they are compiled for.
    258///
    259/// ## Size of Unions
    260///
    261/// The size of a union is the size of its largest field.
    262///
    263/// Unlike `C`, zero sized unions are not rounded up to one byte in size.
    264///
    265/// # Examples
    266///
    267/// ```
    268/// // Some primitives
    269/// assert_eq!(4, size_of::<i32>());
    270/// assert_eq!(8, size_of::<f64>());
    271/// assert_eq!(0, size_of::<()>());
    272///
    273/// // Some arrays
    274/// assert_eq!(8, size_of::<[i32; 2]>());
    275/// assert_eq!(12, size_of::<[i32; 3]>());
    276/// assert_eq!(0, size_of::<[i32; 0]>());
    277///
    278///
    279/// // Pointer size equality
    280/// assert_eq!(size_of::<&i32>(), size_of::<*const i32>());
    281/// assert_eq!(size_of::<&i32>(), size_of::<Box<i32>>());
    282/// assert_eq!(size_of::<&i32>(), size_of::<Option<&i32>>());
    283/// assert_eq!(size_of::<Box<i32>>(), size_of::<Option<Box<i32>>>());
    284/// ```
    285///
    286/// Using `#[repr(C)]`.
    287///
    288/// ```
    289/// #[repr(C)]
    290/// struct FieldStruct {
    291///     first: u8,
    292///     second: u16,
    293///     third: u8
    294/// }
    295///
    296/// // The size of the first field is 1, so add 1 to the size. Size is 1.
    297/// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
    298/// // The size of the second field is 2, so add 2 to the size. Size is 4.
    299/// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
    300/// // The size of the third field is 1, so add 1 to the size. Size is 5.
    301/// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
    302/// // fields is 2), so add 1 to the size for padding. Size is 6.
    303/// assert_eq!(6, size_of::<FieldStruct>());
    304///
    305/// #[repr(C)]
    306/// struct TupleStruct(u8, u16, u8);
    307///
    308/// // Tuple structs follow the same rules.
    309/// assert_eq!(6, size_of::<TupleStruct>());
    310///
    311/// // Note that reordering the fields can lower the size. We can remove both padding bytes
    312/// // by putting `third` before `second`.
    313/// #[repr(C)]
    314/// struct FieldStructOptimized {
    315///     first: u8,
    316///     third: u8,
    317///     second: u16
    318/// }
    319///
    320/// assert_eq!(4, size_of::<FieldStructOptimized>());
    321///
    322/// // Union size is the size of the largest field.
    323/// #[repr(C)]
    324/// union ExampleUnion {
    325///     smaller: u8,
    326///     larger: u16
    327/// }
    328///
    329/// assert_eq!(2, size_of::<ExampleUnion>());
    330/// ```
    331///
    332/// [alignment]: align_of
    333/// [`*const T`]: primitive@pointer
    334/// [`Box<T>`]: ../../std/boxed/struct.Box.html
    335/// [`Option<&T>`]: crate::option::Option
    336///
    337#[inline(always)]
    338#[must_use]
    339#[stable(feature = "rust1", since = "1.0.0")]
    340#[rustc_promotable]
    341#[rustc_const_stable(feature = "const_mem_size_of", since = "1.24.0")]
    342#[rustc_diagnostic_item = "mem_size_of"]
    343pub const fn size_of<T>() -> usize {
    344    <T as SizedTypeProperties>::SIZE
    345}
    346
    347/// Returns the size of the pointed-to value in bytes.
    348///
    349/// This is usually the same as [`size_of::<T>()`]. However, when `T` *has* no
    350/// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
    351/// then `size_of_val` can be used to get the dynamically-known size.
    352///
    353/// [trait object]: ../../book/ch17-02-trait-objects.html
    354///
    355/// # Examples
    356///
    357/// ```
    358/// assert_eq!(4, size_of_val(&5i32));
    359///
    360/// let x: [u8; 13] = [0; 13];
    361/// let y: &[u8] = &x;
    362/// assert_eq!(13, size_of_val(y));
    363/// ```
    364///
    365/// [`size_of::<T>()`]: size_of
    366#[inline]
    367#[must_use]
    368#[stable(feature = "rust1", since = "1.0.0")]
    369#[rustc_const_stable(feature = "const_size_of_val", since = "1.85.0")]
    370#[rustc_diagnostic_item = "mem_size_of_val"]
    371pub const fn size_of_val<T: ?Sized>(val: &T) -> usize {
    372    // SAFETY: `val` is a reference, so it's a valid raw pointer
    373    unsafe { intrinsics::size_of_val(val) }
    374}
    375
    376/// Returns the size of the pointed-to value in bytes.
    377///
    378/// This is usually the same as [`size_of::<T>()`]. However, when `T` *has* no
    379/// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
    380/// then `size_of_val_raw` can be used to get the dynamically-known size.
    381///
    382/// # Safety
    383///
    384/// This function is only safe to call if the following conditions hold:
    385///
    386/// - If `T` is `Sized`, this function is always safe to call.
    387/// - If the unsized tail of `T` is:
    388///     - a [slice], then the length of the slice tail must be an initialized
    389///       integer, and the size of the *entire value*
    390///       (dynamic tail length + statically sized prefix) must fit in `isize`.
    391///       For the special case where the dynamic tail length is 0, this function
    392///       is safe to call.
    393//        NOTE: the reason this is safe is that if an overflow were to occur already with size 0,
    394//        then we would stop compilation as even the "statically known" part of the type would
    395//        already be too big (or the call may be in dead code and optimized away, but then it
    396//        doesn't matter).
    397///     - a [trait object], then the vtable part of the pointer must point
    398///       to a valid vtable acquired by an unsizing coercion, and the size
    399///       of the *entire value* (dynamic tail length + statically sized prefix)
    400///       must fit in `isize`.
    401///     - an (unstable) [extern type], then this function is always safe to
    402///       call, but may panic or otherwise return the wrong value, as the
    403///       extern type's layout is not known. This is the same behavior as
    404///       [`size_of_val`] on a reference to a type with an extern type tail.
    405///     - otherwise, it is conservatively not allowed to call this function.
    406///
    407/// [`size_of::<T>()`]: size_of
    408/// [trait object]: ../../book/ch17-02-trait-objects.html
    409/// [extern type]: ../../unstable-book/language-features/extern-types.html
    410///
    411/// # Examples
    412///
    413/// ```
    414/// #![feature(layout_for_ptr)]
    415/// use std::mem;
    416///
    417/// assert_eq!(4, size_of_val(&5i32));
    418///
    419/// let x: [u8; 13] = [0; 13];
    420/// let y: &[u8] = &x;
    421/// assert_eq!(13, unsafe { mem::size_of_val_raw(y) });
    422/// ```
    423#[inline]
    424#[must_use]
    425#[unstable(feature = "layout_for_ptr", issue = "69835")]
    426pub const unsafe fn size_of_val_raw<T: ?Sized>(val: *const T) -> usize {
    427    // SAFETY: the caller must provide a valid raw pointer
    428    unsafe { intrinsics::size_of_val(val) }
    429}
    430
    431/// Returns the [ABI]-required minimum alignment of a type in bytes.
    432///
    433/// Every reference to a value of the type `T` must be a multiple of this number.
    434///
    435/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
    436///
    437/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
    438///
    439/// # Examples
    440///
    441/// ```
    442/// # #![allow(deprecated)]
    443/// use std::mem;
    444///
    445/// assert_eq!(4, mem::min_align_of::<i32>());
    446/// ```
    447#[inline]
    448#[must_use]
    449#[stable(feature = "rust1", since = "1.0.0")]
    450#[deprecated(note = "use `align_of` instead", since = "1.2.0", suggestion = "align_of")]
    451pub fn min_align_of<T>() -> usize {
    452    <T as SizedTypeProperties>::ALIGN
    453}
    454
    455/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
    456/// bytes.
    457///
    458/// Every reference to a value of the type `T` must be a multiple of this number.
    459///
    460/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
    461///
    462/// # Examples
    463///
    464/// ```
    465/// # #![allow(deprecated)]
    466/// use std::mem;
    467///
    468/// assert_eq!(4, mem::min_align_of_val(&5i32));
    469/// ```
    470#[inline]
    471#[must_use]
    472#[stable(feature = "rust1", since = "1.0.0")]
    473#[deprecated(note = "use `align_of_val` instead", since = "1.2.0", suggestion = "align_of_val")]
    474pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
    475    // SAFETY: val is a reference, so it's a valid raw pointer
    476    unsafe { intrinsics::align_of_val(val) }
    477}
    478
    479/// Returns the [ABI]-required minimum alignment of a type in bytes.
    480///
    481/// Every reference to a value of the type `T` must be a multiple of this number.
    482///
    483/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
    484///
    485/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
    486///
    487/// # Examples
    488///
    489/// ```
    490/// assert_eq!(4, align_of::<i32>());
    491/// ```
    492#[inline(always)]
    493#[must_use]
    494#[stable(feature = "rust1", since = "1.0.0")]
    495#[rustc_promotable]
    496#[rustc_const_stable(feature = "const_align_of", since = "1.24.0")]
    497#[rustc_diagnostic_item = "mem_align_of"]
    498pub const fn align_of<T>() -> usize {
    499    <T as SizedTypeProperties>::ALIGN
    500}
    501
    502/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
    503/// bytes.
    504///
    505/// Every reference to a value of the type `T` must be a multiple of this number.
    506///
    507/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
    508///
    509/// # Examples
    510///
    511/// ```
    512/// assert_eq!(4, align_of_val(&5i32));
    513/// ```
    514#[inline]
    515#[must_use]
    516#[stable(feature = "rust1", since = "1.0.0")]
    517#[rustc_const_stable(feature = "const_align_of_val", since = "1.85.0")]
    518pub const fn align_of_val<T: ?Sized>(val: &T) -> usize {
    519    // SAFETY: val is a reference, so it's a valid raw pointer
    520    unsafe { intrinsics::align_of_val(val) }
    521}
    522
    523/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
    524/// bytes.
    525///
    526/// Every reference to a value of the type `T` must be a multiple of this number.
    527///
    528/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
    529///
    530/// # Safety
    531///
    532/// This function is only safe to call if the following conditions hold:
    533///
    534/// - If `T` is `Sized`, this function is always safe to call.
    535/// - If the unsized tail of `T` is:
    536///     - a [slice], then the length of the slice tail must be an initialized
    537///       integer, and the size of the *entire value*
    538///       (dynamic tail length + statically sized prefix) must fit in `isize`.
    539///       For the special case where the dynamic tail length is 0, this function
    540///       is safe to call.
    541///     - a [trait object], then the vtable part of the pointer must point
    542///       to a valid vtable acquired by an unsizing coercion, and the size
    543///       of the *entire value* (dynamic tail length + statically sized prefix)
    544///       must fit in `isize`.
    545///     - an (unstable) [extern type], then this function is always safe to
    546///       call, but may panic or otherwise return the wrong value, as the
    547///       extern type's layout is not known. This is the same behavior as
    548///       [`align_of_val`] on a reference to a type with an extern type tail.
    549///     - otherwise, it is conservatively not allowed to call this function.
    550///
    551/// [trait object]: ../../book/ch17-02-trait-objects.html
    552/// [extern type]: ../../unstable-book/language-features/extern-types.html
    553///
    554/// # Examples
    555///
    556/// ```
    557/// #![feature(layout_for_ptr)]
    558/// use std::mem;
    559///
    560/// assert_eq!(4, unsafe { mem::align_of_val_raw(&5i32) });
    561/// ```
    562#[inline]
    563#[must_use]
    564#[unstable(feature = "layout_for_ptr", issue = "69835")]
    565pub const unsafe fn align_of_val_raw<T: ?Sized>(val: *const T) -> usize {
    566    // SAFETY: the caller must provide a valid raw pointer
    567    unsafe { intrinsics::align_of_val(val) }
    568}
    569
    570/// Returns `true` if dropping values of type `T` matters.
    571///
    572/// This is purely an optimization hint, and may be implemented conservatively:
    573/// it may return `true` for types that don't actually need to be dropped.
    574/// As such always returning `true` would be a valid implementation of
    575/// this function. However if this function actually returns `false`, then you
    576/// can be certain dropping `T` has no side effect.
    577///
    578/// Low level implementations of things like collections, which need to manually
    579/// drop their data, should use this function to avoid unnecessarily
    580/// trying to drop all their contents when they are destroyed. This might not
    581/// make a difference in release builds (where a loop that has no side-effects
    582/// is easily detected and eliminated), but is often a big win for debug builds.
    583///
    584/// Note that [`drop_in_place`] already performs this check, so if your workload
    585/// can be reduced to some small number of [`drop_in_place`] calls, using this is
    586/// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
    587/// will do a single needs_drop check for all the values.
    588///
    589/// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
    590/// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
    591/// values one at a time and should use this API.
    592///
    593/// [`drop_in_place`]: crate::ptr::drop_in_place
    594/// [`HashMap`]: ../../std/collections/struct.HashMap.html
    595///
    596/// # Examples
    597///
    598/// Here's an example of how a collection might make use of `needs_drop`:
    599///
    600/// ```
    601/// use std::{mem, ptr};
    602///
    603/// pub struct MyCollection<T> {
    604/// #   data: [T; 1],
    605///     /* ... */
    606/// }
    607/// # impl<T> MyCollection<T> {
    608/// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
    609/// #   fn free_buffer(&mut self) {}
    610/// # }
    611///
    612/// impl<T> Drop for MyCollection<T> {
    613///     fn drop(&mut self) {
    614///         unsafe {
    615///             // drop the data
    616///             if mem::needs_drop::<T>() {
    617///                 for x in self.iter_mut() {
    618///                     ptr::drop_in_place(x);
    619///                 }
    620///             }
    621///             self.free_buffer();
    622///         }
    623///     }
    624/// }
    625/// ```
    626#[inline]
    627#[must_use]
    628#[stable(feature = "needs_drop", since = "1.21.0")]
    629#[rustc_const_stable(feature = "const_mem_needs_drop", since = "1.36.0")]
    630#[rustc_diagnostic_item = "needs_drop"]
    631pub const fn needs_drop<T: ?Sized>() -> bool {
    632    const { intrinsics::needs_drop::<T>() }
    633}
    634
    635/// Returns the value of type `T` represented by the all-zero byte-pattern.
    636///
    637/// This means that, for example, the padding byte in `(u8, u16)` is not
    638/// necessarily zeroed.
    639///
    640/// There is no guarantee that an all-zero byte-pattern represents a valid value
    641/// of some type `T`. For example, the all-zero byte-pattern is not a valid value
    642/// for reference types (`&T`, `&mut T`) and function pointers. Using `zeroed`
    643/// on such types causes immediate [undefined behavior][ub] because [the Rust
    644/// compiler assumes][inv] that there always is a valid value in a variable it
    645/// considers initialized.
    646///
    647/// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
    648/// It is useful for FFI sometimes, but should generally be avoided.
    649///
    650/// [zeroed]: MaybeUninit::zeroed
    651/// [ub]: ../../reference/behavior-considered-undefined.html
    652/// [inv]: MaybeUninit#initialization-invariant
    653///
    654/// # Examples
    655///
    656/// Correct usage of this function: initializing an integer with zero.
    657///
    658/// ```
    659/// use std::mem;
    660///
    661/// let x: i32 = unsafe { mem::zeroed() };
    662/// assert_eq!(0, x);
    663/// ```
    664///
    665/// *Incorrect* usage of this function: initializing a reference with zero.
    666///
    667/// ```rust,no_run
    668/// # #![allow(invalid_value)]
    669/// use std::mem;
    670///
    671/// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
    672/// let _y: fn() = unsafe { mem::zeroed() }; // And again!
    673/// ```
    674#[inline(always)]
    675#[must_use]
    676#[stable(feature = "rust1", since = "1.0.0")]
    677#[rustc_diagnostic_item = "mem_zeroed"]
    678#[track_caller]
    679#[rustc_const_stable(feature = "const_mem_zeroed", since = "1.75.0")]
    680pub const unsafe fn zeroed<T>() -> T {
    681    // SAFETY: the caller must guarantee that an all-zero value is valid for `T`.
    682    unsafe {
    683        intrinsics::assert_zero_valid::<T>();
    684        MaybeUninit::zeroed().assume_init()
    685    }
    686}
    687
    688/// Bypasses Rust's normal memory-initialization checks by pretending to
    689/// produce a value of type `T`, while doing nothing at all.
    690///
    691/// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
    692/// It also might be slower than using `MaybeUninit<T>` due to mitigations that were put in place to
    693/// limit the potential harm caused by incorrect use of this function in legacy code.
    694///
    695/// The reason for deprecation is that the function basically cannot be used
    696/// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
    697/// As the [`assume_init` documentation][assume_init] explains,
    698/// [the Rust compiler assumes][inv] that values are properly initialized.
    699///
    700/// Truly uninitialized memory like what gets returned here
    701/// is special in that the compiler knows that it does not have a fixed value.
    702/// This makes it undefined behavior to have uninitialized data in a variable even
    703/// if that variable has an integer type.
    704///
    705/// Therefore, it is immediate undefined behavior to call this function on nearly all types,
    706/// including integer types and arrays of integer types, and even if the result is unused.
    707///
    708/// [uninit]: MaybeUninit::uninit
    709/// [assume_init]: MaybeUninit::assume_init
    710/// [inv]: MaybeUninit#initialization-invariant
    711#[inline(always)]
    712#[must_use]
    713#[deprecated(since = "1.39.0", note = "use `mem::MaybeUninit` instead")]
    714#[stable(feature = "rust1", since = "1.0.0")]
    715#[rustc_diagnostic_item = "mem_uninitialized"]
    716#[track_caller]
    717pub unsafe fn uninitialized<T>() -> T {
    718    // SAFETY: the caller must guarantee that an uninitialized value is valid for `T`.
    719    unsafe {
    720        intrinsics::assert_mem_uninitialized_valid::<T>();
    721        let mut val = MaybeUninit::<T>::uninit();
    722
    723        // Fill memory with 0x01, as an imperfect mitigation for old code that uses this function on
    724        // bool, nonnull, and noundef types. But don't do this if we actively want to detect UB.
    725        if !cfg!(any(miri, sanitize = "memory")) {
    726            val.as_mut_ptr().write_bytes(0x01, 1);
    727        }
    728
    729        val.assume_init()
    730    }
    731}
    732
    733/// Swaps the values at two mutable locations, without deinitializing either one.
    734///
    735/// * If you want to swap with a default or dummy value, see [`take`].
    736/// * If you want to swap with a passed value, returning the old value, see [`replace`].
    737///
    738/// # Examples
    739///
    740/// ```
    741/// use std::mem;
    742///
    743/// let mut x = 5;
    744/// let mut y = 42;
    745///
    746/// mem::swap(&mut x, &mut y);
    747///
    748/// assert_eq!(42, x);
    749/// assert_eq!(5, y);
    750/// ```
    751#[inline]
    752#[stable(feature = "rust1", since = "1.0.0")]
    753#[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
    754#[rustc_diagnostic_item = "mem_swap"]
    755pub const fn swap<T>(x: &mut T, y: &mut T) {
    756    // SAFETY: `&mut` guarantees these are typed readable and writable
    757    // as well as non-overlapping.
    758    unsafe { intrinsics::typed_swap_nonoverlapping(x, y) }
    759}
    760
    761/// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
    762///
    763/// * If you want to replace the values of two variables, see [`swap`].
    764/// * If you want to replace with a passed value instead of the default value, see [`replace`].
    765///
    766/// # Examples
    767///
    768/// A simple example:
    769///
    770/// ```
    771/// use std::mem;
    772///
    773/// let mut v: Vec<i32> = vec![1, 2];
    774///
    775/// let old_v = mem::take(&mut v);
    776/// assert_eq!(vec![1, 2], old_v);
    777/// assert!(v.is_empty());
    778/// ```
    779///
    780/// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
    781/// Without `take` you can run into issues like these:
    782///
    783/// ```compile_fail,E0507
    784/// struct Buffer<T> { buf: Vec<T> }
    785///
    786/// impl<T> Buffer<T> {
    787///     fn get_and_reset(&mut self) -> Vec<T> {
    788///         // error: cannot move out of dereference of `&mut`-pointer
    789///         let buf = self.buf;
    790///         self.buf = Vec::new();
    791///         buf
    792///     }
    793/// }
    794/// ```
    795///
    796/// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
    797/// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
    798/// `self`, allowing it to be returned:
    799///
    800/// ```
    801/// use std::mem;
    802///
    803/// # struct Buffer<T> { buf: Vec<T> }
    804/// impl<T> Buffer<T> {
    805///     fn get_and_reset(&mut self) -> Vec<T> {
    806///         mem::take(&mut self.buf)
    807///     }
    808/// }
    809///
    810/// let mut buffer = Buffer { buf: vec![0, 1] };
    811/// assert_eq!(buffer.buf.len(), 2);
    812///
    813/// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
    814/// assert_eq!(buffer.buf.len(), 0);
    815/// ```
    816#[inline]
    817#[stable(feature = "mem_take", since = "1.40.0")]
    818#[rustc_const_unstable(feature = "const_default", issue = "143894")]
    819pub const fn take<T: [const] Default>(dest: &mut T) -> T {
    820    replace(dest, T::default())
    821}
    822
    823/// Moves `src` into the referenced `dest`, returning the previous `dest` value.
    824///
    825/// Neither value is dropped.
    826///
    827/// * If you want to replace the values of two variables, see [`swap`].
    828/// * If you want to replace with a default value, see [`take`].
    829///
    830/// # Examples
    831///
    832/// A simple example:
    833///
    834/// ```
    835/// use std::mem;
    836///
    837/// let mut v: Vec<i32> = vec![1, 2];
    838///
    839/// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
    840/// assert_eq!(vec![1, 2], old_v);
    841/// assert_eq!(vec![3, 4, 5], v);
    842/// ```
    843///
    844/// `replace` allows consumption of a struct field by replacing it with another value.
    845/// Without `replace` you can run into issues like these:
    846///
    847/// ```compile_fail,E0507
    848/// struct Buffer<T> { buf: Vec<T> }
    849///
    850/// impl<T> Buffer<T> {
    851///     fn replace_index(&mut self, i: usize, v: T) -> T {
    852///         // error: cannot move out of dereference of `&mut`-pointer
    853///         let t = self.buf[i];
    854///         self.buf[i] = v;
    855///         t
    856///     }
    857/// }
    858/// ```
    859///
    860/// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
    861/// avoid the move. But `replace` can be used to disassociate the original value at that index from
    862/// `self`, allowing it to be returned:
    863///
    864/// ```
    865/// # #![allow(dead_code)]
    866/// use std::mem;
    867///
    868/// # struct Buffer<T> { buf: Vec<T> }
    869/// impl<T> Buffer<T> {
    870///     fn replace_index(&mut self, i: usize, v: T) -> T {
    871///         mem::replace(&mut self.buf[i], v)
    872///     }
    873/// }
    874///
    875/// let mut buffer = Buffer { buf: vec![0, 1] };
    876/// assert_eq!(buffer.buf[0], 0);
    877///
    878/// assert_eq!(buffer.replace_index(0, 2), 0);
    879/// assert_eq!(buffer.buf[0], 2);
    880/// ```
    881#[inline]
    882#[stable(feature = "rust1", since = "1.0.0")]
    883#[must_use = "if you don't need the old value, you can just assign the new value directly"]
    884#[rustc_const_stable(feature = "const_replace", since = "1.83.0")]
    885#[rustc_diagnostic_item = "mem_replace"]
    886pub const fn replace<T>(dest: &mut T, src: T) -> T {
    887    // It may be tempting to use `swap` to avoid `unsafe` here. Don't!
    888    // The compiler optimizes the implementation below to two `memcpy`s
    889    // while `swap` would require at least three. See PR#83022 for details.
    890
    891    // SAFETY: We read from `dest` but directly write `src` into it afterwards,
    892    // such that the old value is not duplicated. Nothing is dropped and
    893    // nothing here can panic.
    894    unsafe {
    895        // Ideally we wouldn't use the intrinsics here, but going through the
    896        // `ptr` methods introduces two unnecessary UbChecks, so until we can
    897        // remove those for pointers that come from references, this uses the
    898        // intrinsics instead so this stays very cheap in MIR (and debug).
    899
    900        let result = crate::intrinsics::read_via_copy(dest);
    901        crate::intrinsics::write_via_move(dest, src);
    902        result
    903    }
    904}
    905
    906/// Disposes of a value.
    907///
    908/// This effectively does nothing for types which implement `Copy`, e.g.
    909/// integers. Such values are copied and _then_ moved into the function, so the
    910/// value persists after this function call.
    911///
    912/// This function is not magic; it is literally defined as
    913///
    914/// ```
    915/// pub fn drop<T>(_x: T) {}
    916/// ```
    917///
    918/// Because `_x` is moved into the function, it is automatically [dropped][drop] before
    919/// the function returns.
    920///
    921/// [drop]: Drop
    922///
    923/// # Examples
    924///
    925/// Basic usage:
    926///
    927/// ```
    928/// let v = vec![1, 2, 3];
    929///
    930/// drop(v); // explicitly drop the vector
    931/// ```
    932///
    933/// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
    934/// release a [`RefCell`] borrow:
    935///
    936/// ```
    937/// use std::cell::RefCell;
    938///
    939/// let x = RefCell::new(1);
    940///
    941/// let mut mutable_borrow = x.borrow_mut();
    942/// *mutable_borrow = 1;
    943///
    944/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
    945///
    946/// let borrow = x.borrow();
    947/// println!("{}", *borrow);
    948/// ```
    949///
    950/// Integers and other types implementing [`Copy`] are unaffected by `drop`.
    951///
    952/// ```
    953/// # #![allow(dropping_copy_types)]
    954/// #[derive(Copy, Clone)]
    955/// struct Foo(u8);
    956///
    957/// let x = 1;
    958/// let y = Foo(2);
    959/// drop(x); // a copy of `x` is moved and dropped
    960/// drop(y); // a copy of `y` is moved and dropped
    961///
    962/// println!("x: {}, y: {}", x, y.0); // still available
    963/// ```
    964///
    965/// [`RefCell`]: crate::cell::RefCell
    966#[inline]
    967#[stable(feature = "rust1", since = "1.0.0")]
    968#[rustc_const_unstable(feature = "const_destruct", issue = "133214")]
    969#[rustc_diagnostic_item = "mem_drop"]
    970pub const fn drop<T>(_x: T)
    971where
    972    T: [const] Destruct,
    973{
    974}
    975
    976/// Bitwise-copies a value.
    977///
    978/// This function is not magic; it is literally defined as
    979/// ```
    980/// pub const fn copy<T: Copy>(x: &T) -> T { *x }
    981/// ```
    982///
    983/// It is useful when you want to pass a function pointer to a combinator, rather than defining a new closure.
    984///
    985/// Example:
    986/// ```
    987/// #![feature(mem_copy_fn)]
    988/// use core::mem::copy;
    989/// let result_from_ffi_function: Result<(), &i32> = Err(&1);
    990/// let result_copied: Result<(), i32> = result_from_ffi_function.map_err(copy);
    991/// ```
    992#[inline]
    993#[unstable(feature = "mem_copy_fn", issue = "98262")]
    994pub const fn copy<T: Copy>(x: &T) -> T {
    995    *x
    996}
    997
    998/// Interprets `src` as having type `&Dst`, and then reads `src` without moving
    999/// the contained value.
    1000///
    1001/// This function will unsafely assume the pointer `src` is valid for [`size_of::<Dst>`][size_of]
    1002/// bytes by transmuting `&Src` to `&Dst` and then reading the `&Dst` (except that this is done
    1003/// in a way that is correct even when `&Dst` has stricter alignment requirements than `&Src`).
    1004/// It will also unsafely create a copy of the contained value instead of moving out of `src`.
    1005///
    1006/// It is not a compile-time error if `Src` and `Dst` have different sizes, but it
    1007/// is highly encouraged to only invoke this function where `Src` and `Dst` have the
    1008/// same size. This function triggers [undefined behavior][ub] if `Dst` is larger than
    1009/// `Src`.
    1010///
    1011/// [ub]: ../../reference/behavior-considered-undefined.html
    1012///
    1013/// # Examples
    1014///
    1015/// ```
    1016/// use std::mem;
    1017///
    1018/// #[repr(packed)]
    1019/// struct Foo {
    1020///     bar: u8,
    1021/// }
    1022///
    1023/// let foo_array = [10u8];
    1024///
    1025/// unsafe {
    1026///     // Copy the data from 'foo_array' and treat it as a 'Foo'
    1027///     let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
    1028///     assert_eq!(foo_struct.bar, 10);
    1029///
    1030///     // Modify the copied data
    1031///     foo_struct.bar = 20;
    1032///     assert_eq!(foo_struct.bar, 20);
    1033/// }
    1034///
    1035/// // The contents of 'foo_array' should not have changed
    1036/// assert_eq!(foo_array, [10]);
    1037/// ```
    1038#[inline]
    1039#[must_use]
    1040#[track_caller]
    1041#[stable(feature = "rust1", since = "1.0.0")]
    1042#[rustc_const_stable(feature = "const_transmute_copy", since = "1.74.0")]
    1043pub const unsafe fn transmute_copy<Src, Dst>(src: &Src) -> Dst {
    1044    assert!(
    1045        size_of::<Src>() >= size_of::<Dst>(),
    1046        "cannot transmute_copy if Dst is larger than Src"
    1047    );
    1048
    1049    // If Dst has a higher alignment requirement, src might not be suitably aligned.
    1050    if align_of::<Dst>() > align_of::<Src>() {
    1051        // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
    1052        // The caller must guarantee that the actual transmutation is safe.
    1053        unsafe { ptr::read_unaligned(src as *const Src as *const Dst) }
    1054    } else {
    1055        // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
    1056        // We just checked that `src as *const Dst` was properly aligned.
    1057        // The caller must guarantee that the actual transmutation is safe.
    1058        unsafe { ptr::read(src as *const Src as *const Dst) }
    1059    }
    1060}
    1061
    1062/// Opaque type representing the discriminant of an enum.
    1063///
    1064/// See the [`discriminant`] function in this module for more information.
    1065#[stable(feature = "discriminant_value", since = "1.21.0")]
    1066pub struct Discriminant<T>(<T as DiscriminantKind>::Discriminant);
    1067
    1068// N.B. These trait implementations cannot be derived because we don't want any bounds on T.
    1069
    1070#[stable(feature = "discriminant_value", since = "1.21.0")]
    1071impl<T> Copy for Discriminant<T> {}
    1072
    1073#[stable(feature = "discriminant_value", since = "1.21.0")]
    1074impl<T> clone::Clone for Discriminant<T> {
    1075    fn clone(&self) -> Self {
    1076        *self
    1077    }
    1078}
    1079
    1080#[doc(hidden)]
    1081#[unstable(feature = "trivial_clone", issue = "none")]
    1082unsafe impl<T> TrivialClone for Discriminant<T> {}
    1083
    1084#[stable(feature = "discriminant_value", since = "1.21.0")]
    1085impl<T> cmp::PartialEq for Discriminant<T> {
    1086    fn eq(&self, rhs: &Self) -> bool {
    1087        self.0 == rhs.0
    1088    }
    1089}
    1090
    1091#[stable(feature = "discriminant_value", since = "1.21.0")]
    1092impl<T> cmp::Eq for Discriminant<T> {}
    1093
    1094#[stable(feature = "discriminant_value", since = "1.21.0")]
    1095impl<T> hash::Hash for Discriminant<T> {
    1096    fn hash<H: hash::Hasher>(&self, state: &mut H) {
    1097        self.0.hash(state);
    1098    }
    1099}
    1100
    1101#[stable(feature = "discriminant_value", since = "1.21.0")]
    1102impl<T> fmt::Debug for Discriminant<T> {
    1103    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
    1104        fmt.debug_tuple("Discriminant").field(&self.0).finish()
    1105    }
    1106}
    1107
    1108/// Returns a value uniquely identifying the enum variant in `v`.
    1109///
    1110/// If `T` is not an enum, calling this function will not result in undefined behavior, but the
    1111/// return value is unspecified.
    1112///
    1113/// # Stability
    1114///
    1115/// The discriminant of an enum variant may change if the enum definition changes. A discriminant
    1116/// of some variant will not change between compilations with the same compiler. See the [Reference]
    1117/// for more information.
    1118///
    1119/// [Reference]: ../../reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
    1120///
    1121/// The value of a [`Discriminant<T>`] is independent of any *free lifetimes* in `T`. As such,
    1122/// reading or writing a `Discriminant<Foo<'a>>` as a `Discriminant<Foo<'b>>` (whether via
    1123/// [`transmute`] or otherwise) is always sound. Note that this is **not** true for other kinds
    1124/// of generic parameters and for higher-ranked lifetimes; `Discriminant<Foo<A>>` and
    1125/// `Discriminant<Foo<B>>` as well as `Discriminant<Bar<dyn for<'a> Trait<'a>>>` and
    1126/// `Discriminant<Bar<dyn Trait<'static>>>` may be incompatible.
    1127///
    1128/// # Examples
    1129///
    1130/// This can be used to compare enums that carry data, while disregarding
    1131/// the actual data:
    1132///
    1133/// ```
    1134/// use std::mem;
    1135///
    1136/// enum Foo { A(&'static str), B(i32), C(i32) }
    1137///
    1138/// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
    1139/// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
    1140/// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
    1141/// ```
    1142///
    1143/// ## Accessing the numeric value of the discriminant
    1144///
    1145/// Note that it is *undefined behavior* to [`transmute`] from [`Discriminant`] to a primitive!
    1146///
    1147/// If an enum has only unit variants, then the numeric value of the discriminant can be accessed
    1148/// with an [`as`] cast:
    1149///
    1150/// ```
    1151/// enum Enum {
    1152///     Foo,
    1153///     Bar,
    1154///     Baz,
    1155/// }
    1156///
    1157/// assert_eq!(0, Enum::Foo as isize);
    1158/// assert_eq!(1, Enum::Bar as isize);
    1159/// assert_eq!(2, Enum::Baz as isize);
    1160/// ```
    1161///
    1162/// If an enum has opted-in to having a [primitive representation] for its discriminant,
    1163/// then it's possible to use pointers to read the memory location storing the discriminant.
    1164/// That **cannot** be done for enums using the [default representation], however, as it's
    1165/// undefined what layout the discriminant has and where it's stored — it might not even be
    1166/// stored at all!
    1167///
    1168/// [`as`]: ../../std/keyword.as.html
    1169/// [primitive representation]: ../../reference/type-layout.html#primitive-representations
    1170/// [default representation]: ../../reference/type-layout.html#the-default-representation
    1171/// ```
    1172/// #[repr(u8)]
    1173/// enum Enum {
    1174///     Unit,
    1175///     Tuple(bool),
    1176///     Struct { a: bool },
    1177/// }
    1178///
    1179/// impl Enum {
    1180///     fn discriminant(&self) -> u8 {
    1181///         // SAFETY: Because `Self` is marked `repr(u8)`, its layout is a `repr(C)` `union`
    1182///         // between `repr(C)` structs, each of which has the `u8` discriminant as its first
    1183///         // field, so we can read the discriminant without offsetting the pointer.
    1184///         unsafe { *<*const _>::from(self).cast::<u8>() }
    1185///     }
    1186/// }
    1187///
    1188/// let unit_like = Enum::Unit;
    1189/// let tuple_like = Enum::Tuple(true);
    1190/// let struct_like = Enum::Struct { a: false };
    1191/// assert_eq!(0, unit_like.discriminant());
    1192/// assert_eq!(1, tuple_like.discriminant());
    1193/// assert_eq!(2, struct_like.discriminant());
    1194///
    1195/// // ⚠️ This is undefined behavior. Don't do this. ⚠️
    1196/// // assert_eq!(0, unsafe { std::mem::transmute::<_, u8>(std::mem::discriminant(&unit_like)) });
    1197/// ```
    1198#[stable(feature = "discriminant_value", since = "1.21.0")]
    1199#[rustc_const_stable(feature = "const_discriminant", since = "1.75.0")]
    1200#[rustc_diagnostic_item = "mem_discriminant"]
    1201#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
    1202pub const fn discriminant<T>(v: &T) -> Discriminant<T> {
    1203    Discriminant(intrinsics::discriminant_value(v))
    1204}
    1205
    1206/// Returns the number of variants in the enum type `T`.
    1207///
    1208/// If `T` is not an enum, calling this function will not result in undefined behavior, but the
    1209/// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX`
    1210/// the return value is unspecified. Uninhabited variants will be counted.
    1211///
    1212/// Note that an enum may be expanded with additional variants in the future
    1213/// as a non-breaking change, for example if it is marked `#[non_exhaustive]`,
    1214/// which will change the result of this function.
    1215///
    1216/// # Examples
    1217///
    1218/// ```
    1219/// # #![feature(never_type)]
    1220/// # #![feature(variant_count)]
    1221///
    1222/// use std::mem;
    1223///
    1224/// enum Void {}
    1225/// enum Foo { A(&'static str), B(i32), C(i32) }
    1226///
    1227/// assert_eq!(mem::variant_count::<Void>(), 0);
    1228/// assert_eq!(mem::variant_count::<Foo>(), 3);
    1229///
    1230/// assert_eq!(mem::variant_count::<Option<!>>(), 2);
    1231/// assert_eq!(mem::variant_count::<Result<!, !>>(), 2);
    1232/// ```
    1233#[inline(always)]
    1234#[must_use]
    1235#[unstable(feature = "variant_count", issue = "73662")]
    1236#[rustc_const_unstable(feature = "variant_count", issue = "73662")]
    1237#[rustc_diagnostic_item = "mem_variant_count"]
    1238pub const fn variant_count<T>() -> usize {
    1239    const { intrinsics::variant_count::<T>() }
    1240}
    1241
    1242/// Provides associated constants for various useful properties of types,
    1243/// to give them a canonical form in our code and make them easier to read.
    1244///
    1245/// This is here only to simplify all the ZST checks we need in the library.
    1246/// It's not on a stabilization track right now.
    1247#[doc(hidden)]
    1248#[unstable(feature = "sized_type_properties", issue = "none")]
    1249pub trait SizedTypeProperties: Sized {
    1250    #[doc(hidden)]
    1251    #[unstable(feature = "sized_type_properties", issue = "none")]
    1252    #[lang = "mem_size_const"]
    1253    const SIZE: usize = intrinsics::size_of::<Self>();
    1254
    1255    #[doc(hidden)]
    1256    #[unstable(feature = "sized_type_properties", issue = "none")]
    1257    #[lang = "mem_align_const"]
    1258    const ALIGN: usize = intrinsics::align_of::<Self>();
    1259
    1260    /// `true` if this type requires no storage.
    1261    /// `false` if its [size](size_of) is greater than zero.
    1262    ///
    1263    /// # Examples
    1264    ///
    1265    /// ```
    1266    /// #![feature(sized_type_properties)]
    1267    /// use core::mem::SizedTypeProperties;
    1268    ///
    1269    /// fn do_something_with<T>() {
    1270    ///     if T::IS_ZST {
    1271    ///         // ... special approach ...
    1272    ///     } else {
    1273    ///         // ... the normal thing ...
    1274    ///     }
    1275    /// }
    1276    ///
    1277    /// struct MyUnit;
    1278    /// assert!(MyUnit::IS_ZST);
    1279    ///
    1280    /// // For negative checks, consider using UFCS to emphasize the negation
    1281    /// assert!(!<i32>::IS_ZST);
    1282    /// // As it can sometimes hide in the type otherwise
    1283    /// assert!(!String::IS_ZST);
    1284    /// ```
    1285    #[doc(hidden)]
    1286    #[unstable(feature = "sized_type_properties", issue = "none")]
    1287    const IS_ZST: bool = Self::SIZE == 0;
    1288
    1289    #[doc(hidden)]
    1290    #[unstable(feature = "sized_type_properties", issue = "none")]
    1291    const LAYOUT: Layout = {
    1292        // SAFETY: if the type is instantiated, rustc already ensures that its
    1293        // layout is valid. Use the unchecked constructor to avoid inserting a
    1294        // panicking codepath that needs to be optimized out.
    1295        unsafe { Layout::from_size_align_unchecked(Self::SIZE, Self::ALIGN) }
    1296    };
    1297
    1298    /// The largest safe length for a `[Self]`.
    1299    ///
    1300    /// Anything larger than this would make `size_of_val` overflow `isize::MAX`,
    1301    /// which is never allowed for a single object.
    1302    #[doc(hidden)]
    1303    #[unstable(feature = "sized_type_properties", issue = "none")]
    1304    const MAX_SLICE_LEN: usize = match Self::SIZE {
    1305        0 => usize::MAX,
    1306        n => (isize::MAX as usize) / n,
    1307    };
    1308}
    1309#[doc(hidden)]
    1310#[unstable(feature = "sized_type_properties", issue = "none")]
    1311impl<T> SizedTypeProperties for T {}
    1312
    1313/// Expands to the offset in bytes of a field from the beginning of the given type.
    1314///
    1315/// The type may be a `struct`, `enum`, `union`, or tuple.
    1316///
    1317/// The field may be a nested field (`field1.field2`), but not an array index.
    1318/// The field must be visible to the call site.
    1319///
    1320/// The offset is returned as a [`usize`].
    1321///
    1322/// # Offsets of, and in, dynamically sized types
    1323///
    1324/// The field’s type must be [`Sized`], but it may be located in a [dynamically sized] container.
    1325/// If the field type is dynamically sized, then you cannot use `offset_of!` (since the field's
    1326/// alignment, and therefore its offset, may also be dynamic) and must take the offset from an
    1327/// actual pointer to the container instead.
    1328///
    1329/// ```
    1330/// # use core::mem;
    1331/// # use core::fmt::Debug;
    1332/// #[repr(C)]
    1333/// pub struct Struct<T: ?Sized> {
    1334///     a: u8,
    1335///     b: T,
    1336/// }
    1337///
    1338/// #[derive(Debug)]
    1339/// #[repr(C, align(4))]
    1340/// struct Align4(u32);
    1341///
    1342/// assert_eq!(mem::offset_of!(Struct<dyn Debug>, a), 0); // OK — Sized field
    1343/// assert_eq!(mem::offset_of!(Struct<Align4>, b), 4); // OK — not DST
    1344///
    1345/// // assert_eq!(mem::offset_of!(Struct<dyn Debug>, b), 1);
    1346/// // ^^^ error[E0277]: ... cannot be known at compilation time
    1347///
    1348/// // To obtain the offset of a !Sized field, examine a concrete value
    1349/// // instead of using offset_of!.
    1350/// let value: Struct<Align4> = Struct { a: 1, b: Align4(2) };
    1351/// let ref_unsized: &Struct<dyn Debug> = &value;
    1352/// let offset_of_b = unsafe {
    1353///     (&raw const ref_unsized.b).byte_offset_from_unsigned(ref_unsized)
    1354/// };
    1355/// assert_eq!(offset_of_b, 4);
    1356/// ```
    1357///
    1358/// If you need to obtain the offset of a field of a `!Sized` type, then, since the offset may
    1359/// depend on the particular value being stored (in particular, `dyn Trait` values have a
    1360/// dynamically-determined alignment), you must retrieve the offset from a specific reference
    1361/// or pointer, and so you cannot use `offset_of!` to work without one.
    1362///
    1363/// # Layout is subject to change
    1364///
    1365/// Note that type layout is, in general, [subject to change and
    1366/// platform-specific](https://doc.rust-lang.org/reference/type-layout.html). If
    1367/// layout stability is required, consider using an [explicit `repr` attribute].
    1368///
    1369/// Rust guarantees that the offset of a given field within a given type will not
    1370/// change over the lifetime of the program. However, two different compilations of
    1371/// the same program may result in different layouts. Also, even within a single
    1372/// program execution, no guarantees are made about types which are *similar* but
    1373/// not *identical*, e.g.:
    1374///
    1375/// ```
    1376/// struct Wrapper<T, U>(T, U);
    1377///
    1378/// type A = Wrapper<u8, u8>;
    1379/// type B = Wrapper<u8, i8>;
    1380///
    1381/// // Not necessarily identical even though `u8` and `i8` have the same layout!
    1382/// // assert_eq!(mem::offset_of!(A, 1), mem::offset_of!(B, 1));
    1383///
    1384/// #[repr(transparent)]
    1385/// struct U8(u8);
    1386///
    1387/// type C = Wrapper<u8, U8>;
    1388///
    1389/// // Not necessarily identical even though `u8` and `U8` have the same layout!
    1390/// // assert_eq!(mem::offset_of!(A, 1), mem::offset_of!(C, 1));
    1391///
    1392/// struct Empty<T>(core::marker::PhantomData<T>);
    1393///
    1394/// // Not necessarily identical even though `PhantomData` always has the same layout!
    1395/// // assert_eq!(mem::offset_of!(Empty<u8>, 0), mem::offset_of!(Empty<i8>, 0));
    1396/// ```
    1397///
    1398/// [explicit `repr` attribute]: https://doc.rust-lang.org/reference/type-layout.html#representations
    1399///
    1400/// # Unstable features
    1401///
    1402/// The following unstable features expand the functionality of `offset_of!`:
    1403///
    1404/// * [`offset_of_enum`] — allows `enum` variants to be traversed as if they were fields.
    1405/// * [`offset_of_slice`] — allows getting the offset of a field of type `[T]`.
    1406///
    1407/// # Examples
    1408///
    1409/// ```
    1410/// use std::mem;
    1411/// #[repr(C)]
    1412/// struct FieldStruct {
    1413///     first: u8,
    1414///     second: u16,
    1415///     third: u8
    1416/// }
    1417///
    1418/// assert_eq!(mem::offset_of!(FieldStruct, first), 0);
    1419/// assert_eq!(mem::offset_of!(FieldStruct, second), 2);
    1420/// assert_eq!(mem::offset_of!(FieldStruct, third), 4);
    1421///
    1422/// #[repr(C)]
    1423/// struct NestedA {
    1424///     b: NestedB
    1425/// }
    1426///
    1427/// #[repr(C)]
    1428/// struct NestedB(u8);
    1429///
    1430/// assert_eq!(mem::offset_of!(NestedA, b.0), 0);
    1431/// ```
    1432///
    1433/// [dynamically sized]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
    1434/// [`offset_of_enum`]: https://doc.rust-lang.org/nightly/unstable-book/language-features/offset-of-enum.html
    1435/// [`offset_of_slice`]: https://doc.rust-lang.org/nightly/unstable-book/language-features/offset-of-slice.html
    1436#[stable(feature = "offset_of", since = "1.77.0")]
    1437#[allow_internal_unstable(builtin_syntax, core_intrinsics)]
    1438pub macro offset_of($Container:ty, $($fields:expr)+ $(,)?) {
    1439    // The `{}` is for better error messages
    1440    const {builtin # offset_of($Container, $($fields)+)}
    1441}
    1442
    1443/// Create a fresh instance of the inhabited ZST type `T`.
    1444///
    1445/// Prefer this to [`zeroed`] or [`uninitialized`] or [`transmute_copy`]
    1446/// in places where you know that `T` is zero-sized, but don't have a bound
    1447/// (such as [`Default`]) that would allow you to instantiate it using safe code.
    1448///
    1449/// If you're not sure whether `T` is an inhabited ZST, then you should be
    1450/// using [`MaybeUninit`], not this function.
    1451///
    1452/// # Panics
    1453///
    1454/// If `size_of::<T>() != 0`.
    1455///
    1456/// # Safety
    1457///
    1458/// - `T` must be *[inhabited]*, i.e. possible to construct. This means that types
    1459///   like zero-variant enums and [`!`] are unsound to conjure.
    1460/// - You must use the value only in ways which do not violate any *safety*
    1461///   invariants of the type.
    1462///
    1463/// While it's easy to create a *valid* instance of an inhabited ZST, since having
    1464/// no bits in its representation means there's only one possible value, that
    1465/// doesn't mean that it's always *sound* to do so.
    1466///
    1467/// For example, a library could design zero-sized tokens that are `!Default + !Clone`, limiting
    1468/// their creation to functions that initialize some state or establish a scope. Conjuring such a
    1469/// token could break invariants and lead to unsoundness.
    1470///
    1471/// # Examples
    1472///
    1473/// ```
    1474/// #![feature(mem_conjure_zst)]
    1475/// use std::mem::conjure_zst;
    1476///
    1477/// assert_eq!(unsafe { conjure_zst::<()>() }, ());
    1478/// assert_eq!(unsafe { conjure_zst::<[i32; 0]>() }, []);
    1479/// ```
    1480///
    1481/// [inhabited]: https://doc.rust-lang.org/reference/glossary.html#inhabited
    1482#[unstable(feature = "mem_conjure_zst", issue = "95383")]
    1483pub const unsafe fn conjure_zst<T>() -> T {
    1484    const_assert!(
    1485        size_of::<T>() == 0,
    1486        "mem::conjure_zst invoked on a nonzero-sized type",
    1487        "mem::conjure_zst invoked on type {t}, which is not zero-sized",
    1488        t: &str = stringify!(T)
    1489    );
    1490
    1491    // SAFETY: because the caller must guarantee that it's inhabited and zero-sized,
    1492    // there's nothing in the representation that needs to be set.
    1493    // `assume_init` calls `assert_inhabited`, so we don't need to here.
    1494    unsafe {
    1495        #[allow(clippy::uninit_assumed_init)]
    1496        MaybeUninit::uninit().assume_init()
    1497    }
    1498}