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