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