Skip to main content

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