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_subset"))]
10use crate::clone::TrivialClone;
11use crate::marker::{Destruct, DiscriminantKind};
12use crate::panic::const_assert;
13#[cfg(not(feature = "ferrocene_subset"))]
14use crate::{clone, cmp, fmt, hash, intrinsics, ptr};
15
16// Ferrocene addition: imports for certified subset
17#[cfg(feature = "ferrocene_subset")]
18#[rustfmt::skip]
19use crate::{cmp, intrinsics, ptr};
20
21mod manually_drop;
22#[stable(feature = "manually_drop", since = "1.20.0")]
23pub use manually_drop::ManuallyDrop;
24
25mod maybe_uninit;
26#[stable(feature = "maybe_uninit", since = "1.36.0")]
27pub use maybe_uninit::MaybeUninit;
28
29mod maybe_dangling;
30#[unstable(feature = "maybe_dangling", issue = "118166")]
31pub use maybe_dangling::MaybeDangling;
32
33#[cfg(not(feature = "ferrocene_subset"))]
34mod transmutability;
35#[unstable(feature = "transmutability", issue = "99571")]
36#[cfg(not(feature = "ferrocene_subset"))]
37pub use transmutability::{Assume, TransmuteFrom};
38
39#[cfg(not(feature = "ferrocene_subset"))]
40mod drop_guard;
41#[unstable(feature = "drop_guard", issue = "144426")]
42#[cfg(not(feature = "ferrocene_subset"))]
43pub use drop_guard::DropGuard;
44
45// This one has to be a re-export (rather than wrapping the underlying intrinsic) so that we can do
46// the special magic "types have equal size" check at the call site.
47#[stable(feature = "rust1", since = "1.0.0")]
48#[doc(inline)]
49pub use crate::intrinsics::transmute;
50
51/// Takes ownership and "forgets" about the value **without running its destructor**.
52///
53/// Any resources the value manages, such as heap memory or a file handle, will linger
54/// forever in an unreachable state. However, it does not guarantee that pointers
55/// to this memory will remain valid.
56///
57/// * If you want to leak memory, see [`Box::leak`].
58/// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`].
59/// * If you want to dispose of a value properly, running its destructor, see
60/// [`mem::drop`].
61///
62/// # Safety
63///
64/// `forget` is not marked as `unsafe`, because Rust's safety guarantees
65/// do not include a guarantee that destructors will always run. For example,
66/// a program can create a reference cycle using [`Rc`][rc], or call
67/// [`process::exit`][exit] to exit without running destructors. Thus, allowing
68/// `mem::forget` from safe code does not fundamentally change Rust's safety
69/// guarantees.
70///
71/// That said, leaking resources such as memory or I/O objects is usually undesirable.
72/// The need comes up in some specialized use cases for FFI or unsafe code, but even
73/// then, [`ManuallyDrop`] is typically preferred.
74///
75/// Because forgetting a value is allowed, any `unsafe` code you write must
76/// allow for this possibility. You cannot return a value and expect that the
77/// caller will necessarily run the value's destructor.
78///
79/// [rc]: ../../std/rc/struct.Rc.html
80/// [exit]: ../../std/process/fn.exit.html
81///
82/// # Examples
83///
84/// The canonical safe use of `mem::forget` is to circumvent a value's destructor
85/// implemented by the `Drop` trait. For example, this will leak a `File`, i.e. reclaim
86/// the space taken by the variable but never close the underlying system resource:
87///
88/// ```no_run
89/// use std::mem;
90/// use std::fs::File;
91///
92/// let file = File::open("foo.txt").unwrap();
93/// mem::forget(file);
94/// ```
95///
96/// This is useful when the ownership of the underlying resource was previously
97/// transferred to code outside of Rust, for example by transmitting the raw
98/// file descriptor to C code.
99///
100/// # Relationship with `ManuallyDrop`
101///
102/// While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone.
103/// [`ManuallyDrop`] should be used instead. Consider, for example, this code:
104///
105/// ```
106/// use std::mem;
107///
108/// let mut v = vec![65, 122];
109/// // Build a `String` using the contents of `v`
110/// let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) };
111/// // leak `v` because its memory is now managed by `s`
112/// mem::forget(v); // ERROR - v is invalid and must not be passed to a function
113/// assert_eq!(s, "Az");
114/// // `s` is implicitly dropped and its memory deallocated.
115/// ```
116///
117/// There are two issues with the above example:
118///
119/// * If more code were added between the construction of `String` and the invocation of
120/// `mem::forget()`, a panic within it would cause a double free because the same memory
121/// is handled by both `v` and `s`.
122/// * After calling `v.as_mut_ptr()` and transmitting the ownership of the data to `s`,
123/// the `v` value is invalid. Even when a value is just moved to `mem::forget` (which won't
124/// inspect it), some types have strict requirements on their values that
125/// make them invalid when dangling or no longer owned. Using invalid values in any
126/// way, including passing them to or returning them from functions, constitutes
127/// undefined behavior and may break the assumptions made by the compiler.
128///
129/// Switching to `ManuallyDrop` avoids both issues:
130///
131/// ```
132/// use std::mem::ManuallyDrop;
133///
134/// let v = vec![65, 122];
135/// // Before we disassemble `v` into its raw parts, make sure it
136/// // does not get dropped!
137/// let mut v = ManuallyDrop::new(v);
138/// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak.
139/// let (ptr, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity());
140/// // Finally, build a `String`.
141/// let s = unsafe { String::from_raw_parts(ptr, len, cap) };
142/// assert_eq!(s, "Az");
143/// // `s` is implicitly dropped and its memory deallocated.
144/// ```
145///
146/// `ManuallyDrop` robustly prevents double-free because we disable `v`'s destructor
147/// before doing anything else. `mem::forget()` doesn't allow this because it consumes its
148/// argument, forcing us to call it only after extracting anything we need from `v`. Even
149/// if a panic were introduced between construction of `ManuallyDrop` and building the
150/// string (which cannot happen in the code as shown), it would result in a leak and not a
151/// double free. In other words, `ManuallyDrop` errs on the side of leaking instead of
152/// erring on the side of (double-)dropping.
153///
154/// Also, `ManuallyDrop` prevents us from having to "touch" `v` after transferring the
155/// ownership to `s` — the final step of interacting with `v` to dispose of it without
156/// running its destructor is entirely avoided.
157///
158/// [`Box`]: ../../std/boxed/struct.Box.html
159/// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak
160/// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw
161/// [`mem::drop`]: drop
162/// [ub]: ../../reference/behavior-considered-undefined.html
163#[inline]
164#[rustc_const_stable(feature = "const_forget", since = "1.46.0")]
165#[stable(feature = "rust1", since = "1.0.0")]
166#[rustc_diagnostic_item = "mem_forget"]
167pub const fn forget<T>(t: T) {
168 let _ = ManuallyDrop::new(t);
169}
170
171/// Like [`forget`], but also accepts unsized values.
172///
173/// While Rust does not permit unsized locals since its removal in [#111942] it is
174/// still possible to call functions with unsized values from a function argument
175/// or place expression.
176///
177/// ```rust
178/// #![feature(unsized_fn_params, forget_unsized)]
179/// #![allow(internal_features)]
180///
181/// use std::mem::forget_unsized;
182///
183/// pub fn in_place() {
184/// forget_unsized(*Box::<str>::from("str"));
185/// }
186///
187/// pub fn param(x: str) {
188/// forget_unsized(x);
189/// }
190/// ```
191///
192/// This works because the compiler will alter these functions to pass the parameter
193/// by reference instead. This trick is necessary to support `Box<dyn FnOnce()>: FnOnce()`.
194/// See [#68304] and [#71170] for more information.
195///
196/// [#111942]: https://github.com/rust-lang/rust/issues/111942
197/// [#68304]: https://github.com/rust-lang/rust/issues/68304
198/// [#71170]: https://github.com/rust-lang/rust/pull/71170
199#[inline]
200#[unstable(feature = "forget_unsized", issue = "none")]
201#[cfg(not(feature = "ferrocene_subset"))]
202pub fn forget_unsized<T: ?Sized>(t: T) {
203 intrinsics::forget(t)
204}
205
206/// Returns the size of a type in bytes.
207///
208/// More specifically, this is the offset in bytes between successive elements
209/// in an array with that item type including alignment padding. Thus, for any
210/// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
211///
212/// In general, the size of a type is not stable across compilations, but
213/// specific types such as primitives are.
214///
215/// The following table gives the size for primitives.
216///
217/// Type | `size_of::<Type>()`
218/// ---- | ---------------
219/// () | 0
220/// bool | 1
221/// u8 | 1
222/// u16 | 2
223/// u32 | 4
224/// u64 | 8
225/// u128 | 16
226/// i8 | 1
227/// i16 | 2
228/// i32 | 4
229/// i64 | 8
230/// i128 | 16
231/// f32 | 4
232/// f64 | 8
233/// char | 4
234///
235/// Furthermore, `usize` and `isize` have the same size.
236///
237/// The types [`*const T`], `&T`, [`Box<T>`], [`Option<&T>`], and `Option<Box<T>>` all have
238/// the same size. If `T` is `Sized`, all of those types have the same size as `usize`.
239///
240/// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
241/// have the same size. Likewise for `*const T` and `*mut T`.
242///
243/// # Size of `#[repr(C)]` items
244///
245/// The `C` representation for items has a defined layout. With this layout,
246/// the size of items is also stable as long as all fields have a stable size.
247///
248/// ## Size of Structs
249///
250/// For `struct`s, the size is determined by the following algorithm.
251///
252/// For each field in the struct ordered by declaration order:
253///
254/// 1. Add the size of the field.
255/// 2. Round up the current size to the nearest multiple of the next field's [alignment].
256///
257/// Finally, round the size of the struct to the nearest multiple of its [alignment].
258/// The alignment of the struct is usually the largest alignment of all its
259/// fields; this can be changed with the use of `repr(align(N))`.
260///
261/// Unlike `C`, zero sized structs are not rounded up to one byte in size.
262///
263/// ## Size of Enums
264///
265/// Enums that carry no data other than the discriminant have the same size as C enums
266/// on the platform they are compiled for.
267///
268/// ## Size of Unions
269///
270/// The size of a union is the size of its largest field.
271///
272/// Unlike `C`, zero sized unions are not rounded up to one byte in size.
273///
274/// # Examples
275///
276/// ```
277/// // Some primitives
278/// assert_eq!(4, size_of::<i32>());
279/// assert_eq!(8, size_of::<f64>());
280/// assert_eq!(0, size_of::<()>());
281///
282/// // Some arrays
283/// assert_eq!(8, size_of::<[i32; 2]>());
284/// assert_eq!(12, size_of::<[i32; 3]>());
285/// assert_eq!(0, size_of::<[i32; 0]>());
286///
287///
288/// // Pointer size equality
289/// assert_eq!(size_of::<&i32>(), size_of::<*const i32>());
290/// assert_eq!(size_of::<&i32>(), size_of::<Box<i32>>());
291/// assert_eq!(size_of::<&i32>(), size_of::<Option<&i32>>());
292/// assert_eq!(size_of::<Box<i32>>(), size_of::<Option<Box<i32>>>());
293/// ```
294///
295/// Using `#[repr(C)]`.
296///
297/// ```
298/// #[repr(C)]
299/// struct FieldStruct {
300/// first: u8,
301/// second: u16,
302/// third: u8
303/// }
304///
305/// // The size of the first field is 1, so add 1 to the size. Size is 1.
306/// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
307/// // The size of the second field is 2, so add 2 to the size. Size is 4.
308/// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
309/// // The size of the third field is 1, so add 1 to the size. Size is 5.
310/// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
311/// // fields is 2), so add 1 to the size for padding. Size is 6.
312/// assert_eq!(6, size_of::<FieldStruct>());
313///
314/// #[repr(C)]
315/// struct TupleStruct(u8, u16, u8);
316///
317/// // Tuple structs follow the same rules.
318/// assert_eq!(6, size_of::<TupleStruct>());
319///
320/// // Note that reordering the fields can lower the size. We can remove both padding bytes
321/// // by putting `third` before `second`.
322/// #[repr(C)]
323/// struct FieldStructOptimized {
324/// first: u8,
325/// third: u8,
326/// second: u16
327/// }
328///
329/// assert_eq!(4, size_of::<FieldStructOptimized>());
330///
331/// // Union size is the size of the largest field.
332/// #[repr(C)]
333/// union ExampleUnion {
334/// smaller: u8,
335/// larger: u16
336/// }
337///
338/// assert_eq!(2, size_of::<ExampleUnion>());
339/// ```
340///
341/// [alignment]: align_of
342/// [`*const T`]: primitive@pointer
343/// [`Box<T>`]: ../../std/boxed/struct.Box.html
344/// [`Option<&T>`]: crate::option::Option
345///
346#[inline(always)]
347#[must_use]
348#[stable(feature = "rust1", since = "1.0.0")]
349#[rustc_promotable]
350#[rustc_const_stable(feature = "const_mem_size_of", since = "1.24.0")]
351#[rustc_diagnostic_item = "mem_size_of"]
352pub const fn size_of<T>() -> usize {
353 <T as SizedTypeProperties>::SIZE
354}
355
356/// Returns the size of the pointed-to value in bytes.
357///
358/// This is usually the same as [`size_of::<T>()`]. However, when `T` *has* no
359/// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
360/// then `size_of_val` can be used to get the dynamically-known size.
361///
362/// [trait object]: ../../book/ch17-02-trait-objects.html
363///
364/// # Examples
365///
366/// ```
367/// assert_eq!(4, size_of_val(&5i32));
368///
369/// let x: [u8; 13] = [0; 13];
370/// let y: &[u8] = &x;
371/// assert_eq!(13, size_of_val(y));
372/// ```
373///
374/// [`size_of::<T>()`]: size_of
375#[inline]
376#[must_use]
377#[stable(feature = "rust1", since = "1.0.0")]
378#[rustc_const_stable(feature = "const_size_of_val", since = "1.85.0")]
379#[rustc_diagnostic_item = "mem_size_of_val"]
380pub const fn size_of_val<T: ?Sized>(val: &T) -> usize {
381 // SAFETY: `val` is a reference, so it's a valid raw pointer
382 unsafe { intrinsics::size_of_val(val) }
383}
384
385/// Returns the size of the pointed-to value in bytes.
386///
387/// This is usually the same as [`size_of::<T>()`]. However, when `T` *has* no
388/// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
389/// then `size_of_val_raw` can be used to get the dynamically-known size.
390///
391/// # Safety
392///
393/// This function is only safe to call if the following conditions hold:
394///
395/// - If `T` is `Sized`, this function is always safe to call.
396/// - If the unsized tail of `T` is:
397/// - a [slice], then the length of the slice tail must be an initialized
398/// integer, and the size of the *entire value*
399/// (dynamic tail length + statically sized prefix) must fit in `isize`.
400/// For the special case where the dynamic tail length is 0, this function
401/// is safe to call.
402// NOTE: the reason this is safe is that if an overflow were to occur already with size 0,
403// then we would stop compilation as even the "statically known" part of the type would
404// already be too big (or the call may be in dead code and optimized away, but then it
405// doesn't matter).
406/// - a [trait object], then the vtable part of the pointer must point
407/// to a valid vtable acquired by an unsizing coercion, and the size
408/// of the *entire value* (dynamic tail length + statically sized prefix)
409/// must fit in `isize`.
410/// - an (unstable) [extern type], then this function is always safe to
411/// call, but may panic or otherwise return the wrong value, as the
412/// extern type's layout is not known. This is the same behavior as
413/// [`size_of_val`] on a reference to a type with an extern type tail.
414/// - otherwise, it is conservatively not allowed to call this function.
415///
416/// [`size_of::<T>()`]: size_of
417/// [trait object]: ../../book/ch17-02-trait-objects.html
418/// [extern type]: ../../unstable-book/language-features/extern-types.html
419///
420/// # Examples
421///
422/// ```
423/// #![feature(layout_for_ptr)]
424/// use std::mem;
425///
426/// assert_eq!(4, size_of_val(&5i32));
427///
428/// let x: [u8; 13] = [0; 13];
429/// let y: &[u8] = &x;
430/// assert_eq!(13, unsafe { mem::size_of_val_raw(y) });
431/// ```
432#[inline]
433#[must_use]
434#[unstable(feature = "layout_for_ptr", issue = "69835")]
435pub const unsafe fn size_of_val_raw<T: ?Sized>(val: *const T) -> usize {
436 // SAFETY: the caller must provide a valid raw pointer
437 unsafe { intrinsics::size_of_val(val) }
438}
439
440/// Returns the [ABI]-required minimum alignment of a type in bytes.
441///
442/// Every reference to a value of the type `T` must be a multiple of this number.
443///
444/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
445///
446/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
447///
448/// # Examples
449///
450/// ```
451/// # #![allow(deprecated)]
452/// use std::mem;
453///
454/// assert_eq!(4, mem::min_align_of::<i32>());
455/// ```
456#[inline]
457#[must_use]
458#[stable(feature = "rust1", since = "1.0.0")]
459#[deprecated(note = "use `align_of` instead", since = "1.2.0", suggestion = "align_of")]
460#[cfg(not(feature = "ferrocene_subset"))]
461pub fn min_align_of<T>() -> usize {
462 <T as SizedTypeProperties>::ALIGN
463}
464
465/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
466/// bytes.
467///
468/// Every reference to a value of the type `T` must be a multiple of this number.
469///
470/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
471///
472/// # Examples
473///
474/// ```
475/// # #![allow(deprecated)]
476/// use std::mem;
477///
478/// assert_eq!(4, mem::min_align_of_val(&5i32));
479/// ```
480#[inline]
481#[must_use]
482#[stable(feature = "rust1", since = "1.0.0")]
483#[deprecated(note = "use `align_of_val` instead", since = "1.2.0", suggestion = "align_of_val")]
484#[cfg(not(feature = "ferrocene_subset"))]
485pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
486 // SAFETY: val is a reference, so it's a valid raw pointer
487 unsafe { intrinsics::align_of_val(val) }
488}
489
490/// Returns the [ABI]-required minimum alignment of a type in bytes.
491///
492/// Every reference to a value of the type `T` must be a multiple of this number.
493///
494/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
495///
496/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
497///
498/// # Examples
499///
500/// ```
501/// assert_eq!(4, align_of::<i32>());
502/// ```
503#[inline(always)]
504#[must_use]
505#[stable(feature = "rust1", since = "1.0.0")]
506#[rustc_promotable]
507#[rustc_const_stable(feature = "const_align_of", since = "1.24.0")]
508#[rustc_diagnostic_item = "mem_align_of"]
509pub const fn align_of<T>() -> usize {
510 <T as SizedTypeProperties>::ALIGN
511}
512
513/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
514/// bytes.
515///
516/// Every reference to a value of the type `T` must be a multiple of this number.
517///
518/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
519///
520/// # Examples
521///
522/// ```
523/// assert_eq!(4, align_of_val(&5i32));
524/// ```
525#[inline]
526#[must_use]
527#[stable(feature = "rust1", since = "1.0.0")]
528#[rustc_const_stable(feature = "const_align_of_val", since = "1.85.0")]
529pub const fn align_of_val<T: ?Sized>(val: &T) -> usize {
530 // SAFETY: val is a reference, so it's a valid raw pointer
531 unsafe { intrinsics::align_of_val(val) }
532}
533
534/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
535/// bytes.
536///
537/// Every reference to a value of the type `T` must be a multiple of this number.
538///
539/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
540///
541/// # Safety
542///
543/// This function is only safe to call if the following conditions hold:
544///
545/// - If `T` is `Sized`, this function is always safe to call.
546/// - If the unsized tail of `T` is:
547/// - a [slice], then the length of the slice tail must be an initialized
548/// integer, and the size of the *entire value*
549/// (dynamic tail length + statically sized prefix) must fit in `isize`.
550/// For the special case where the dynamic tail length is 0, this function
551/// is safe to call.
552/// - a [trait object], then the vtable part of the pointer must point
553/// to a valid vtable acquired by an unsizing coercion, and the size
554/// of the *entire value* (dynamic tail length + statically sized prefix)
555/// must fit in `isize`.
556/// - an (unstable) [extern type], then this function is always safe to
557/// call, but may panic or otherwise return the wrong value, as the
558/// extern type's layout is not known. This is the same behavior as
559/// [`align_of_val`] on a reference to a type with an extern type tail.
560/// - otherwise, it is conservatively not allowed to call this function.
561///
562/// [trait object]: ../../book/ch17-02-trait-objects.html
563/// [extern type]: ../../unstable-book/language-features/extern-types.html
564///
565/// # Examples
566///
567/// ```
568/// #![feature(layout_for_ptr)]
569/// use std::mem;
570///
571/// assert_eq!(4, unsafe { mem::align_of_val_raw(&5i32) });
572/// ```
573#[inline]
574#[must_use]
575#[unstable(feature = "layout_for_ptr", issue = "69835")]
576#[cfg(not(feature = "ferrocene_subset"))]
577pub const unsafe fn align_of_val_raw<T: ?Sized>(val: *const T) -> usize {
578 // SAFETY: the caller must provide a valid raw pointer
579 unsafe { intrinsics::align_of_val(val) }
580}
581
582/// Returns `true` if dropping values of type `T` matters.
583///
584/// This is purely an optimization hint, and may be implemented conservatively:
585/// it may return `true` for types that don't actually need to be dropped.
586/// As such always returning `true` would be a valid implementation of
587/// this function. However if this function actually returns `false`, then you
588/// can be certain dropping `T` has no side effect.
589///
590/// Low level implementations of things like collections, which need to manually
591/// drop their data, should use this function to avoid unnecessarily
592/// trying to drop all their contents when they are destroyed. This might not
593/// make a difference in release builds (where a loop that has no side-effects
594/// is easily detected and eliminated), but is often a big win for debug builds.
595///
596/// Note that [`drop_in_place`] already performs this check, so if your workload
597/// can be reduced to some small number of [`drop_in_place`] calls, using this is
598/// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
599/// will do a single needs_drop check for all the values.
600///
601/// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
602/// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
603/// values one at a time and should use this API.
604///
605/// [`drop_in_place`]: crate::ptr::drop_in_place
606/// [`HashMap`]: ../../std/collections/struct.HashMap.html
607///
608/// # Examples
609///
610/// Here's an example of how a collection might make use of `needs_drop`:
611///
612/// ```
613/// use std::{mem, ptr};
614///
615/// pub struct MyCollection<T> {
616/// # data: [T; 1],
617/// /* ... */
618/// }
619/// # impl<T> MyCollection<T> {
620/// # fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
621/// # fn free_buffer(&mut self) {}
622/// # }
623///
624/// impl<T> Drop for MyCollection<T> {
625/// fn drop(&mut self) {
626/// unsafe {
627/// // drop the data
628/// if mem::needs_drop::<T>() {
629/// for x in self.iter_mut() {
630/// ptr::drop_in_place(x);
631/// }
632/// }
633/// self.free_buffer();
634/// }
635/// }
636/// }
637/// ```
638#[inline]
639#[must_use]
640#[stable(feature = "needs_drop", since = "1.21.0")]
641#[rustc_const_stable(feature = "const_mem_needs_drop", since = "1.36.0")]
642#[rustc_diagnostic_item = "needs_drop"]
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")]
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_subset"))]
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"]
768pub const fn swap<T>(x: &mut T, y: &mut T) {
769 // SAFETY: `&mut` guarantees these are typed readable and writable
770 // as well as non-overlapping.
771 unsafe { intrinsics::typed_swap_nonoverlapping(x, y) }
772}
773
774/// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
775///
776/// * If you want to replace the values of two variables, see [`swap`].
777/// * If you want to replace with a passed value instead of the default value, see [`replace`].
778///
779/// # Examples
780///
781/// A simple example:
782///
783/// ```
784/// use std::mem;
785///
786/// let mut v: Vec<i32> = vec![1, 2];
787///
788/// let old_v = mem::take(&mut v);
789/// assert_eq!(vec![1, 2], old_v);
790/// assert!(v.is_empty());
791/// ```
792///
793/// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
794/// Without `take` you can run into issues like these:
795///
796/// ```compile_fail,E0507
797/// struct Buffer<T> { buf: Vec<T> }
798///
799/// impl<T> Buffer<T> {
800/// fn get_and_reset(&mut self) -> Vec<T> {
801/// // error: cannot move out of dereference of `&mut`-pointer
802/// let buf = self.buf;
803/// self.buf = Vec::new();
804/// buf
805/// }
806/// }
807/// ```
808///
809/// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
810/// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
811/// `self`, allowing it to be returned:
812///
813/// ```
814/// use std::mem;
815///
816/// # struct Buffer<T> { buf: Vec<T> }
817/// impl<T> Buffer<T> {
818/// fn get_and_reset(&mut self) -> Vec<T> {
819/// mem::take(&mut self.buf)
820/// }
821/// }
822///
823/// let mut buffer = Buffer { buf: vec![0, 1] };
824/// assert_eq!(buffer.buf.len(), 2);
825///
826/// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
827/// assert_eq!(buffer.buf.len(), 0);
828/// ```
829#[inline]
830#[stable(feature = "mem_take", since = "1.40.0")]
831#[rustc_const_unstable(feature = "const_default", issue = "143894")]
832pub const fn take<T: [const] 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 effectively does nothing for types which implement `Copy`, e.g.
922/// integers. Such values are copied and _then_ moved into the function, so the
923/// value persists after this function call.
924///
925/// This function is not magic; it is literally defined as
926///
927/// ```
928/// pub fn drop<T>(_x: T) {}
929/// ```
930///
931/// Because `_x` is moved into the function, it is automatically [dropped][drop] before
932/// the function returns.
933///
934/// [drop]: Drop
935///
936/// # Examples
937///
938/// Basic usage:
939///
940/// ```
941/// let v = vec![1, 2, 3];
942///
943/// drop(v); // explicitly drop the vector
944/// ```
945///
946/// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
947/// release a [`RefCell`] borrow:
948///
949/// ```
950/// use std::cell::RefCell;
951///
952/// let x = RefCell::new(1);
953///
954/// let mut mutable_borrow = x.borrow_mut();
955/// *mutable_borrow = 1;
956///
957/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
958///
959/// let borrow = x.borrow();
960/// println!("{}", *borrow);
961/// ```
962///
963/// Integers and other types implementing [`Copy`] are unaffected by `drop`.
964///
965/// ```
966/// # #![allow(dropping_copy_types)]
967/// #[derive(Copy, Clone)]
968/// struct Foo(u8);
969///
970/// let x = 1;
971/// let y = Foo(2);
972/// drop(x); // a copy of `x` is moved and dropped
973/// drop(y); // a copy of `y` is moved and dropped
974///
975/// println!("x: {}, y: {}", x, y.0); // still available
976/// ```
977///
978/// [`RefCell`]: crate::cell::RefCell
979#[inline]
980#[stable(feature = "rust1", since = "1.0.0")]
981#[rustc_const_unstable(feature = "const_destruct", issue = "133214")]
982#[rustc_diagnostic_item = "mem_drop"]
983pub const fn drop<T>(_x: T)
984where
985 T: [const] Destruct,
986{
987}
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_subset"))]
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")]
1057pub const unsafe fn transmute_copy<Src, Dst>(src: &Src) -> Dst {
1058 assert!(
1059 size_of::<Src>() >= size_of::<Dst>(),
1060 "cannot transmute_copy if Dst is larger than Src"
1061 );
1062
1063 // If Dst has a higher alignment requirement, src might not be suitably aligned.
1064 if align_of::<Dst>() > align_of::<Src>() {
1065 // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
1066 // The caller must guarantee that the actual transmutation is safe.
1067 unsafe { ptr::read_unaligned(src as *const Src as *const Dst) }
1068 } else {
1069 // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
1070 // We just checked that `src as *const Dst` was properly aligned.
1071 // The caller must guarantee that the actual transmutation is safe.
1072 unsafe { ptr::read(src as *const Src as *const Dst) }
1073 }
1074}
1075
1076/// Opaque type representing the discriminant of an enum.
1077///
1078/// See the [`discriminant`] function in this module for more information.
1079#[stable(feature = "discriminant_value", since = "1.21.0")]
1080pub struct Discriminant<T>(<T as DiscriminantKind>::Discriminant);
1081
1082// N.B. These trait implementations cannot be derived because we don't want any bounds on T.
1083
1084#[stable(feature = "discriminant_value", since = "1.21.0")]
1085#[cfg(not(feature = "ferrocene_subset"))]
1086impl<T> Copy for Discriminant<T> {}
1087
1088#[stable(feature = "discriminant_value", since = "1.21.0")]
1089#[cfg(not(feature = "ferrocene_subset"))]
1090impl<T> clone::Clone for Discriminant<T> {
1091 fn clone(&self) -> Self {
1092 *self
1093 }
1094}
1095
1096#[cfg(not(feature = "ferrocene_subset"))]
1097#[doc(hidden)]
1098#[unstable(feature = "trivial_clone", issue = "none")]
1099unsafe impl<T> TrivialClone for Discriminant<T> {}
1100
1101#[stable(feature = "discriminant_value", since = "1.21.0")]
1102impl<T> cmp::PartialEq for Discriminant<T> {
1103 fn eq(&self, rhs: &Self) -> bool {
1104 self.0 == rhs.0
1105 }
1106}
1107
1108#[stable(feature = "discriminant_value", since = "1.21.0")]
1109#[cfg(not(feature = "ferrocene_subset"))]
1110impl<T> cmp::Eq for Discriminant<T> {}
1111
1112#[stable(feature = "discriminant_value", since = "1.21.0")]
1113#[cfg(not(feature = "ferrocene_subset"))]
1114impl<T> hash::Hash for Discriminant<T> {
1115 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1116 self.0.hash(state);
1117 }
1118}
1119
1120#[stable(feature = "discriminant_value", since = "1.21.0")]
1121#[cfg(not(feature = "ferrocene_subset"))]
1122impl<T> fmt::Debug for Discriminant<T> {
1123 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1124 fmt.debug_tuple("Discriminant").field(&self.0).finish()
1125 }
1126}
1127
1128/// Returns a value uniquely identifying the enum variant in `v`.
1129///
1130/// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1131/// return value is unspecified.
1132///
1133/// # Stability
1134///
1135/// The discriminant of an enum variant may change if the enum definition changes. A discriminant
1136/// of some variant will not change between compilations with the same compiler. See the [Reference]
1137/// for more information.
1138///
1139/// [Reference]: ../../reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
1140///
1141/// The value of a [`Discriminant<T>`] is independent of any *free lifetimes* in `T`. As such,
1142/// reading or writing a `Discriminant<Foo<'a>>` as a `Discriminant<Foo<'b>>` (whether via
1143/// [`transmute`] or otherwise) is always sound. Note that this is **not** true for other kinds
1144/// of generic parameters and for higher-ranked lifetimes; `Discriminant<Foo<A>>` and
1145/// `Discriminant<Foo<B>>` as well as `Discriminant<Bar<dyn for<'a> Trait<'a>>>` and
1146/// `Discriminant<Bar<dyn Trait<'static>>>` may be incompatible.
1147///
1148/// # Examples
1149///
1150/// This can be used to compare enums that carry data, while disregarding
1151/// the actual data:
1152///
1153/// ```
1154/// use std::mem;
1155///
1156/// enum Foo { A(&'static str), B(i32), C(i32) }
1157///
1158/// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
1159/// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
1160/// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
1161/// ```
1162///
1163/// ## Accessing the numeric value of the discriminant
1164///
1165/// Note that it is *undefined behavior* to [`transmute`] from [`Discriminant`] to a primitive!
1166///
1167/// If an enum has only unit variants, then the numeric value of the discriminant can be accessed
1168/// with an [`as`] cast:
1169///
1170/// ```
1171/// enum Enum {
1172/// Foo,
1173/// Bar,
1174/// Baz,
1175/// }
1176///
1177/// assert_eq!(0, Enum::Foo as isize);
1178/// assert_eq!(1, Enum::Bar as isize);
1179/// assert_eq!(2, Enum::Baz as isize);
1180/// ```
1181///
1182/// If an enum has opted-in to having a [primitive representation] for its discriminant,
1183/// then it's possible to use pointers to read the memory location storing the discriminant.
1184/// That **cannot** be done for enums using the [default representation], however, as it's
1185/// undefined what layout the discriminant has and where it's stored — it might not even be
1186/// stored at all!
1187///
1188/// [`as`]: ../../std/keyword.as.html
1189/// [primitive representation]: ../../reference/type-layout.html#primitive-representations
1190/// [default representation]: ../../reference/type-layout.html#the-default-representation
1191/// ```
1192/// #[repr(u8)]
1193/// enum Enum {
1194/// Unit,
1195/// Tuple(bool),
1196/// Struct { a: bool },
1197/// }
1198///
1199/// impl Enum {
1200/// fn discriminant(&self) -> u8 {
1201/// // SAFETY: Because `Self` is marked `repr(u8)`, its layout is a `repr(C)` `union`
1202/// // between `repr(C)` structs, each of which has the `u8` discriminant as its first
1203/// // field, so we can read the discriminant without offsetting the pointer.
1204/// unsafe { *<*const _>::from(self).cast::<u8>() }
1205/// }
1206/// }
1207///
1208/// let unit_like = Enum::Unit;
1209/// let tuple_like = Enum::Tuple(true);
1210/// let struct_like = Enum::Struct { a: false };
1211/// assert_eq!(0, unit_like.discriminant());
1212/// assert_eq!(1, tuple_like.discriminant());
1213/// assert_eq!(2, struct_like.discriminant());
1214///
1215/// // ⚠️ This is undefined behavior. Don't do this. ⚠️
1216/// // assert_eq!(0, unsafe { std::mem::transmute::<_, u8>(std::mem::discriminant(&unit_like)) });
1217/// ```
1218#[stable(feature = "discriminant_value", since = "1.21.0")]
1219#[rustc_const_stable(feature = "const_discriminant", since = "1.75.0")]
1220#[rustc_diagnostic_item = "mem_discriminant"]
1221#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1222pub const fn discriminant<T>(v: &T) -> Discriminant<T> {
1223 Discriminant(intrinsics::discriminant_value(v))
1224}
1225
1226/// Returns the number of variants in the enum type `T`.
1227///
1228/// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1229/// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX`
1230/// the return value is unspecified. Uninhabited variants will be counted.
1231///
1232/// Note that an enum may be expanded with additional variants in the future
1233/// as a non-breaking change, for example if it is marked `#[non_exhaustive]`,
1234/// which will change the result of this function.
1235///
1236/// # Examples
1237///
1238/// ```
1239/// # #![feature(never_type)]
1240/// # #![feature(variant_count)]
1241///
1242/// use std::mem;
1243///
1244/// enum Void {}
1245/// enum Foo { A(&'static str), B(i32), C(i32) }
1246///
1247/// assert_eq!(mem::variant_count::<Void>(), 0);
1248/// assert_eq!(mem::variant_count::<Foo>(), 3);
1249///
1250/// assert_eq!(mem::variant_count::<Option<!>>(), 2);
1251/// assert_eq!(mem::variant_count::<Result<!, !>>(), 2);
1252/// ```
1253#[inline(always)]
1254#[must_use]
1255#[unstable(feature = "variant_count", issue = "73662")]
1256#[rustc_const_unstable(feature = "variant_count", issue = "73662")]
1257#[rustc_diagnostic_item = "mem_variant_count"]
1258#[cfg(not(feature = "ferrocene_subset"))]
1259pub const fn variant_count<T>() -> usize {
1260 const { intrinsics::variant_count::<T>() }
1261}
1262
1263/// Provides associated constants for various useful properties of types,
1264/// to give them a canonical form in our code and make them easier to read.
1265///
1266/// This is here only to simplify all the ZST checks we need in the library.
1267/// It's not on a stabilization track right now.
1268#[doc(hidden)]
1269#[unstable(feature = "sized_type_properties", issue = "none")]
1270pub trait SizedTypeProperties: Sized {
1271 #[doc(hidden)]
1272 #[unstable(feature = "sized_type_properties", issue = "none")]
1273 #[lang = "mem_size_const"]
1274 const SIZE: usize = intrinsics::size_of::<Self>();
1275
1276 #[doc(hidden)]
1277 #[unstable(feature = "sized_type_properties", issue = "none")]
1278 #[lang = "mem_align_const"]
1279 const ALIGN: usize = intrinsics::align_of::<Self>();
1280
1281 /// `true` if this type requires no storage.
1282 /// `false` if its [size](size_of) is greater than zero.
1283 ///
1284 /// # Examples
1285 ///
1286 /// ```
1287 /// #![feature(sized_type_properties)]
1288 /// use core::mem::SizedTypeProperties;
1289 ///
1290 /// fn do_something_with<T>() {
1291 /// if T::IS_ZST {
1292 /// // ... special approach ...
1293 /// } else {
1294 /// // ... the normal thing ...
1295 /// }
1296 /// }
1297 ///
1298 /// struct MyUnit;
1299 /// assert!(MyUnit::IS_ZST);
1300 ///
1301 /// // For negative checks, consider using UFCS to emphasize the negation
1302 /// assert!(!<i32>::IS_ZST);
1303 /// // As it can sometimes hide in the type otherwise
1304 /// assert!(!String::IS_ZST);
1305 /// ```
1306 #[doc(hidden)]
1307 #[unstable(feature = "sized_type_properties", issue = "none")]
1308 const IS_ZST: bool = Self::SIZE == 0;
1309
1310 #[doc(hidden)]
1311 #[unstable(feature = "sized_type_properties", issue = "none")]
1312 const LAYOUT: Layout = {
1313 // SAFETY: if the type is instantiated, rustc already ensures that its
1314 // layout is valid. Use the unchecked constructor to avoid inserting a
1315 // panicking codepath that needs to be optimized out.
1316 unsafe { Layout::from_size_align_unchecked(Self::SIZE, Self::ALIGN) }
1317 };
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, core_intrinsics)]
1459pub macro offset_of($Container:ty, $($fields:expr)+ $(,)?) {
1460 // The `{}` is for better error messages
1461 const {builtin # offset_of($Container, $($fields)+)}
1462}
1463
1464/// Create a fresh instance of the inhabited ZST type `T`.
1465///
1466/// Prefer this to [`zeroed`] or [`uninitialized`] or [`transmute_copy`]
1467/// in places where you know that `T` is zero-sized, but don't have a bound
1468/// (such as [`Default`]) that would allow you to instantiate it using safe code.
1469///
1470/// If you're not sure whether `T` is an inhabited ZST, then you should be
1471/// using [`MaybeUninit`], not this function.
1472///
1473/// # Panics
1474///
1475/// If `size_of::<T>() != 0`.
1476///
1477/// # Safety
1478///
1479/// - `T` must be *[inhabited]*, i.e. possible to construct. This means that types
1480/// like zero-variant enums and [`!`] are unsound to conjure.
1481/// - You must use the value only in ways which do not violate any *safety*
1482/// invariants of the type.
1483///
1484/// While it's easy to create a *valid* instance of an inhabited ZST, since having
1485/// no bits in its representation means there's only one possible value, that
1486/// doesn't mean that it's always *sound* to do so.
1487///
1488/// For example, a library could design zero-sized tokens that are `!Default + !Clone`, limiting
1489/// their creation to functions that initialize some state or establish a scope. Conjuring such a
1490/// token could break invariants and lead to unsoundness.
1491///
1492/// # Examples
1493///
1494/// ```
1495/// #![feature(mem_conjure_zst)]
1496/// use std::mem::conjure_zst;
1497///
1498/// assert_eq!(unsafe { conjure_zst::<()>() }, ());
1499/// assert_eq!(unsafe { conjure_zst::<[i32; 0]>() }, []);
1500/// ```
1501///
1502/// [inhabited]: https://doc.rust-lang.org/reference/glossary.html#inhabited
1503#[unstable(feature = "mem_conjure_zst", issue = "95383")]
1504pub const unsafe fn conjure_zst<T>() -> T {
1505 #[ferrocene::annotation(
1506 "This assertion only runs in compilation, meaning that it cannot be covered in runtime"
1507 )]
1508 {
1509 const_assert!(
1510 size_of::<T>() == 0,
1511 "mem::conjure_zst invoked on a nonzero-sized type",
1512 "mem::conjure_zst invoked on type {t}, which is not zero-sized",
1513 t: &str = stringify!(T)
1514 );
1515 }
1516
1517 // SAFETY: because the caller must guarantee that it's inhabited and zero-sized,
1518 // there's nothing in the representation that needs to be set.
1519 // `assume_init` calls `assert_inhabited`, so we don't need to here.
1520 unsafe {
1521 #[allow(clippy::uninit_assumed_init)]
1522 MaybeUninit::uninit().assume_init()
1523 }
1524}