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