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