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