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