core/mem/
mod.rs

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