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