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