Skip to main content

core/mem/
mod.rs

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