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