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