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