1 //! Basic functions for dealing with memory.
3 //! This module contains functions for querying the size and alignment of
4 //! types, initializing and manipulating memory.
6 #![stable(feature = "rust1", since = "1.0.0")]
12 use crate::intrinsics;
13 use crate::marker::{Copy, DiscriminantKind, Sized};
17 #[stable(feature = "manually_drop", since = "1.20.0")]
18 pub use manually_drop::ManuallyDrop;
21 #[stable(feature = "maybe_uninit", since = "1.36.0")]
22 pub use maybe_uninit::MaybeUninit;
24 #[stable(feature = "rust1", since = "1.0.0")]
26 pub use crate::intrinsics::transmute;
28 /// Takes ownership and "forgets" about the value **without running its destructor**.
30 /// Any resources the value manages, such as heap memory or a file handle, will linger
31 /// forever in an unreachable state. However, it does not guarantee that pointers
32 /// to this memory will remain valid.
34 /// * If you want to leak memory, see [`Box::leak`].
35 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`].
36 /// * If you want to dispose of a value properly, running its destructor, see
41 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
42 /// do not include a guarantee that destructors will always run. For example,
43 /// a program can create a reference cycle using [`Rc`][rc], or call
44 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
45 /// `mem::forget` from safe code does not fundamentally change Rust's safety
48 /// That said, leaking resources such as memory or I/O objects is usually undesirable.
49 /// The need comes up in some specialized use cases for FFI or unsafe code, but even
50 /// then, [`ManuallyDrop`] is typically preferred.
52 /// Because forgetting a value is allowed, any `unsafe` code you write must
53 /// allow for this possibility. You cannot return a value and expect that the
54 /// caller will necessarily run the value's destructor.
56 /// [rc]: ../../std/rc/struct.Rc.html
57 /// [exit]: ../../std/process/fn.exit.html
61 /// The canonical safe use of `mem::forget` is to circumvent a value's destructor
62 /// implemented by the `Drop` trait. For example, this will leak a `File`, i.e. reclaim
63 /// the space taken by the variable but never close the underlying system resource:
67 /// use std::fs::File;
69 /// let file = File::open("foo.txt").unwrap();
70 /// mem::forget(file);
73 /// This is useful when the ownership of the underlying resource was previously
74 /// transferred to code outside of Rust, for example by transmitting the raw
75 /// file descriptor to C code.
77 /// # Relationship with `ManuallyDrop`
79 /// While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone.
80 /// [`ManuallyDrop`] should be used instead. Consider, for example, this code:
85 /// let mut v = vec![65, 122];
86 /// // Build a `String` using the contents of `v`
87 /// let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) };
88 /// // leak `v` because its memory is now managed by `s`
89 /// mem::forget(v); // ERROR - v is invalid and must not be passed to a function
90 /// assert_eq!(s, "Az");
91 /// // `s` is implicitly dropped and its memory deallocated.
94 /// There are two issues with the above example:
96 /// * If more code were added between the construction of `String` and the invocation of
97 /// `mem::forget()`, a panic within it would cause a double free because the same memory
98 /// is handled by both `v` and `s`.
99 /// * After calling `v.as_mut_ptr()` and transmitting the ownership of the data to `s`,
100 /// the `v` value is invalid. Even when a value is just moved to `mem::forget` (which won't
101 /// inspect it), some types have strict requirements on their values that
102 /// make them invalid when dangling or no longer owned. Using invalid values in any
103 /// way, including passing them to or returning them from functions, constitutes
104 /// undefined behavior and may break the assumptions made by the compiler.
106 /// Switching to `ManuallyDrop` avoids both issues:
109 /// use std::mem::ManuallyDrop;
111 /// let v = vec![65, 122];
112 /// // Before we disassemble `v` into its raw parts, make sure it
113 /// // does not get dropped!
114 /// let mut v = ManuallyDrop::new(v);
115 /// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak.
116 /// let (ptr, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity());
117 /// // Finally, build a `String`.
118 /// let s = unsafe { String::from_raw_parts(ptr, len, cap) };
119 /// assert_eq!(s, "Az");
120 /// // `s` is implicitly dropped and its memory deallocated.
123 /// `ManuallyDrop` robustly prevents double-free because we disable `v`'s destructor
124 /// before doing anything else. `mem::forget()` doesn't allow this because it consumes its
125 /// argument, forcing us to call it only after extracting anything we need from `v`. Even
126 /// if a panic were introduced between construction of `ManuallyDrop` and building the
127 /// string (which cannot happen in the code as shown), it would result in a leak and not a
128 /// double free. In other words, `ManuallyDrop` errs on the side of leaking instead of
129 /// erring on the side of (double-)dropping.
131 /// Also, `ManuallyDrop` prevents us from having to "touch" `v` after transferring the
132 /// ownership to `s` — the final step of interacting with `v` to dispose of it without
133 /// running its destructor is entirely avoided.
135 /// [`Box`]: ../../std/boxed/struct.Box.html
136 /// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak
137 /// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw
138 /// [`mem::drop`]: drop
139 /// [ub]: ../../reference/behavior-considered-undefined.html
141 #[rustc_const_stable(feature = "const_forget", since = "1.46.0")]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_forget")]
144 pub const fn forget<T>(t: T) {
145 let _ = ManuallyDrop::new(t);
148 /// Like [`forget`], but also accepts unsized values.
150 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
153 #[unstable(feature = "forget_unsized", issue = "none")]
154 pub fn forget_unsized<T: ?Sized>(t: T) {
155 intrinsics::forget(t)
158 /// Returns the size of a type in bytes.
160 /// More specifically, this is the offset in bytes between successive elements
161 /// in an array with that item type including alignment padding. Thus, for any
162 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
164 /// In general, the size of a type is not stable across compilations, but
165 /// specific types such as primitives are.
167 /// The following table gives the size for primitives.
169 /// Type | size_of::\<Type>()
170 /// ---- | ---------------
187 /// Furthermore, `usize` and `isize` have the same size.
189 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
190 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
192 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
193 /// have the same size. Likewise for `*const T` and `*mut T`.
195 /// # Size of `#[repr(C)]` items
197 /// The `C` representation for items has a defined layout. With this layout,
198 /// the size of items is also stable as long as all fields have a stable size.
200 /// ## Size of Structs
202 /// For `structs`, the size is determined by the following algorithm.
204 /// For each field in the struct ordered by declaration order:
206 /// 1. Add the size of the field.
207 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
209 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
210 /// The alignment of the struct is usually the largest alignment of all its
211 /// fields; this can be changed with the use of `repr(align(N))`.
213 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
217 /// Enums that carry no data other than the discriminant have the same size as C enums
218 /// on the platform they are compiled for.
220 /// ## Size of Unions
222 /// The size of a union is the size of its largest field.
224 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
231 /// // Some primitives
232 /// assert_eq!(4, mem::size_of::<i32>());
233 /// assert_eq!(8, mem::size_of::<f64>());
234 /// assert_eq!(0, mem::size_of::<()>());
237 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
238 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
239 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
242 /// // Pointer size equality
243 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
244 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
245 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
246 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
249 /// Using `#[repr(C)]`.
255 /// struct FieldStruct {
261 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
262 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
263 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
264 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
265 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
266 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
267 /// // fields is 2), so add 1 to the size for padding. Size is 6.
268 /// assert_eq!(6, mem::size_of::<FieldStruct>());
271 /// struct TupleStruct(u8, u16, u8);
273 /// // Tuple structs follow the same rules.
274 /// assert_eq!(6, mem::size_of::<TupleStruct>());
276 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
277 /// // by putting `third` before `second`.
279 /// struct FieldStructOptimized {
285 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
287 /// // Union size is the size of the largest field.
289 /// union ExampleUnion {
294 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
297 /// [alignment]: align_of
299 #[stable(feature = "rust1", since = "1.0.0")]
301 #[rustc_const_stable(feature = "const_size_of", since = "1.24.0")]
302 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of")]
303 pub const fn size_of<T>() -> usize {
304 intrinsics::size_of::<T>()
307 /// Returns the size of the pointed-to value in bytes.
309 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
310 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
311 /// then `size_of_val` can be used to get the dynamically-known size.
313 /// [trait object]: ../../book/ch17-02-trait-objects.html
320 /// assert_eq!(4, mem::size_of_val(&5i32));
322 /// let x: [u8; 13] = [0; 13];
323 /// let y: &[u8] = &x;
324 /// assert_eq!(13, mem::size_of_val(y));
327 #[stable(feature = "rust1", since = "1.0.0")]
328 #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")]
329 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")]
330 pub const fn size_of_val<T: ?Sized>(val: &T) -> usize {
331 // SAFETY: `val` is a reference, so it's a valid raw pointer
332 unsafe { intrinsics::size_of_val(val) }
335 /// Returns the size of the pointed-to value in bytes.
337 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
338 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
339 /// then `size_of_val_raw` can be used to get the dynamically-known size.
343 /// This function is only safe to call if the following conditions hold:
345 /// - If `T` is `Sized`, this function is always safe to call.
346 /// - If the unsized tail of `T` is:
347 /// - a [slice], then the length of the slice tail must be an initialized
348 /// integer, and the size of the *entire value*
349 /// (dynamic tail length + statically sized prefix) must fit in `isize`.
350 /// - a [trait object], then the vtable part of the pointer must point
351 /// to a valid vtable acquired by an unsizing coercion, and the size
352 /// of the *entire value* (dynamic tail length + statically sized prefix)
353 /// must fit in `isize`.
354 /// - an (unstable) [extern type], then this function is always safe to
355 /// call, but may panic or otherwise return the wrong value, as the
356 /// extern type's layout is not known. This is the same behavior as
357 /// [`size_of_val`] on a reference to a type with an extern type tail.
358 /// - otherwise, it is conservatively not allowed to call this function.
360 /// [trait object]: ../../book/ch17-02-trait-objects.html
361 /// [extern type]: ../../unstable-book/language-features/extern-types.html
366 /// #![feature(layout_for_ptr)]
369 /// assert_eq!(4, mem::size_of_val(&5i32));
371 /// let x: [u8; 13] = [0; 13];
372 /// let y: &[u8] = &x;
373 /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) });
376 #[unstable(feature = "layout_for_ptr", issue = "69835")]
377 #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")]
378 pub const unsafe fn size_of_val_raw<T: ?Sized>(val: *const T) -> usize {
379 // SAFETY: the caller must provide a valid raw pointer
380 unsafe { intrinsics::size_of_val(val) }
383 /// Returns the [ABI]-required minimum alignment of a type.
385 /// Every reference to a value of the type `T` must be a multiple of this number.
387 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
389 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
394 /// # #![allow(deprecated)]
397 /// assert_eq!(4, mem::min_align_of::<i32>());
400 #[stable(feature = "rust1", since = "1.0.0")]
401 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
402 pub fn min_align_of<T>() -> usize {
403 intrinsics::min_align_of::<T>()
406 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
408 /// Every reference to a value of the type `T` must be a multiple of this number.
410 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
415 /// # #![allow(deprecated)]
418 /// assert_eq!(4, mem::min_align_of_val(&5i32));
421 #[stable(feature = "rust1", since = "1.0.0")]
422 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
423 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
424 // SAFETY: val is a reference, so it's a valid raw pointer
425 unsafe { intrinsics::min_align_of_val(val) }
428 /// Returns the [ABI]-required minimum alignment of a type.
430 /// Every reference to a value of the type `T` must be a multiple of this number.
432 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
434 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
441 /// assert_eq!(4, mem::align_of::<i32>());
444 #[stable(feature = "rust1", since = "1.0.0")]
446 #[rustc_const_stable(feature = "const_align_of", since = "1.24.0")]
447 pub const fn align_of<T>() -> usize {
448 intrinsics::min_align_of::<T>()
451 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
453 /// Every reference to a value of the type `T` must be a multiple of this number.
455 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
462 /// assert_eq!(4, mem::align_of_val(&5i32));
465 #[stable(feature = "rust1", since = "1.0.0")]
466 #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")]
468 pub const fn align_of_val<T: ?Sized>(val: &T) -> usize {
469 // SAFETY: val is a reference, so it's a valid raw pointer
470 unsafe { intrinsics::min_align_of_val(val) }
473 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
475 /// Every reference to a value of the type `T` must be a multiple of this number.
477 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
481 /// This function is only safe to call if the following conditions hold:
483 /// - If `T` is `Sized`, this function is always safe to call.
484 /// - If the unsized tail of `T` is:
485 /// - a [slice], then the length of the slice tail must be an initialized
486 /// integer, and the size of the *entire value*
487 /// (dynamic tail length + statically sized prefix) must fit in `isize`.
488 /// - a [trait object], then the vtable part of the pointer must point
489 /// to a valid vtable acquired by an unsizing coercion, and the size
490 /// of the *entire value* (dynamic tail length + statically sized prefix)
491 /// must fit in `isize`.
492 /// - an (unstable) [extern type], then this function is always safe to
493 /// call, but may panic or otherwise return the wrong value, as the
494 /// extern type's layout is not known. This is the same behavior as
495 /// [`align_of_val`] on a reference to a type with an extern type tail.
496 /// - otherwise, it is conservatively not allowed to call this function.
498 /// [trait object]: ../../book/ch17-02-trait-objects.html
499 /// [extern type]: ../../unstable-book/language-features/extern-types.html
504 /// #![feature(layout_for_ptr)]
507 /// assert_eq!(4, unsafe { mem::align_of_val_raw(&5i32) });
510 #[unstable(feature = "layout_for_ptr", issue = "69835")]
511 #[rustc_const_unstable(feature = "const_align_of_val_raw", issue = "46571")]
512 pub const unsafe fn align_of_val_raw<T: ?Sized>(val: *const T) -> usize {
513 // SAFETY: the caller must provide a valid raw pointer
514 unsafe { intrinsics::min_align_of_val(val) }
517 /// Returns `true` if dropping values of type `T` matters.
519 /// This is purely an optimization hint, and may be implemented conservatively:
520 /// it may return `true` for types that don't actually need to be dropped.
521 /// As such always returning `true` would be a valid implementation of
522 /// this function. However if this function actually returns `false`, then you
523 /// can be certain dropping `T` has no side effect.
525 /// Low level implementations of things like collections, which need to manually
526 /// drop their data, should use this function to avoid unnecessarily
527 /// trying to drop all their contents when they are destroyed. This might not
528 /// make a difference in release builds (where a loop that has no side-effects
529 /// is easily detected and eliminated), but is often a big win for debug builds.
531 /// Note that [`drop_in_place`] already performs this check, so if your workload
532 /// can be reduced to some small number of [`drop_in_place`] calls, using this is
533 /// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
534 /// will do a single needs_drop check for all the values.
536 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
537 /// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
538 /// values one at a time and should use this API.
540 /// [`drop_in_place`]: crate::ptr::drop_in_place
541 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
545 /// Here's an example of how a collection might make use of `needs_drop`:
548 /// use std::{mem, ptr};
550 /// pub struct MyCollection<T> {
554 /// # impl<T> MyCollection<T> {
555 /// # fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
556 /// # fn free_buffer(&mut self) {}
559 /// impl<T> Drop for MyCollection<T> {
560 /// fn drop(&mut self) {
563 /// if mem::needs_drop::<T>() {
564 /// for x in self.iter_mut() {
565 /// ptr::drop_in_place(x);
568 /// self.free_buffer();
574 #[stable(feature = "needs_drop", since = "1.21.0")]
575 #[rustc_const_stable(feature = "const_needs_drop", since = "1.36.0")]
576 #[rustc_diagnostic_item = "needs_drop"]
577 pub const fn needs_drop<T>() -> bool {
578 intrinsics::needs_drop::<T>()
581 /// Returns the value of type `T` represented by the all-zero byte-pattern.
583 /// This means that, for example, the padding byte in `(u8, u16)` is not
584 /// necessarily zeroed.
586 /// There is no guarantee that an all-zero byte-pattern represents a valid value
587 /// of some type `T`. For example, the all-zero byte-pattern is not a valid value
588 /// for reference types (`&T`, `&mut T`) and functions pointers. Using `zeroed`
589 /// on such types causes immediate [undefined behavior][ub] because [the Rust
590 /// compiler assumes][inv] that there always is a valid value in a variable it
591 /// considers initialized.
593 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
594 /// It is useful for FFI sometimes, but should generally be avoided.
596 /// [zeroed]: MaybeUninit::zeroed
597 /// [ub]: ../../reference/behavior-considered-undefined.html
598 /// [inv]: MaybeUninit#initialization-invariant
602 /// Correct usage of this function: initializing an integer with zero.
607 /// let x: i32 = unsafe { mem::zeroed() };
608 /// assert_eq!(0, x);
611 /// *Incorrect* usage of this function: initializing a reference with zero.
614 /// # #![allow(invalid_value)]
617 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
618 /// let _y: fn() = unsafe { mem::zeroed() }; // And again!
621 #[stable(feature = "rust1", since = "1.0.0")]
622 #[allow(deprecated_in_future)]
624 #[rustc_diagnostic_item = "mem_zeroed"]
625 pub unsafe fn zeroed<T>() -> T {
626 // SAFETY: the caller must guarantee that an all-zero value is valid for `T`.
628 intrinsics::assert_zero_valid::<T>();
629 MaybeUninit::zeroed().assume_init()
633 /// Bypasses Rust's normal memory-initialization checks by pretending to
634 /// produce a value of type `T`, while doing nothing at all.
636 /// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
638 /// The reason for deprecation is that the function basically cannot be used
639 /// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
640 /// As the [`assume_init` documentation][assume_init] explains,
641 /// [the Rust compiler assumes][inv] that values are properly initialized.
642 /// As a consequence, calling e.g. `mem::uninitialized::<bool>()` causes immediate
643 /// undefined behavior for returning a `bool` that is not definitely either `true`
644 /// or `false`. Worse, truly uninitialized memory like what gets returned here
645 /// is special in that the compiler knows that it does not have a fixed value.
646 /// This makes it undefined behavior to have uninitialized data in a variable even
647 /// if that variable has an integer type.
648 /// (Notice that the rules around uninitialized integers are not finalized yet, but
649 /// until they are, it is advisable to avoid them.)
651 /// [uninit]: MaybeUninit::uninit
652 /// [assume_init]: MaybeUninit::assume_init
653 /// [inv]: MaybeUninit#initialization-invariant
655 #[rustc_deprecated(since = "1.39.0", reason = "use `mem::MaybeUninit` instead")]
656 #[stable(feature = "rust1", since = "1.0.0")]
657 #[allow(deprecated_in_future)]
659 #[rustc_diagnostic_item = "mem_uninitialized"]
660 pub unsafe fn uninitialized<T>() -> T {
661 // SAFETY: the caller must guarantee that an unitialized value is valid for `T`.
663 intrinsics::assert_uninit_valid::<T>();
664 MaybeUninit::uninit().assume_init()
668 /// Swaps the values at two mutable locations, without deinitializing either one.
670 /// * If you want to swap with a default or dummy value, see [`take`].
671 /// * If you want to swap with a passed value, returning the old value, see [`replace`].
681 /// mem::swap(&mut x, &mut y);
683 /// assert_eq!(42, x);
684 /// assert_eq!(5, y);
687 #[stable(feature = "rust1", since = "1.0.0")]
688 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
689 pub const fn swap<T>(x: &mut T, y: &mut T) {
690 // SAFETY: the raw pointers have been created from safe mutable references satisfying all the
691 // constraints on `ptr::swap_nonoverlapping_one`
693 ptr::swap_nonoverlapping_one(x, y);
697 /// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
699 /// * If you want to replace the values of two variables, see [`swap`].
700 /// * If you want to replace with a passed value instead of the default value, see [`replace`].
704 /// A simple example:
709 /// let mut v: Vec<i32> = vec![1, 2];
711 /// let old_v = mem::take(&mut v);
712 /// assert_eq!(vec![1, 2], old_v);
713 /// assert!(v.is_empty());
716 /// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
717 /// Without `take` you can run into issues like these:
719 /// ```compile_fail,E0507
720 /// struct Buffer<T> { buf: Vec<T> }
722 /// impl<T> Buffer<T> {
723 /// fn get_and_reset(&mut self) -> Vec<T> {
724 /// // error: cannot move out of dereference of `&mut`-pointer
725 /// let buf = self.buf;
726 /// self.buf = Vec::new();
732 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
733 /// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
734 /// `self`, allowing it to be returned:
739 /// # struct Buffer<T> { buf: Vec<T> }
740 /// impl<T> Buffer<T> {
741 /// fn get_and_reset(&mut self) -> Vec<T> {
742 /// mem::take(&mut self.buf)
746 /// let mut buffer = Buffer { buf: vec![0, 1] };
747 /// assert_eq!(buffer.buf.len(), 2);
749 /// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
750 /// assert_eq!(buffer.buf.len(), 0);
753 #[stable(feature = "mem_take", since = "1.40.0")]
754 pub fn take<T: Default>(dest: &mut T) -> T {
755 replace(dest, T::default())
758 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
760 /// Neither value is dropped.
762 /// * If you want to replace the values of two variables, see [`swap`].
763 /// * If you want to replace with a default value, see [`take`].
767 /// A simple example:
772 /// let mut v: Vec<i32> = vec![1, 2];
774 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
775 /// assert_eq!(vec![1, 2], old_v);
776 /// assert_eq!(vec![3, 4, 5], v);
779 /// `replace` allows consumption of a struct field by replacing it with another value.
780 /// Without `replace` you can run into issues like these:
782 /// ```compile_fail,E0507
783 /// struct Buffer<T> { buf: Vec<T> }
785 /// impl<T> Buffer<T> {
786 /// fn replace_index(&mut self, i: usize, v: T) -> T {
787 /// // error: cannot move out of dereference of `&mut`-pointer
788 /// let t = self.buf[i];
795 /// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
796 /// avoid the move. But `replace` can be used to disassociate the original value at that index from
797 /// `self`, allowing it to be returned:
800 /// # #![allow(dead_code)]
803 /// # struct Buffer<T> { buf: Vec<T> }
804 /// impl<T> Buffer<T> {
805 /// fn replace_index(&mut self, i: usize, v: T) -> T {
806 /// mem::replace(&mut self.buf[i], v)
810 /// let mut buffer = Buffer { buf: vec![0, 1] };
811 /// assert_eq!(buffer.buf[0], 0);
813 /// assert_eq!(buffer.replace_index(0, 2), 0);
814 /// assert_eq!(buffer.buf[0], 2);
817 #[stable(feature = "rust1", since = "1.0.0")]
818 #[must_use = "if you don't need the old value, you can just assign the new value directly"]
819 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
820 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")]
821 pub const fn replace<T>(dest: &mut T, src: T) -> T {
822 // SAFETY: We read from `dest` but directly write `src` into it afterwards,
823 // such that the old value is not duplicated. Nothing is dropped and
824 // nothing here can panic.
826 let result = ptr::read(dest);
827 ptr::write(dest, src);
832 /// Disposes of a value.
834 /// This does so by calling the argument's implementation of [`Drop`][drop].
836 /// This effectively does nothing for types which implement `Copy`, e.g.
837 /// integers. Such values are copied and _then_ moved into the function, so the
838 /// value persists after this function call.
840 /// This function is not magic; it is literally defined as
843 /// pub fn drop<T>(_x: T) { }
846 /// Because `_x` is moved into the function, it is automatically dropped before
847 /// the function returns.
856 /// let v = vec![1, 2, 3];
858 /// drop(v); // explicitly drop the vector
861 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
862 /// release a [`RefCell`] borrow:
865 /// use std::cell::RefCell;
867 /// let x = RefCell::new(1);
869 /// let mut mutable_borrow = x.borrow_mut();
870 /// *mutable_borrow = 1;
872 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
874 /// let borrow = x.borrow();
875 /// println!("{}", *borrow);
878 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
881 /// #[derive(Copy, Clone)]
886 /// drop(x); // a copy of `x` is moved and dropped
887 /// drop(y); // a copy of `y` is moved and dropped
889 /// println!("x: {}, y: {}", x, y.0); // still available
892 /// [`RefCell`]: crate::cell::RefCell
894 #[stable(feature = "rust1", since = "1.0.0")]
895 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")]
896 pub fn drop<T>(_x: T) {}
898 /// Interprets `src` as having type `&U`, and then reads `src` without moving
899 /// the contained value.
901 /// This function will unsafely assume the pointer `src` is valid for [`size_of::<U>`][size_of]
902 /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way
903 /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also
904 /// unsafely create a copy of the contained value instead of moving out of `src`.
906 /// It is not a compile-time error if `T` and `U` have different sizes, but it
907 /// is highly encouraged to only invoke this function where `T` and `U` have the
908 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
911 /// [ub]: ../../reference/behavior-considered-undefined.html
923 /// let foo_array = [10u8];
926 /// // Copy the data from 'foo_array' and treat it as a 'Foo'
927 /// let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
928 /// assert_eq!(foo_struct.bar, 10);
930 /// // Modify the copied data
931 /// foo_struct.bar = 20;
932 /// assert_eq!(foo_struct.bar, 20);
935 /// // The contents of 'foo_array' should not have changed
936 /// assert_eq!(foo_array, [10]);
939 #[stable(feature = "rust1", since = "1.0.0")]
940 #[rustc_const_unstable(feature = "const_transmute_copy", issue = "83165")]
941 pub const unsafe fn transmute_copy<T, U>(src: &T) -> U {
942 // If U has a higher alignment requirement, src may not be suitably aligned.
943 if align_of::<U>() > align_of::<T>() {
944 // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
945 // The caller must guarantee that the actual transmutation is safe.
946 unsafe { ptr::read_unaligned(src as *const T as *const U) }
948 // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
949 // We just checked that `src as *const U` was properly aligned.
950 // The caller must guarantee that the actual transmutation is safe.
951 unsafe { ptr::read(src as *const T as *const U) }
955 /// Opaque type representing the discriminant of an enum.
957 /// See the [`discriminant`] function in this module for more information.
958 #[stable(feature = "discriminant_value", since = "1.21.0")]
959 pub struct Discriminant<T>(<T as DiscriminantKind>::Discriminant);
961 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
963 #[stable(feature = "discriminant_value", since = "1.21.0")]
964 impl<T> Copy for Discriminant<T> {}
966 #[stable(feature = "discriminant_value", since = "1.21.0")]
967 impl<T> clone::Clone for Discriminant<T> {
968 fn clone(&self) -> Self {
973 #[stable(feature = "discriminant_value", since = "1.21.0")]
974 impl<T> cmp::PartialEq for Discriminant<T> {
975 fn eq(&self, rhs: &Self) -> bool {
980 #[stable(feature = "discriminant_value", since = "1.21.0")]
981 impl<T> cmp::Eq for Discriminant<T> {}
983 #[stable(feature = "discriminant_value", since = "1.21.0")]
984 impl<T> hash::Hash for Discriminant<T> {
985 fn hash<H: hash::Hasher>(&self, state: &mut H) {
990 #[stable(feature = "discriminant_value", since = "1.21.0")]
991 impl<T> fmt::Debug for Discriminant<T> {
992 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
993 fmt.debug_tuple("Discriminant").field(&self.0).finish()
997 /// Returns a value uniquely identifying the enum variant in `v`.
999 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1000 /// return value is unspecified.
1004 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
1005 /// of some variant will not change between compilations with the same compiler.
1009 /// This can be used to compare enums that carry data, while disregarding
1010 /// the actual data:
1015 /// enum Foo { A(&'static str), B(i32), C(i32) }
1017 /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
1018 /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
1019 /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
1021 #[stable(feature = "discriminant_value", since = "1.21.0")]
1022 #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")]
1023 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")]
1024 pub const fn discriminant<T>(v: &T) -> Discriminant<T> {
1025 Discriminant(intrinsics::discriminant_value(v))
1028 /// Returns the number of variants in the enum type `T`.
1030 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1031 /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX`
1032 /// the return value is unspecified. Uninhabited variants will be counted.
1037 /// # #![feature(never_type)]
1038 /// # #![feature(variant_count)]
1043 /// enum Foo { A(&'static str), B(i32), C(i32) }
1045 /// assert_eq!(mem::variant_count::<Void>(), 0);
1046 /// assert_eq!(mem::variant_count::<Foo>(), 3);
1048 /// assert_eq!(mem::variant_count::<Option<!>>(), 2);
1049 /// assert_eq!(mem::variant_count::<Result<!, !>>(), 2);
1052 #[unstable(feature = "variant_count", issue = "73662")]
1053 #[rustc_const_unstable(feature = "variant_count", issue = "73662")]
1054 pub const fn variant_count<T>() -> usize {
1055 intrinsics::variant_count::<T>()