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