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