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