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