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, PhantomData, Sized};
15 use crate::ops::{Deref, DerefMut};
17 #[stable(feature = "rust1", since = "1.0.0")]
19 pub use crate::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.
66 /// [drop]: fn.drop.html
67 /// [uninit]: fn.uninitialized.html
68 /// [clone]: ../clone/trait.Clone.html
69 /// [swap]: fn.swap.html
70 /// [box]: ../../std/boxed/struct.Box.html
71 /// [leak]: ../../std/boxed/struct.Box.html#method.leak
72 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
73 /// [ub]: ../../reference/behavior-considered-undefined.html
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub fn forget<T>(t: T) {
80 /// Like [`forget`], but also accepts unsized values.
82 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
85 /// [`forget`]: fn.forget.html
87 #[unstable(feature = "forget_unsized", issue = "0")]
88 pub fn forget_unsized<T: ?Sized>(t: T) {
89 unsafe { intrinsics::forget(t) }
92 /// Returns the size of a type in bytes.
94 /// More specifically, this is the offset in bytes between successive elements
95 /// in an array with that item type including alignment padding. Thus, for any
96 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
98 /// In general, the size of a type is not stable across compilations, but
99 /// specific types such as primitives are.
101 /// The following table gives the size for primitives.
103 /// Type | size_of::\<Type>()
104 /// ---- | ---------------
121 /// Furthermore, `usize` and `isize` have the same size.
123 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
124 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
126 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
127 /// have the same size. Likewise for `*const T` and `*mut T`.
129 /// # Size of `#[repr(C)]` items
131 /// The `C` representation for items has a defined layout. With this layout,
132 /// the size of items is also stable as long as all fields have a stable size.
134 /// ## Size of Structs
136 /// For `structs`, the size is determined by the following algorithm.
138 /// For each field in the struct ordered by declaration order:
140 /// 1. Add the size of the field.
141 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
143 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
144 /// The alignment of the struct is usually the largest alignment of all its
145 /// fields; this can be changed with the use of `repr(align(N))`.
147 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
151 /// Enums that carry no data other than the discriminant have the same size as C enums
152 /// on the platform they are compiled for.
154 /// ## Size of Unions
156 /// The size of a union is the size of its largest field.
158 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
165 /// // Some primitives
166 /// assert_eq!(4, mem::size_of::<i32>());
167 /// assert_eq!(8, mem::size_of::<f64>());
168 /// assert_eq!(0, mem::size_of::<()>());
171 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
172 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
173 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
176 /// // Pointer size equality
177 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
178 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
179 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
180 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
183 /// Using `#[repr(C)]`.
189 /// struct FieldStruct {
195 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
196 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
197 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
198 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
199 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
200 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
201 /// // fields is 2), so add 1 to the size for padding. Size is 6.
202 /// assert_eq!(6, mem::size_of::<FieldStruct>());
205 /// struct TupleStruct(u8, u16, u8);
207 /// // Tuple structs follow the same rules.
208 /// assert_eq!(6, mem::size_of::<TupleStruct>());
210 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
211 /// // by putting `third` before `second`.
213 /// struct FieldStructOptimized {
219 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
221 /// // Union size is the size of the largest field.
223 /// union ExampleUnion {
228 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
231 /// [alignment]: ./fn.align_of.html
233 #[stable(feature = "rust1", since = "1.0.0")]
235 pub const fn size_of<T>() -> usize {
236 intrinsics::size_of::<T>()
239 /// Returns the size of the pointed-to value in bytes.
241 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
242 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
243 /// then `size_of_val` can be used to get the dynamically-known size.
245 /// [slice]: ../../std/primitive.slice.html
246 /// [trait object]: ../../book/ch17-02-trait-objects.html
253 /// assert_eq!(4, mem::size_of_val(&5i32));
255 /// let x: [u8; 13] = [0; 13];
256 /// let y: &[u8] = &x;
257 /// assert_eq!(13, mem::size_of_val(y));
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
262 unsafe { intrinsics::size_of_val(val) }
265 /// Returns the [ABI]-required minimum alignment of a type.
267 /// Every reference to a value of the type `T` must be a multiple of this number.
269 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
271 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
276 /// # #![allow(deprecated)]
279 /// assert_eq!(4, mem::min_align_of::<i32>());
282 #[stable(feature = "rust1", since = "1.0.0")]
283 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
284 pub fn min_align_of<T>() -> usize {
285 intrinsics::min_align_of::<T>()
288 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
290 /// Every reference to a value of the type `T` must be a multiple of this number.
292 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
297 /// # #![allow(deprecated)]
300 /// assert_eq!(4, mem::min_align_of_val(&5i32));
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
305 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
306 unsafe { intrinsics::min_align_of_val(val) }
309 /// Returns the [ABI]-required minimum alignment of a type.
311 /// Every reference to a value of the type `T` must be a multiple of this number.
313 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
315 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
322 /// assert_eq!(4, mem::align_of::<i32>());
325 #[stable(feature = "rust1", since = "1.0.0")]
327 pub const fn align_of<T>() -> usize {
328 intrinsics::min_align_of::<T>()
331 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
333 /// Every reference to a value of the type `T` must be a multiple of this number.
335 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
342 /// assert_eq!(4, mem::align_of_val(&5i32));
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
347 unsafe { intrinsics::min_align_of_val(val) }
350 /// Returns `true` if dropping values of type `T` matters.
352 /// This is purely an optimization hint, and may be implemented conservatively:
353 /// it may return `true` for types that don't actually need to be dropped.
354 /// As such always returning `true` would be a valid implementation of
355 /// this function. However if this function actually returns `false`, then you
356 /// can be certain dropping `T` has no side effect.
358 /// Low level implementations of things like collections, which need to manually
359 /// drop their data, should use this function to avoid unnecessarily
360 /// trying to drop all their contents when they are destroyed. This might not
361 /// make a difference in release builds (where a loop that has no side-effects
362 /// is easily detected and eliminated), but is often a big win for debug builds.
364 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
365 /// can be reduced to some small number of drop_in_place calls, using this is
366 /// unnecessary. In particular note that you can drop_in_place a slice, and that
367 /// will do a single needs_drop check for all the values.
369 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
370 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
371 /// values one at a time and should use this API.
376 /// Here's an example of how a collection might make use of needs_drop:
379 /// use std::{mem, ptr};
381 /// pub struct MyCollection<T> {
385 /// # impl<T> MyCollection<T> {
386 /// # fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
387 /// # fn free_buffer(&mut self) {}
390 /// impl<T> Drop for MyCollection<T> {
391 /// fn drop(&mut self) {
394 /// if mem::needs_drop::<T>() {
395 /// for x in self.iter_mut() {
396 /// ptr::drop_in_place(x);
399 /// self.free_buffer();
405 #[stable(feature = "needs_drop", since = "1.21.0")]
406 pub const fn needs_drop<T>() -> bool {
407 intrinsics::needs_drop::<T>()
410 /// Creates a value whose bytes are all zero.
412 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
413 /// It is useful for FFI sometimes, but should generally be avoided.
415 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
416 /// some type `T`. For example, the all-zero byte-pattern is not a valid value
417 /// for reference types (`&T` and `&mut T`). Using `zeroed` on such types
418 /// causes immediate [undefined behavior][ub] because [the Rust compiler assumes][inv]
419 /// that there always is a valid value in a variable it considers initialized.
421 /// [zeroed]: union.MaybeUninit.html#method.zeroed
422 /// [ub]: ../../reference/behavior-considered-undefined.html
423 /// [inv]: union.MaybeUninit.html#initialization-invariant
427 /// Correct usage of this function: initializing an integer with zero.
432 /// let x: i32 = unsafe { mem::zeroed() };
433 /// assert_eq!(0, x);
436 /// *Incorrect* usage of this function: initializing a reference with zero.
441 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub unsafe fn zeroed<T>() -> T {
446 intrinsics::panic_if_uninhabited::<T>();
450 /// Bypasses Rust's normal memory-initialization checks by pretending to
451 /// produce a value of type `T`, while doing nothing at all.
453 /// **This functon is deprecated.** Use [`MaybeUninit<T>`] instead.
455 /// The reason for deprecation is that the function basically cannot be used
456 /// correctly: [the Rust compiler assumes][inv] that values are properly initialized.
457 /// As a consequence, calling e.g. `mem::uninitialized::<bool>()` causes immediate
458 /// undefined behavior for returning a `bool` that is not definitely either `true`
459 /// or `false`. Worse, truly uninitialized memory like what gets returned here
460 /// is special in that the compiler knows that it does not have a fixed value.
461 /// This makes it undefined behavior to have uninitialized data in a variable even
462 /// if that variable has an integer type.
463 /// (Notice that the rules around uninitialized integers are not finalized yet, but
464 /// until they are, it is advisable to avoid them.)
466 /// [`MaybeUninit<T>`]: union.MaybeUninit.html
467 /// [inv]: union.MaybeUninit.html#initialization-invariant
469 #[rustc_deprecated(since = "1.38.0", reason = "use `mem::MaybeUninit` instead")]
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub unsafe fn uninitialized<T>() -> T {
472 intrinsics::panic_if_uninhabited::<T>();
476 /// Swaps the values at two mutable locations, without deinitializing either one.
486 /// mem::swap(&mut x, &mut y);
488 /// assert_eq!(42, x);
489 /// assert_eq!(5, y);
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn swap<T>(x: &mut T, y: &mut T) {
495 ptr::swap_nonoverlapping_one(x, y);
499 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
501 /// Neither value is dropped.
505 /// A simple example:
510 /// let mut v: Vec<i32> = vec![1, 2];
512 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
513 /// assert_eq!(vec![1, 2], old_v);
514 /// assert_eq!(vec![3, 4, 5], v);
517 /// `replace` allows consumption of a struct field by replacing it with another value.
518 /// Without `replace` you can run into issues like these:
520 /// ```compile_fail,E0507
521 /// struct Buffer<T> { buf: Vec<T> }
523 /// impl<T> Buffer<T> {
524 /// fn get_and_reset(&mut self) -> Vec<T> {
525 /// // error: cannot move out of dereference of `&mut`-pointer
526 /// let buf = self.buf;
527 /// self.buf = Vec::new();
533 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
534 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
535 /// `self`, allowing it to be returned:
538 /// # #![allow(dead_code)]
541 /// # struct Buffer<T> { buf: Vec<T> }
542 /// impl<T> Buffer<T> {
543 /// fn get_and_reset(&mut self) -> Vec<T> {
544 /// mem::replace(&mut self.buf, Vec::new())
549 /// [`Clone`]: ../../std/clone/trait.Clone.html
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
553 swap(dest, &mut src);
557 /// Disposes of a value.
559 /// This does call the argument's implementation of [`Drop`][drop].
561 /// This effectively does nothing for types which implement `Copy`, e.g.
562 /// integers. Such values are copied and _then_ moved into the function, so the
563 /// value persists after this function call.
565 /// This function is not magic; it is literally defined as
568 /// pub fn drop<T>(_x: T) { }
571 /// Because `_x` is moved into the function, it is automatically dropped before
572 /// the function returns.
574 /// [drop]: ../ops/trait.Drop.html
581 /// let v = vec![1, 2, 3];
583 /// drop(v); // explicitly drop the vector
586 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
587 /// release a [`RefCell`] borrow:
590 /// use std::cell::RefCell;
592 /// let x = RefCell::new(1);
594 /// let mut mutable_borrow = x.borrow_mut();
595 /// *mutable_borrow = 1;
597 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
599 /// let borrow = x.borrow();
600 /// println!("{}", *borrow);
603 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
606 /// #[derive(Copy, Clone)]
611 /// drop(x); // a copy of `x` is moved and dropped
612 /// drop(y); // a copy of `y` is moved and dropped
614 /// println!("x: {}, y: {}", x, y.0); // still available
617 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
618 /// [`Copy`]: ../../std/marker/trait.Copy.html
620 #[stable(feature = "rust1", since = "1.0.0")]
621 pub fn drop<T>(_x: T) { }
623 /// Interprets `src` as having type `&U`, and then reads `src` without moving
624 /// the contained value.
626 /// This function will unsafely assume the pointer `src` is valid for
627 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
628 /// the `&U`. It will also unsafely create a copy of the contained value instead of
629 /// moving out of `src`.
631 /// It is not a compile-time error if `T` and `U` have different sizes, but it
632 /// is highly encouraged to only invoke this function where `T` and `U` have the
633 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
636 /// [ub]: ../../reference/behavior-considered-undefined.html
637 /// [size_of]: fn.size_of.html
649 /// let foo_slice = [10u8];
652 /// // Copy the data from 'foo_slice' and treat it as a 'Foo'
653 /// let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
654 /// assert_eq!(foo_struct.bar, 10);
656 /// // Modify the copied data
657 /// foo_struct.bar = 20;
658 /// assert_eq!(foo_struct.bar, 20);
661 /// // The contents of 'foo_slice' should not have changed
662 /// assert_eq!(foo_slice, [10]);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
667 ptr::read_unaligned(src as *const T as *const U)
670 /// Opaque type representing the discriminant of an enum.
672 /// See the [`discriminant`] function in this module for more information.
674 /// [`discriminant`]: fn.discriminant.html
675 #[stable(feature = "discriminant_value", since = "1.21.0")]
676 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
678 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
680 #[stable(feature = "discriminant_value", since = "1.21.0")]
681 impl<T> Copy for Discriminant<T> {}
683 #[stable(feature = "discriminant_value", since = "1.21.0")]
684 impl<T> clone::Clone for Discriminant<T> {
685 fn clone(&self) -> Self {
690 #[stable(feature = "discriminant_value", since = "1.21.0")]
691 impl<T> cmp::PartialEq for Discriminant<T> {
692 fn eq(&self, rhs: &Self) -> bool {
697 #[stable(feature = "discriminant_value", since = "1.21.0")]
698 impl<T> cmp::Eq for Discriminant<T> {}
700 #[stable(feature = "discriminant_value", since = "1.21.0")]
701 impl<T> hash::Hash for Discriminant<T> {
702 fn hash<H: hash::Hasher>(&self, state: &mut H) {
707 #[stable(feature = "discriminant_value", since = "1.21.0")]
708 impl<T> fmt::Debug for Discriminant<T> {
709 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
710 fmt.debug_tuple("Discriminant")
716 /// Returns a value uniquely identifying the enum variant in `v`.
718 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
719 /// return value is unspecified.
723 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
724 /// of some variant will not change between compilations with the same compiler.
728 /// This can be used to compare enums that carry data, while disregarding
734 /// enum Foo { A(&'static str), B(i32), C(i32) }
736 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
737 /// assert!(mem::discriminant(&Foo::B(1)) == mem::discriminant(&Foo::B(2)));
738 /// assert!(mem::discriminant(&Foo::B(3)) != mem::discriminant(&Foo::C(3)));
740 #[stable(feature = "discriminant_value", since = "1.21.0")]
741 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
743 Discriminant(intrinsics::discriminant_value(v), PhantomData)
747 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
749 /// This wrapper is 0-cost.
751 /// `ManuallyDrop<T>` is subject to the same layout optimizations as `T`.
752 /// As a consequence, it has *no effect* on the assumptions that the compiler makes
753 /// about all values being initialized at their type. In particular, initializing
754 /// a `ManuallyDrop<&mut T>` with [`mem::zeroed`] is undefined behavior.
755 /// If you need to handle uninitialized data, use [`MaybeUninit<T>`] instead.
759 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
763 /// use std::mem::ManuallyDrop;
767 /// struct FruitBox {
768 /// // Immediately clear there’s something non-trivial going on with these fields.
769 /// peach: ManuallyDrop<Peach>,
770 /// melon: Melon, // Field that’s independent of the other two.
771 /// banana: ManuallyDrop<Banana>,
774 /// impl Drop for FruitBox {
775 /// fn drop(&mut self) {
777 /// // Explicit ordering in which field destructors are run specified in the intuitive
778 /// // location – the destructor of the structure containing the fields.
779 /// // Moreover, one can now reorder fields within the struct however much they want.
780 /// ManuallyDrop::drop(&mut self.peach);
781 /// ManuallyDrop::drop(&mut self.banana);
783 /// // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
784 /// // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
789 /// [`mem::zeroed`]: fn.zeroed.html
790 /// [`MaybeUninit<T>`]: union.MaybeUninit.html
791 #[stable(feature = "manually_drop", since = "1.20.0")]
792 #[lang = "manually_drop"]
793 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
795 pub struct ManuallyDrop<T: ?Sized> {
799 impl<T> ManuallyDrop<T> {
800 /// Wrap a value to be manually dropped.
805 /// use std::mem::ManuallyDrop;
806 /// ManuallyDrop::new(Box::new(()));
808 #[stable(feature = "manually_drop", since = "1.20.0")]
810 pub const fn new(value: T) -> ManuallyDrop<T> {
811 ManuallyDrop { value }
814 /// Extracts the value from the `ManuallyDrop` container.
816 /// This allows the value to be dropped again.
821 /// use std::mem::ManuallyDrop;
822 /// let x = ManuallyDrop::new(Box::new(()));
823 /// let _: Box<()> = ManuallyDrop::into_inner(x); // This drops the `Box`.
825 #[stable(feature = "manually_drop", since = "1.20.0")]
827 pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
831 /// Takes the contained value out.
833 /// This method is primarily intended for moving out values in drop.
834 /// Instead of using [`ManuallyDrop::drop`] to manually drop the value,
835 /// you can use this method to take the value and use it however desired.
836 /// `Drop` will be invoked on the returned value following normal end-of-scope rules.
838 /// If you have ownership of the container, you can use [`ManuallyDrop::into_inner`] instead.
842 /// This function semantically moves out the contained value without preventing further usage.
843 /// It is up to the user of this method to ensure that this container is not used again.
845 /// [`ManuallyDrop::drop`]: #method.drop
846 /// [`ManuallyDrop::into_inner`]: #method.into_inner
847 #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"]
848 #[unstable(feature = "manually_drop_take", issue = "55422")]
850 pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
851 ManuallyDrop::into_inner(ptr::read(slot))
855 impl<T: ?Sized> ManuallyDrop<T> {
856 /// Manually drops the contained value.
858 /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead.
862 /// This function runs the destructor of the contained value and thus the wrapped value
863 /// now represents uninitialized data. It is up to the user of this method to ensure the
864 /// uninitialized data is not actually used.
866 /// [`ManuallyDrop::into_inner`]: #method.into_inner
867 #[stable(feature = "manually_drop", since = "1.20.0")]
869 pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
870 ptr::drop_in_place(&mut slot.value)
874 #[stable(feature = "manually_drop", since = "1.20.0")]
875 impl<T: ?Sized> Deref for ManuallyDrop<T> {
878 fn deref(&self) -> &T {
883 #[stable(feature = "manually_drop", since = "1.20.0")]
884 impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
886 fn deref_mut(&mut self) -> &mut T {
891 /// A wrapper type to construct uninitialized instances of `T`.
893 /// # Initialization invariant
895 /// The compiler, in general, assumes that variables are properly initialized
896 /// at their respective type. For example, a variable of reference type must
897 /// be aligned and non-NULL. This is an invariant that must *always* be upheld,
898 /// even in unsafe code. As a consequence, zero-initializing a variable of reference
899 /// type causes instantaneous [undefined behavior][ub], no matter whether that reference
900 /// ever gets used to access memory:
903 /// use std::mem::{self, MaybeUninit};
905 /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior!
906 /// // The equivalent code with `MaybeUninit<&i32>`:
907 /// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior!
910 /// This is exploited by the compiler for various optimizations, such as eliding
911 /// run-time checks and optimizing `enum` layout.
913 /// Similarly, entirely uninitialized memory may have any content, while a `bool` must
914 /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior:
917 /// use std::mem::{self, MaybeUninit};
919 /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior!
920 /// // The equivalent code with `MaybeUninit<bool>`:
921 /// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior!
924 /// Moreover, uninitialized memory is special in that the compiler knows that
925 /// it does not have a fixed value. This makes it undefined behavior to have
926 /// uninitialized data in a variable even if that variable has an integer type,
927 /// which otherwise can hold any *fixed* bit pattern:
930 /// use std::mem::{self, MaybeUninit};
932 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior!
933 /// // The equivalent code with `MaybeUninit<i32>`:
934 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior!
936 /// (Notice that the rules around uninitialized integers are not finalized yet, but
937 /// until they are, it is advisable to avoid them.)
939 /// On top of that, remember that most types have additional invariants beyond merely
940 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
941 /// is considered initialized because the only requirement the compiler knows about it
942 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
943 /// *immediate* undefined behavior, but will cause undefined behavior with most
944 /// safe operations (including dropping it).
946 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
950 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
951 /// It is a signal to the compiler indicating that the data here might *not*
955 /// use std::mem::MaybeUninit;
957 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
958 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
959 /// let mut x = MaybeUninit::<&i32>::uninit();
960 /// // Set it to a valid value.
961 /// unsafe { x.as_mut_ptr().write(&0); }
962 /// // Extract the initialized data -- this is only allowed *after* properly
963 /// // initializing `x`!
964 /// let x = unsafe { x.assume_init() };
967 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
969 /// You can think of `MaybeUninit<T>` and being a bit like `Option<T>` but without
970 /// any of the run-time tracking and without any of the safety checks.
974 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
975 /// from a function, pass it a pointer to some (uninitialized) memory to put the
976 /// result into. This can be useful when it is important for the caller to control
977 /// how the memory the result is stored in gets allocated, and you want to avoid
978 /// unnecessary moves.
981 /// use std::mem::MaybeUninit;
983 /// unsafe fn make_vec(out: *mut Vec<i32>) {
984 /// // `write` does not drop the old contents, which is important.
985 /// out.write(vec![1, 2, 3]);
988 /// let mut v = MaybeUninit::uninit();
989 /// unsafe { make_vec(v.as_mut_ptr()); }
990 /// // Now we know `v` is initialized! This also makes sure the vector gets
991 /// // properly dropped.
992 /// let v = unsafe { v.assume_init() };
993 /// assert_eq!(&v, &[1, 2, 3]);
996 /// ## Initializing an array element-by-element
998 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
1001 /// use std::mem::{self, MaybeUninit};
1005 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
1006 /// // safe because the type we are claiming to have initialized here is a
1007 /// // bunch of `MaybeUninit`s, which do not require initialization.
1008 /// let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
1009 /// MaybeUninit::uninit().assume_init()
1012 /// // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop,
1013 /// // we have a memory leak, but there is no memory safety issue.
1014 /// for elem in &mut data[..] {
1015 /// unsafe { ptr::write(elem.as_mut_ptr(), vec![42]); }
1018 /// // Everything is initialized. Transmute the array to the
1019 /// // initialized type.
1020 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
1023 /// assert_eq!(&data[0], &[42]);
1026 /// You can also work with partially initialized arrays, which could
1027 /// be found in low-level datastructures.
1030 /// use std::mem::MaybeUninit;
1033 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
1034 /// // safe because the type we are claiming to have initialized here is a
1035 /// // bunch of `MaybeUninit`s, which do not require initialization.
1036 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
1037 /// // Count the number of elements we have assigned.
1038 /// let mut data_len: usize = 0;
1040 /// for elem in &mut data[0..500] {
1041 /// unsafe { ptr::write(elem.as_mut_ptr(), String::from("hello")); }
1045 /// // For each item in the array, drop if we allocated it.
1046 /// for elem in &mut data[0..data_len] {
1047 /// unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
1051 /// ## Initializing a struct field-by-field
1053 /// There is currently no supported way to create a raw pointer or reference
1054 /// to a field of a struct inside `MaybeUninit<Struct>`. That means it is not possible
1055 /// to create a struct by calling `MaybeUninit::uninit::<Struct>()` and then writing
1058 /// [ub]: ../../reference/behavior-considered-undefined.html
1062 /// `MaybeUninit<T>` is guaranteed to have the same size and alignment as `T`:
1065 /// use std::mem::{MaybeUninit, size_of, align_of};
1066 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
1067 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
1070 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
1071 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
1072 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
1073 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
1074 /// optimizations, potentially resulting in a larger size:
1077 /// # use std::mem::{MaybeUninit, size_of};
1078 /// assert_eq!(size_of::<Option<bool>>(), 1);
1079 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
1081 #[allow(missing_debug_implementations)]
1082 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1084 pub union MaybeUninit<T> {
1086 value: ManuallyDrop<T>,
1089 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1090 impl<T: Copy> Clone for MaybeUninit<T> {
1092 fn clone(&self) -> Self {
1093 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
1098 impl<T> MaybeUninit<T> {
1099 /// Creates a new `MaybeUninit<T>` initialized with the given value.
1100 /// It is safe to call [`assume_init`] on the return value of this function.
1102 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1103 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1105 /// [`assume_init`]: #method.assume_init
1106 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1108 pub const fn new(val: T) -> MaybeUninit<T> {
1109 MaybeUninit { value: ManuallyDrop::new(val) }
1112 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
1114 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1115 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1117 /// See the [type-level documentation][type] for some examples.
1119 /// [type]: union.MaybeUninit.html
1120 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1122 pub const fn uninit() -> MaybeUninit<T> {
1123 MaybeUninit { uninit: () }
1126 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
1127 /// filled with `0` bytes. It depends on `T` whether that already makes for
1128 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
1129 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
1132 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1133 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1137 /// Correct usage of this function: initializing a struct with zero, where all
1138 /// fields of the struct can hold the bit-pattern 0 as a valid value.
1141 /// use std::mem::MaybeUninit;
1143 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
1144 /// let x = unsafe { x.assume_init() };
1145 /// assert_eq!(x, (0, false));
1148 /// *Incorrect* usage of this function: initializing a struct with zero, where some fields
1149 /// cannot hold 0 as a valid value.
1152 /// use std::mem::MaybeUninit;
1154 /// enum NotZero { One = 1, Two = 2 };
1156 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
1157 /// let x = unsafe { x.assume_init() };
1158 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
1159 /// // This is undefined behavior.
1161 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1163 pub fn zeroed() -> MaybeUninit<T> {
1164 let mut u = MaybeUninit::<T>::uninit();
1166 u.as_mut_ptr().write_bytes(0u8, 1);
1171 /// Sets the value of the `MaybeUninit<T>`. This overwrites any previous value
1172 /// without dropping it, so be careful not to use this twice unless you want to
1173 /// skip running the destructor. For your convenience, this also returns a mutable
1174 /// reference to the (now safely initialized) contents of `self`.
1175 #[unstable(feature = "maybe_uninit_extra", issue = "53491")]
1177 pub fn write(&mut self, val: T) -> &mut T {
1179 self.value = ManuallyDrop::new(val);
1184 /// Gets a pointer to the contained value. Reading from this pointer or turning it
1185 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
1186 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
1187 /// (except inside an `UnsafeCell<T>`).
1191 /// Correct usage of this method:
1194 /// use std::mem::MaybeUninit;
1196 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
1197 /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
1198 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
1199 /// let x_vec = unsafe { &*x.as_ptr() };
1200 /// assert_eq!(x_vec.len(), 3);
1203 /// *Incorrect* usage of this method:
1206 /// use std::mem::MaybeUninit;
1208 /// let x = MaybeUninit::<Vec<u32>>::uninit();
1209 /// let x_vec = unsafe { &*x.as_ptr() };
1210 /// // We have created a reference to an uninitialized vector! This is undefined behavior.
1213 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
1214 /// until they are, it is advisable to avoid them.)
1215 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1217 pub fn as_ptr(&self) -> *const T {
1218 unsafe { &*self.value as *const T }
1221 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
1222 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
1226 /// Correct usage of this method:
1229 /// use std::mem::MaybeUninit;
1231 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
1232 /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
1233 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
1234 /// // This is okay because we initialized it.
1235 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1237 /// assert_eq!(x_vec.len(), 4);
1240 /// *Incorrect* usage of this method:
1243 /// use std::mem::MaybeUninit;
1245 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
1246 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1247 /// // We have created a reference to an uninitialized vector! This is undefined behavior.
1250 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
1251 /// until they are, it is advisable to avoid them.)
1252 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1254 pub fn as_mut_ptr(&mut self) -> *mut T {
1255 unsafe { &mut *self.value as *mut T }
1258 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
1259 /// to ensure that the data will get dropped, because the resulting `T` is
1260 /// subject to the usual drop handling.
1264 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1265 /// state. Calling this when the content is not yet fully initialized causes immediate undefined
1266 /// behavior. The [type-level documentation][inv] contains more information about
1267 /// this initialization invariant.
1269 /// [inv]: #initialization-invariant
1273 /// Correct usage of this method:
1276 /// use std::mem::MaybeUninit;
1278 /// let mut x = MaybeUninit::<bool>::uninit();
1279 /// unsafe { x.as_mut_ptr().write(true); }
1280 /// let x_init = unsafe { x.assume_init() };
1281 /// assert_eq!(x_init, true);
1284 /// *Incorrect* usage of this method:
1287 /// use std::mem::MaybeUninit;
1289 /// let x = MaybeUninit::<Vec<u32>>::uninit();
1290 /// let x_init = unsafe { x.assume_init() };
1291 /// // `x` had not been initialized yet, so this last line caused undefined behavior.
1293 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1295 pub unsafe fn assume_init(self) -> T {
1296 intrinsics::panic_if_uninhabited::<T>();
1297 ManuallyDrop::into_inner(self.value)
1300 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
1301 /// to the usual drop handling.
1303 /// Whenever possible, it is preferrable to use [`assume_init`] instead, which
1304 /// prevents duplicating the content of the `MaybeUninit<T>`.
1308 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1309 /// state. Calling this when the content is not yet fully initialized causes undefined
1310 /// behavior. The [type-level documentation][inv] contains more information about
1311 /// this initialization invariant.
1313 /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit<T>`. When using
1314 /// multiple copies of the data (by calling `read` multiple times, or first
1315 /// calling `read` and then [`assume_init`]), it is your responsibility
1316 /// to ensure that that data may indeed be duplicated.
1318 /// [inv]: #initialization-invariant
1319 /// [`assume_init`]: #method.assume_init
1323 /// Correct usage of this method:
1326 /// #![feature(maybe_uninit_extra)]
1327 /// use std::mem::MaybeUninit;
1329 /// let mut x = MaybeUninit::<u32>::uninit();
1331 /// let x1 = unsafe { x.read() };
1332 /// // `u32` is `Copy`, so we may read multiple times.
1333 /// let x2 = unsafe { x.read() };
1334 /// assert_eq!(x1, x2);
1336 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
1338 /// let x1 = unsafe { x.read() };
1339 /// // Duplicating a `None` value is okay, so we may read multiple times.
1340 /// let x2 = unsafe { x.read() };
1341 /// assert_eq!(x1, x2);
1344 /// *Incorrect* usage of this method:
1347 /// #![feature(maybe_uninit_extra)]
1348 /// use std::mem::MaybeUninit;
1350 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
1351 /// x.write(Some(vec![0,1,2]));
1352 /// let x1 = unsafe { x.read() };
1353 /// let x2 = unsafe { x.read() };
1354 /// // We now created two copies of the same vector, leading to a double-free when
1355 /// // they both get dropped!
1357 #[unstable(feature = "maybe_uninit_extra", issue = "53491")]
1359 pub unsafe fn read(&self) -> T {
1360 intrinsics::panic_if_uninhabited::<T>();
1361 self.as_ptr().read()
1364 /// Gets a reference to the contained value.
1368 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1369 /// state. Calling this when the content is not yet fully initialized causes undefined
1371 #[unstable(feature = "maybe_uninit_ref", issue = "53491")]
1373 pub unsafe fn get_ref(&self) -> &T {
1377 /// Gets a mutable reference to the contained value.
1381 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1382 /// state. Calling this when the content is not yet fully initialized causes undefined
1384 // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references
1385 // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make
1386 // a final decision about the rules before stabilization.
1387 #[unstable(feature = "maybe_uninit_ref", issue = "53491")]
1389 pub unsafe fn get_mut(&mut self) -> &mut T {
1393 /// Gets a pointer to the first element of the array.
1394 #[unstable(feature = "maybe_uninit_slice", issue = "53491")]
1396 pub fn first_ptr(this: &[MaybeUninit<T>]) -> *const T {
1397 this as *const [MaybeUninit<T>] as *const T
1400 /// Gets a mutable pointer to the first element of the array.
1401 #[unstable(feature = "maybe_uninit_slice", issue = "53491")]
1403 pub fn first_ptr_mut(this: &mut [MaybeUninit<T>]) -> *mut T {
1404 this as *mut [MaybeUninit<T>] as *mut T