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")]
13 use marker::{Copy, PhantomData, Sized};
15 use ops::{Deref, DerefMut};
17 #[stable(feature = "rust1", since = "1.0.0")]
19 pub use intrinsics::transmute;
21 /// Takes ownership and "forgets" about the value **without running its destructor**.
23 /// Any resources the value manages, such as heap memory or a file handle, will linger
24 /// forever in an unreachable state. However, it does not guarantee that pointers
25 /// to this memory will remain valid.
27 /// * If you want to leak memory, see [`Box::leak`][leak].
28 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`][into_raw].
29 /// * If you want to dispose of a value properly, running its destructor, see
30 /// [`mem::drop`][drop].
34 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
35 /// do not include a guarantee that destructors will always run. For example,
36 /// a program can create a reference cycle using [`Rc`][rc], or call
37 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
38 /// `mem::forget` from safe code does not fundamentally change Rust's safety
41 /// That said, leaking resources such as memory or I/O objects is usually undesirable,
42 /// so `forget` is only recommended for specialized use cases like those shown below.
44 /// Because forgetting a value is allowed, any `unsafe` code you write must
45 /// allow for this possibility. You cannot return a value and expect that the
46 /// caller will necessarily run the value's destructor.
48 /// [rc]: ../../std/rc/struct.Rc.html
49 /// [exit]: ../../std/process/fn.exit.html
53 /// Leak an I/O object, never closing the file:
57 /// use std::fs::File;
59 /// let file = File::open("foo.txt").unwrap();
60 /// mem::forget(file);
63 /// The practical use cases for `forget` are rather specialized and mainly come
64 /// up in unsafe or FFI code.
68 /// You have created an uninitialized value using [`mem::uninitialized`][uninit].
69 /// You must either initialize or `forget` it on every computation path before
70 /// Rust drops it automatically, like at the end of a scope or after a panic.
71 /// Running the destructor on an uninitialized value would be [undefined behavior][ub].
77 /// # let some_condition = false;
79 /// let mut uninit_vec: Vec<u32> = mem::uninitialized();
81 /// if some_condition {
82 /// // Initialize the variable.
83 /// ptr::write(&mut uninit_vec, Vec::new());
85 /// // Forget the uninitialized value so its destructor doesn't run.
86 /// mem::forget(uninit_vec);
93 /// You have duplicated the bytes making up a value, without doing a proper
94 /// [`Clone`][clone]. You need the value's destructor to run only once,
95 /// because a double `free` is undefined behavior.
97 /// An example is a possible implementation of [`mem::swap`][swap]:
103 /// # #[allow(dead_code)]
104 /// fn swap<T>(x: &mut T, y: &mut T) {
106 /// // Give ourselves some scratch space to work with
107 /// let mut t: T = mem::uninitialized();
109 /// // Perform the swap, `&mut` pointers never alias
110 /// ptr::copy_nonoverlapping(&*x, &mut t, 1);
111 /// ptr::copy_nonoverlapping(&*y, x, 1);
112 /// ptr::copy_nonoverlapping(&t, y, 1);
114 /// // y and t now point to the same thing, but we need to completely
115 /// // forget `t` because we do not want to run the destructor for `T`
116 /// // on its value, which is still owned somewhere outside this function.
122 /// [drop]: fn.drop.html
123 /// [uninit]: fn.uninitialized.html
124 /// [clone]: ../clone/trait.Clone.html
125 /// [swap]: fn.swap.html
126 /// [box]: ../../std/boxed/struct.Box.html
127 /// [leak]: ../../std/boxed/struct.Box.html#method.leak
128 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
129 /// [ub]: ../../reference/behavior-considered-undefined.html
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub fn forget<T>(t: T) {
133 ManuallyDrop::new(t);
136 /// Like [`forget`], but also accepts unsized values.
138 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
141 /// [`forget`]: fn.forget.html
143 #[unstable(feature = "forget_unsized", issue = "0")]
144 pub fn forget_unsized<T: ?Sized>(t: T) {
145 unsafe { intrinsics::forget(t) }
148 /// Returns the size of a type in bytes.
150 /// More specifically, this is the offset in bytes between successive elements
151 /// in an array with that item type including alignment padding. Thus, for any
152 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
154 /// In general, the size of a type is not stable across compilations, but
155 /// specific types such as primitives are.
157 /// The following table gives the size for primitives.
159 /// Type | size_of::\<Type>()
160 /// ---- | ---------------
177 /// Furthermore, `usize` and `isize` have the same size.
179 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
180 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
182 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
183 /// have the same size. Likewise for `*const T` and `*mut T`.
185 /// # Size of `#[repr(C)]` items
187 /// The `C` representation for items has a defined layout. With this layout,
188 /// the size of items is also stable as long as all fields have a stable size.
190 /// ## Size of Structs
192 /// For `structs`, the size is determined by the following algorithm.
194 /// For each field in the struct ordered by declaration order:
196 /// 1. Add the size of the field.
197 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
199 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
200 /// The alignment of the struct is usually the largest alignment of all its
201 /// fields; this can be changed with the use of `repr(align(N))`.
203 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
207 /// Enums that carry no data other than the discriminant have the same size as C enums
208 /// on the platform they are compiled for.
210 /// ## Size of Unions
212 /// The size of a union is the size of its largest field.
214 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
221 /// // Some primitives
222 /// assert_eq!(4, mem::size_of::<i32>());
223 /// assert_eq!(8, mem::size_of::<f64>());
224 /// assert_eq!(0, mem::size_of::<()>());
227 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
228 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
229 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
232 /// // Pointer size equality
233 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
234 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
235 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
236 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
239 /// Using `#[repr(C)]`.
245 /// struct FieldStruct {
251 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
252 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
253 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
254 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
255 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
256 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
257 /// // fields is 2), so add 1 to the size for padding. Size is 6.
258 /// assert_eq!(6, mem::size_of::<FieldStruct>());
261 /// struct TupleStruct(u8, u16, u8);
263 /// // Tuple structs follow the same rules.
264 /// assert_eq!(6, mem::size_of::<TupleStruct>());
266 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
267 /// // by putting `third` before `second`.
269 /// struct FieldStructOptimized {
275 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
277 /// // Union size is the size of the largest field.
279 /// union ExampleUnion {
284 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
287 /// [alignment]: ./fn.align_of.html
289 #[stable(feature = "rust1", since = "1.0.0")]
291 pub const fn size_of<T>() -> usize {
292 intrinsics::size_of::<T>()
295 /// Returns the size of the pointed-to value in bytes.
297 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
298 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
299 /// then `size_of_val` can be used to get the dynamically-known size.
301 /// [slice]: ../../std/primitive.slice.html
302 /// [trait object]: ../../book/ch17-02-trait-objects.html
309 /// assert_eq!(4, mem::size_of_val(&5i32));
311 /// let x: [u8; 13] = [0; 13];
312 /// let y: &[u8] = &x;
313 /// assert_eq!(13, mem::size_of_val(y));
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
318 unsafe { intrinsics::size_of_val(val) }
321 /// Returns the [ABI]-required minimum alignment of a type.
323 /// Every reference to a value of the type `T` must be a multiple of this number.
325 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
327 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
332 /// # #![allow(deprecated)]
335 /// assert_eq!(4, mem::min_align_of::<i32>());
338 #[stable(feature = "rust1", since = "1.0.0")]
339 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
340 pub fn min_align_of<T>() -> usize {
341 intrinsics::min_align_of::<T>()
344 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
346 /// Every reference to a value of the type `T` must be a multiple of this number.
348 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
353 /// # #![allow(deprecated)]
356 /// assert_eq!(4, mem::min_align_of_val(&5i32));
359 #[stable(feature = "rust1", since = "1.0.0")]
360 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
361 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
362 unsafe { intrinsics::min_align_of_val(val) }
365 /// Returns the [ABI]-required minimum alignment of a type.
367 /// Every reference to a value of the type `T` must be a multiple of this number.
369 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
371 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
378 /// assert_eq!(4, mem::align_of::<i32>());
381 #[stable(feature = "rust1", since = "1.0.0")]
383 pub const fn align_of<T>() -> usize {
384 intrinsics::min_align_of::<T>()
387 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
389 /// Every reference to a value of the type `T` must be a multiple of this number.
391 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
398 /// assert_eq!(4, mem::align_of_val(&5i32));
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
403 unsafe { intrinsics::min_align_of_val(val) }
406 /// Returns `true` if dropping values of type `T` matters.
408 /// This is purely an optimization hint, and may be implemented conservatively:
409 /// it may return `true` for types that don't actually need to be dropped.
410 /// As such always returning `true` would be a valid implementation of
411 /// this function. However if this function actually returns `false`, then you
412 /// can be certain dropping `T` has no side effect.
414 /// Low level implementations of things like collections, which need to manually
415 /// drop their data, should use this function to avoid unnecessarily
416 /// trying to drop all their contents when they are destroyed. This might not
417 /// make a difference in release builds (where a loop that has no side-effects
418 /// is easily detected and eliminated), but is often a big win for debug builds.
420 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
421 /// can be reduced to some small number of drop_in_place calls, using this is
422 /// unnecessary. In particular note that you can drop_in_place a slice, and that
423 /// will do a single needs_drop check for all the values.
425 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
426 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
427 /// values one at a time and should use this API.
432 /// Here's an example of how a collection might make use of needs_drop:
435 /// use std::{mem, ptr};
437 /// pub struct MyCollection<T> {
441 /// # impl<T> MyCollection<T> {
442 /// # fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
443 /// # fn free_buffer(&mut self) {}
446 /// impl<T> Drop for MyCollection<T> {
447 /// fn drop(&mut self) {
450 /// if mem::needs_drop::<T>() {
451 /// for x in self.iter_mut() {
452 /// ptr::drop_in_place(x);
455 /// self.free_buffer();
461 #[stable(feature = "needs_drop", since = "1.21.0")]
462 #[rustc_const_unstable(feature = "const_needs_drop")]
463 pub const fn needs_drop<T>() -> bool {
464 intrinsics::needs_drop::<T>()
467 /// Creates a value whose bytes are all zero.
469 /// This has the same effect as allocating space with
470 /// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
471 /// FFI sometimes, but should generally be avoided.
473 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
474 /// some type `T`. If `T` has a destructor and the value is destroyed (due to
475 /// a panic or the end of a scope) before being initialized, then the destructor
476 /// will run on zeroed data, likely leading to [undefined behavior][ub].
478 /// See also the documentation for [`mem::uninitialized`][uninit], which has
479 /// many of the same caveats.
481 /// [uninit]: fn.uninitialized.html
482 /// [ub]: ../../reference/behavior-considered-undefined.html
489 /// let x: i32 = unsafe { mem::zeroed() };
490 /// assert_eq!(0, x);
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub unsafe fn zeroed<T>() -> T {
495 intrinsics::panic_if_uninhabited::<T>();
499 /// Bypasses Rust's normal memory-initialization checks by pretending to
500 /// produce a value of type `T`, while doing nothing at all.
502 /// **This is incredibly dangerous and should not be done lightly. Deeply
503 /// consider initializing your memory with a default value instead.**
505 /// This is useful for FFI functions and initializing arrays sometimes,
506 /// but should generally be avoided.
508 /// # Undefined behavior
510 /// It is [undefined behavior][ub] to read uninitialized memory, even just an
511 /// uninitialized boolean. For instance, if you branch on the value of such
512 /// a boolean, your program may take one, both, or neither of the branches.
514 /// Writing to the uninitialized value is similarly dangerous. Rust believes the
515 /// value is initialized, and will therefore try to [`Drop`] the uninitialized
516 /// value and its fields if you try to overwrite it in a normal manner. The only way
517 /// to safely initialize an uninitialized value is with [`ptr::write`][write],
518 /// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
520 /// If the value does implement [`Drop`], it must be initialized before
521 /// it goes out of scope (and therefore would be dropped). Note that this
522 /// includes a `panic` occurring and unwinding the stack suddenly.
524 /// If you partially initialize an array, you may need to use
525 /// [`ptr::drop_in_place`][drop_in_place] to remove the elements you have fully
526 /// initialized followed by [`mem::forget`][mem_forget] to prevent drop running
527 /// on the array. If a partially allocated array is dropped this will lead to
528 /// undefined behaviour.
532 /// Here's how to safely initialize an array of [`Vec`]s.
538 /// // Only declare the array. This safely leaves it
539 /// // uninitialized in a way that Rust will track for us.
540 /// // However we can't initialize it element-by-element
541 /// // safely, and we can't use the `[value; 1000]`
542 /// // constructor because it only works with `Copy` data.
543 /// let mut data: [Vec<u32>; 1000];
546 /// // So we need to do this to initialize it.
547 /// data = mem::uninitialized();
549 /// // DANGER ZONE: if anything panics or otherwise
550 /// // incorrectly reads the array here, we will have
551 /// // Undefined Behavior.
553 /// // It's ok to mutably iterate the data, since this
554 /// // doesn't involve reading it at all.
555 /// // (ptr and len are statically known for arrays)
556 /// for elem in &mut data[..] {
557 /// // *elem = Vec::new() would try to drop the
558 /// // uninitialized memory at `elem` -- bad!
560 /// // Vec::new doesn't allocate or do really
561 /// // anything. It's only safe to call here
562 /// // because we know it won't panic.
563 /// ptr::write(elem, Vec::new());
566 /// // SAFE ZONE: everything is initialized.
569 /// println!("{:?}", &data[0]);
572 /// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
573 /// can be. Note that the [`vec!`] macro *does* let you initialize every element with a
574 /// value that is only [`Clone`], so the following is semantically equivalent and
575 /// vastly less dangerous, as long as you can live with an extra heap
579 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
580 /// println!("{:?}", &data[0]);
583 /// This example shows how to handle partially initialized arrays, which could
584 /// be found in low-level datastructures.
590 /// // Count the number of elements we have assigned.
591 /// let mut data_len: usize = 0;
592 /// let mut data: [String; 1000];
595 /// data = mem::uninitialized();
597 /// for elem in &mut data[0..500] {
598 /// ptr::write(elem, String::from("hello"));
602 /// // For each item in the array, drop if we allocated it.
603 /// for i in &mut data[0..data_len] {
604 /// ptr::drop_in_place(i);
607 /// // Forget the data. If this is allowed to drop, you may see a crash such as:
608 /// // 'mem_uninit_test(2457,0x7fffb55dd380) malloc: *** error for object
609 /// // 0x7ff3b8402920: pointer being freed was not allocated'
610 /// mem::forget(data);
613 /// [`Vec`]: ../../std/vec/struct.Vec.html
614 /// [`vec!`]: ../../std/macro.vec.html
615 /// [`Clone`]: ../../std/clone/trait.Clone.html
616 /// [ub]: ../../reference/behavior-considered-undefined.html
617 /// [write]: ../ptr/fn.write.html
618 /// [drop_in_place]: ../ptr/fn.drop_in_place.html
619 /// [mem_zeroed]: fn.zeroed.html
620 /// [mem_forget]: fn.forget.html
621 /// [copy]: ../intrinsics/fn.copy.html
622 /// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
623 /// [`Drop`]: ../ops/trait.Drop.html
625 #[rustc_deprecated(since = "2.0.0", reason = "use `mem::MaybeUninit::uninitialized` instead")]
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub unsafe fn uninitialized<T>() -> T {
628 intrinsics::panic_if_uninhabited::<T>();
632 /// Swaps the values at two mutable locations, without deinitializing either one.
642 /// mem::swap(&mut x, &mut y);
644 /// assert_eq!(42, x);
645 /// assert_eq!(5, y);
648 #[stable(feature = "rust1", since = "1.0.0")]
649 pub fn swap<T>(x: &mut T, y: &mut T) {
651 ptr::swap_nonoverlapping_one(x, y);
655 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
657 /// Neither value is dropped.
661 /// A simple example:
666 /// let mut v: Vec<i32> = vec![1, 2];
668 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
669 /// assert_eq!(2, old_v.len());
670 /// assert_eq!(3, v.len());
673 /// `replace` allows consumption of a struct field by replacing it with another value.
674 /// Without `replace` you can run into issues like these:
676 /// ```compile_fail,E0507
677 /// struct Buffer<T> { buf: Vec<T> }
679 /// impl<T> Buffer<T> {
680 /// fn get_and_reset(&mut self) -> Vec<T> {
681 /// // error: cannot move out of dereference of `&mut`-pointer
682 /// let buf = self.buf;
683 /// self.buf = Vec::new();
689 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
690 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
691 /// `self`, allowing it to be returned:
694 /// # #![allow(dead_code)]
697 /// # struct Buffer<T> { buf: Vec<T> }
698 /// impl<T> Buffer<T> {
699 /// fn get_and_reset(&mut self) -> Vec<T> {
700 /// mem::replace(&mut self.buf, Vec::new())
705 /// [`Clone`]: ../../std/clone/trait.Clone.html
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
709 swap(dest, &mut src);
713 /// Disposes of a value.
715 /// This does call the argument's implementation of [`Drop`][drop].
717 /// This effectively does nothing for types which implement `Copy`, e.g.
718 /// integers. Such values are copied and _then_ moved into the function, so the
719 /// value persists after this function call.
721 /// This function is not magic; it is literally defined as
724 /// pub fn drop<T>(_x: T) { }
727 /// Because `_x` is moved into the function, it is automatically dropped before
728 /// the function returns.
730 /// [drop]: ../ops/trait.Drop.html
737 /// let v = vec![1, 2, 3];
739 /// drop(v); // explicitly drop the vector
742 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
743 /// release a [`RefCell`] borrow:
746 /// use std::cell::RefCell;
748 /// let x = RefCell::new(1);
750 /// let mut mutable_borrow = x.borrow_mut();
751 /// *mutable_borrow = 1;
753 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
755 /// let borrow = x.borrow();
756 /// println!("{}", *borrow);
759 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
762 /// #[derive(Copy, Clone)]
767 /// drop(x); // a copy of `x` is moved and dropped
768 /// drop(y); // a copy of `y` is moved and dropped
770 /// println!("x: {}, y: {}", x, y.0); // still available
773 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
774 /// [`Copy`]: ../../std/marker/trait.Copy.html
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn drop<T>(_x: T) { }
779 /// Interprets `src` as having type `&U`, and then reads `src` without moving
780 /// the contained value.
782 /// This function will unsafely assume the pointer `src` is valid for
783 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
784 /// the `&U`. It will also unsafely create a copy of the contained value instead of
785 /// moving out of `src`.
787 /// It is not a compile-time error if `T` and `U` have different sizes, but it
788 /// is highly encouraged to only invoke this function where `T` and `U` have the
789 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
792 /// [ub]: ../../reference/behavior-considered-undefined.html
793 /// [size_of]: fn.size_of.html
805 /// let foo_slice = [10u8];
808 /// // Copy the data from 'foo_slice' and treat it as a 'Foo'
809 /// let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
810 /// assert_eq!(foo_struct.bar, 10);
812 /// // Modify the copied data
813 /// foo_struct.bar = 20;
814 /// assert_eq!(foo_struct.bar, 20);
817 /// // The contents of 'foo_slice' should not have changed
818 /// assert_eq!(foo_slice, [10]);
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
823 ptr::read_unaligned(src as *const T as *const U)
826 /// Opaque type representing the discriminant of an enum.
828 /// See the [`discriminant`] function in this module for more information.
830 /// [`discriminant`]: fn.discriminant.html
831 #[stable(feature = "discriminant_value", since = "1.21.0")]
832 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
834 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
836 #[stable(feature = "discriminant_value", since = "1.21.0")]
837 impl<T> Copy for Discriminant<T> {}
839 #[stable(feature = "discriminant_value", since = "1.21.0")]
840 impl<T> clone::Clone for Discriminant<T> {
841 fn clone(&self) -> Self {
846 #[stable(feature = "discriminant_value", since = "1.21.0")]
847 impl<T> cmp::PartialEq for Discriminant<T> {
848 fn eq(&self, rhs: &Self) -> bool {
853 #[stable(feature = "discriminant_value", since = "1.21.0")]
854 impl<T> cmp::Eq for Discriminant<T> {}
856 #[stable(feature = "discriminant_value", since = "1.21.0")]
857 impl<T> hash::Hash for Discriminant<T> {
858 fn hash<H: hash::Hasher>(&self, state: &mut H) {
863 #[stable(feature = "discriminant_value", since = "1.21.0")]
864 impl<T> fmt::Debug for Discriminant<T> {
865 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
866 fmt.debug_tuple("Discriminant")
872 /// Returns a value uniquely identifying the enum variant in `v`.
874 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
875 /// return value is unspecified.
879 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
880 /// of some variant will not change between compilations with the same compiler.
884 /// This can be used to compare enums that carry data, while disregarding
890 /// enum Foo { A(&'static str), B(i32), C(i32) }
892 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
893 /// assert!(mem::discriminant(&Foo::B(1)) == mem::discriminant(&Foo::B(2)));
894 /// assert!(mem::discriminant(&Foo::B(3)) != mem::discriminant(&Foo::C(3)));
896 #[stable(feature = "discriminant_value", since = "1.21.0")]
897 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
899 Discriminant(intrinsics::discriminant_value(v), PhantomData)
903 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
905 /// This wrapper is 0-cost.
909 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
913 /// use std::mem::ManuallyDrop;
917 /// struct FruitBox {
918 /// // Immediately clear there’s something non-trivial going on with these fields.
919 /// peach: ManuallyDrop<Peach>,
920 /// melon: Melon, // Field that’s independent of the other two.
921 /// banana: ManuallyDrop<Banana>,
924 /// impl Drop for FruitBox {
925 /// fn drop(&mut self) {
927 /// // Explicit ordering in which field destructors are run specified in the intuitive
928 /// // location – the destructor of the structure containing the fields.
929 /// // Moreover, one can now reorder fields within the struct however much they want.
930 /// ManuallyDrop::drop(&mut self.peach);
931 /// ManuallyDrop::drop(&mut self.banana);
933 /// // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
934 /// // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
938 #[stable(feature = "manually_drop", since = "1.20.0")]
939 #[lang = "manually_drop"]
940 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
942 pub struct ManuallyDrop<T: ?Sized> {
946 impl<T> ManuallyDrop<T> {
947 /// Wrap a value to be manually dropped.
952 /// use std::mem::ManuallyDrop;
953 /// ManuallyDrop::new(Box::new(()));
955 #[stable(feature = "manually_drop", since = "1.20.0")]
957 pub const fn new(value: T) -> ManuallyDrop<T> {
958 ManuallyDrop { value }
961 /// Extracts the value from the `ManuallyDrop` container.
963 /// This allows the value to be dropped again.
968 /// use std::mem::ManuallyDrop;
969 /// let x = ManuallyDrop::new(Box::new(()));
970 /// let _: Box<()> = ManuallyDrop::into_inner(x); // This drops the `Box`.
972 #[stable(feature = "manually_drop", since = "1.20.0")]
974 pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
978 /// Takes the contained value out.
980 /// This method is primarily intended for moving out values in drop.
981 /// Instead of using [`ManuallyDrop::drop`] to manually drop the value,
982 /// you can use this method to take the value and use it however desired.
983 /// `Drop` will be invoked on the returned value following normal end-of-scope rules.
985 /// If you have ownership of the container, you can use [`ManuallyDrop::into_inner`] instead.
989 /// This function semantically moves out the contained value without preventing further usage.
990 /// It is up to the user of this method to ensure that this container is not used again.
992 /// [`ManuallyDrop::drop`]: #method.drop
993 /// [`ManuallyDrop::into_inner`]: #method.into_inner
994 #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"]
995 #[unstable(feature = "manually_drop_take", issue = "55422")]
997 pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
998 ManuallyDrop::into_inner(ptr::read(slot))
1002 impl<T: ?Sized> ManuallyDrop<T> {
1003 /// Manually drops the contained value.
1005 /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead.
1009 /// This function runs the destructor of the contained value and thus the wrapped value
1010 /// now represents uninitialized data. It is up to the user of this method to ensure the
1011 /// uninitialized data is not actually used.
1013 /// [`ManuallyDrop::into_inner`]: #method.into_inner
1014 #[stable(feature = "manually_drop", since = "1.20.0")]
1016 pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
1017 ptr::drop_in_place(&mut slot.value)
1021 #[stable(feature = "manually_drop", since = "1.20.0")]
1022 impl<T: ?Sized> Deref for ManuallyDrop<T> {
1025 fn deref(&self) -> &T {
1030 #[stable(feature = "manually_drop", since = "1.20.0")]
1031 impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
1033 fn deref_mut(&mut self) -> &mut T {
1038 /// A wrapper to construct uninitialized instances of `T`.
1040 /// The compiler, in general, assumes that variables are properly initialized
1041 /// at their respective type. For example, a variable of reference type must
1042 /// be aligned and non-NULL. This is an invariant that must *always* be upheld,
1043 /// even in unsafe code. As a consequence, zero-initializing a variable of reference
1044 /// type causes instantaneous undefined behavior, no matter whether that reference
1045 /// ever gets used to access memory:
1048 /// #![feature(maybe_uninit)]
1049 /// use std::mem::{self, MaybeUninit};
1051 /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior!
1052 /// // equivalent code with `MaybeUninit<&i32>`
1053 /// let x: &i32 = unsafe { MaybeUninit::zeroed().into_initialized() }; // undefined behavior!
1056 /// This is exploited by the compiler for various optimizations, such as eliding
1057 /// run-time checks and optimizing `enum` layout.
1059 /// Similarly, entirely uninitialized memory may have any content, while a `bool` must
1060 /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior:
1063 /// #![feature(maybe_uninit)]
1064 /// use std::mem::{self, MaybeUninit};
1066 /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior!
1067 /// // The equivalent code with `MaybeUninit<bool>`:
1068 /// let b: bool = unsafe { MaybeUninit::uninitialized().into_initialized() }; // undefined behavior!
1071 /// Moreover, uninitialized memory is special in that the compiler knows that
1072 /// it does not have a fixed value. This makes it undefined behavior to have
1073 /// uninitialized data in a variable even if that variable has an integer type,
1074 /// which otherwise can hold any bit pattern:
1077 /// #![feature(maybe_uninit)]
1078 /// use std::mem::{self, MaybeUninit};
1080 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior!
1081 /// // equivalent code with `MaybeUninit<i32>`
1082 /// let x: i32 = unsafe { MaybeUninit::uninitialized().into_initialized() }; // undefined behavior!
1084 /// (Notice that the rules around uninitialized integers are not finalized yet, but
1085 /// until they are, it is advisable to avoid them.)
1087 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
1088 /// It is a signal to the compiler indicating that the data here might *not*
1092 /// #![feature(maybe_uninit)]
1093 /// use std::mem::MaybeUninit;
1095 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
1096 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
1097 /// let mut x = MaybeUninit::<&i32>::uninitialized();
1098 /// // Set it to a valid value.
1100 /// // Extract the initialized data -- this is only allowed *after* properly
1101 /// // initializing `x`!
1102 /// let x = unsafe { x.into_initialized() };
1105 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
1106 // FIXME before stabilizing, explain how to initialize a struct field-by-field.
1107 #[allow(missing_debug_implementations)]
1108 #[unstable(feature = "maybe_uninit", issue = "53491")]
1110 // NOTE after stabilizing `MaybeUninit` proceed to deprecate `mem::uninitialized`.
1111 pub union MaybeUninit<T> {
1113 value: ManuallyDrop<T>,
1116 #[unstable(feature = "maybe_uninit", issue = "53491")]
1117 impl<T: Copy> Clone for MaybeUninit<T> {
1119 fn clone(&self) -> Self {
1120 // Not calling T::clone(), we cannot know if we are initialized enough for that.
1125 impl<T> MaybeUninit<T> {
1126 /// Create a new `MaybeUninit<T>` initialized with the given value.
1128 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1129 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1130 #[unstable(feature = "maybe_uninit", issue = "53491")]
1132 pub const fn new(val: T) -> MaybeUninit<T> {
1133 MaybeUninit { value: ManuallyDrop::new(val) }
1136 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
1138 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1139 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1140 #[unstable(feature = "maybe_uninit", issue = "53491")]
1142 pub const fn uninitialized() -> MaybeUninit<T> {
1143 MaybeUninit { uninit: () }
1146 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
1147 /// filled with `0` bytes. It depends on `T` whether that already makes for
1148 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
1149 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
1152 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1153 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1157 /// Correct usage of this function: initializing a struct with zero, where all
1158 /// fields of the struct can hold the bit-pattern 0 as a valid value.
1161 /// #![feature(maybe_uninit)]
1162 /// use std::mem::MaybeUninit;
1164 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
1165 /// let x = unsafe { x.into_initialized() };
1166 /// assert_eq!(x, (0, false));
1169 /// *Incorrect* usage of this function: initializing a struct with zero, where some fields
1170 /// cannot hold 0 as a valid value.
1173 /// #![feature(maybe_uninit)]
1174 /// use std::mem::MaybeUninit;
1176 /// enum NotZero { One = 1, Two = 2 };
1178 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
1179 /// let x = unsafe { x.into_initialized() };
1180 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
1181 /// // This is undefined behavior.
1183 #[unstable(feature = "maybe_uninit", issue = "53491")]
1185 pub fn zeroed() -> MaybeUninit<T> {
1186 let mut u = MaybeUninit::<T>::uninitialized();
1188 u.as_mut_ptr().write_bytes(0u8, 1);
1193 /// Sets the value of the `MaybeUninit<T>`. This overwrites any previous value
1194 /// without dropping it. For your convenience, this also returns a mutable
1195 /// reference to the (now safely initialized) contents of `self`.
1196 #[unstable(feature = "maybe_uninit", issue = "53491")]
1198 pub fn set(&mut self, val: T) -> &mut T {
1200 self.value = ManuallyDrop::new(val);
1205 /// Gets a pointer to the contained value. Reading from this pointer or turning it
1206 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
1210 /// Correct usage of this method:
1213 /// #![feature(maybe_uninit)]
1214 /// use std::mem::MaybeUninit;
1216 /// let mut x = MaybeUninit::<Vec<u32>>::uninitialized();
1217 /// x.set(vec![0,1,2]);
1218 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
1219 /// let x_vec = unsafe { &*x.as_ptr() };
1220 /// assert_eq!(x_vec.len(), 3);
1223 /// *Incorrect* usage of this method:
1226 /// #![feature(maybe_uninit)]
1227 /// use std::mem::MaybeUninit;
1229 /// let x = MaybeUninit::<Vec<u32>>::uninitialized();
1230 /// let x_vec = unsafe { &*x.as_ptr() };
1231 /// // We have created a reference to an uninitialized vector! This is undefined behavior.
1233 #[unstable(feature = "maybe_uninit", issue = "53491")]
1235 pub fn as_ptr(&self) -> *const T {
1236 unsafe { &*self.value as *const T }
1239 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
1240 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
1244 /// Correct usage of this method:
1247 /// #![feature(maybe_uninit)]
1248 /// use std::mem::MaybeUninit;
1250 /// let mut x = MaybeUninit::<Vec<u32>>::uninitialized();
1251 /// x.set(vec![0,1,2]);
1252 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
1253 /// // This is okay because we initialized it.
1254 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1256 /// assert_eq!(x_vec.len(), 4);
1259 /// *Incorrect* usage of this method:
1262 /// #![feature(maybe_uninit)]
1263 /// use std::mem::MaybeUninit;
1265 /// let mut x = MaybeUninit::<Vec<u32>>::uninitialized();
1266 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1267 /// // We have created a reference to an uninitialized vector! This is undefined behavior.
1269 #[unstable(feature = "maybe_uninit", issue = "53491")]
1271 pub fn as_mut_ptr(&mut self) -> *mut T {
1272 unsafe { &mut *self.value as *mut T }
1275 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
1276 /// to ensure that the data will get dropped, because the resulting `T` is
1277 /// subject to the usual drop handling.
1281 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1282 /// state. Calling this when the content is not yet fully initialized causes undefined
1287 /// Correct usage of this method:
1290 /// #![feature(maybe_uninit)]
1291 /// use std::mem::MaybeUninit;
1293 /// let mut x = MaybeUninit::<bool>::uninitialized();
1295 /// let x_init = unsafe { x.into_initialized() };
1296 /// assert_eq!(x_init, true);
1299 /// *Incorrect* usage of this method:
1302 /// #![feature(maybe_uninit)]
1303 /// use std::mem::MaybeUninit;
1305 /// let x = MaybeUninit::<Vec<u32>>::uninitialized();
1306 /// let x_init = unsafe { x.into_initialized() };
1307 /// // `x` had not been initialized yet, so this last line caused undefined behavior.
1309 #[unstable(feature = "maybe_uninit", issue = "53491")]
1311 pub unsafe fn into_initialized(self) -> T {
1312 intrinsics::panic_if_uninhabited::<T>();
1313 ManuallyDrop::into_inner(self.value)
1316 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
1317 /// to the usual drop handling.
1321 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1322 /// state. Calling this when the content is not yet fully initialized causes undefined
1325 /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit<T>`. When using
1326 /// multiple copies of the data (by calling `read_initialized` multiple times, or first
1327 /// calling `read_initialized` and then [`into_initialized`]), it is your responsibility
1328 /// to ensure that that data may indeed be duplicated.
1330 /// [`into_initialized`]: #method.into_initialized
1334 /// Correct usage of this method:
1337 /// #![feature(maybe_uninit)]
1338 /// use std::mem::MaybeUninit;
1340 /// let mut x = MaybeUninit::<u32>::uninitialized();
1342 /// let x1 = unsafe { x.read_initialized() };
1343 /// // `u32` is `Copy`, so we may read multiple times.
1344 /// let x2 = unsafe { x.read_initialized() };
1345 /// assert_eq!(x1, x2);
1347 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninitialized();
1349 /// let x1 = unsafe { x.read_initialized() };
1350 /// // Duplicating a `None` value is okay, so we may read multiple times.
1351 /// let x2 = unsafe { x.read_initialized() };
1352 /// assert_eq!(x1, x2);
1355 /// *Incorrect* usage of this method:
1358 /// #![feature(maybe_uninit)]
1359 /// use std::mem::MaybeUninit;
1361 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninitialized();
1362 /// x.set(Some(vec![0,1,2]));
1363 /// let x1 = unsafe { x.read_initialized() };
1364 /// let x2 = unsafe { x.read_initialized() };
1365 /// // We now created two copies of the same vector, leading to a double-free when
1366 /// // they both get dropped!
1368 #[unstable(feature = "maybe_uninit", issue = "53491")]
1370 pub unsafe fn read_initialized(&self) -> T {
1371 intrinsics::panic_if_uninhabited::<T>();
1372 self.as_ptr().read()
1375 /// Gets a reference to the contained value.
1379 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1380 /// state. Calling this when the content is not yet fully initialized causes undefined
1382 #[unstable(feature = "maybe_uninit_ref", issue = "53491")]
1384 pub unsafe fn get_ref(&self) -> &T {
1388 /// Gets a mutable reference to the contained value.
1392 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1393 /// state. Calling this when the content is not yet fully initialized causes undefined
1395 // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references
1396 // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make
1397 // a final decision about the rules before stabilization.
1398 #[unstable(feature = "maybe_uninit_ref", issue = "53491")]
1400 pub unsafe fn get_mut(&mut self) -> &mut T {
1404 /// Gets a pointer to the first element of the array.
1405 #[unstable(feature = "maybe_uninit_slice", issue = "53491")]
1407 pub fn first_ptr(this: &[MaybeUninit<T>]) -> *const T {
1408 this as *const [MaybeUninit<T>] as *const T
1411 /// Gets a mutable pointer to the first element of the array.
1412 #[unstable(feature = "maybe_uninit_slice", issue = "53491")]
1414 pub fn first_ptr_mut(this: &mut [MaybeUninit<T>]) -> *mut T {
1415 this as *mut [MaybeUninit<T>] as *mut T