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