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