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