1 use crate::any::type_name;
4 use crate::mem::ManuallyDrop;
7 /// A wrapper type to construct uninitialized instances of `T`.
9 /// # Initialization invariant
11 /// The compiler, in general, assumes that a variable is properly initialized
12 /// according to the requirements of the variable's type. For example, a variable of
13 /// reference type must be aligned and non-null. This is an invariant that must
14 /// *always* be upheld, even in unsafe code. As a consequence, zero-initializing a
15 /// variable of reference type causes instantaneous [undefined behavior][ub],
16 /// no matter whether that reference ever gets used to access memory:
19 /// # #![allow(invalid_value)]
20 /// use std::mem::{self, MaybeUninit};
22 /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior! ⚠️
23 /// // The equivalent code with `MaybeUninit<&i32>`:
24 /// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! ⚠️
27 /// This is exploited by the compiler for various optimizations, such as eliding
28 /// run-time checks and optimizing `enum` layout.
30 /// Similarly, entirely uninitialized memory may have any content, while a `bool` must
31 /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior:
34 /// # #![allow(invalid_value)]
35 /// use std::mem::{self, MaybeUninit};
37 /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
38 /// // The equivalent code with `MaybeUninit<bool>`:
39 /// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
42 /// Moreover, uninitialized memory is special in that it does not have a fixed value ("fixed"
43 /// meaning "it won't change without being written to"). Reading the same uninitialized byte
44 /// multiple times can give different results. This makes it undefined behavior to have
45 /// uninitialized data in a variable even if that variable has an integer type, which otherwise can
46 /// hold any *fixed* bit pattern:
49 /// # #![allow(invalid_value)]
50 /// use std::mem::{self, MaybeUninit};
52 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
53 /// // The equivalent code with `MaybeUninit<i32>`:
54 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
56 /// (Notice that the rules around uninitialized integers are not finalized yet, but
57 /// until they are, it is advisable to avoid them.)
59 /// On top of that, remember that most types have additional invariants beyond merely
60 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
61 /// is considered initialized (under the current implementation; this does not constitute
62 /// a stable guarantee) because the only requirement the compiler knows about it
63 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
64 /// *immediate* undefined behavior, but will cause undefined behavior with most
65 /// safe operations (including dropping it).
67 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
71 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
72 /// It is a signal to the compiler indicating that the data here might *not*
76 /// use std::mem::MaybeUninit;
78 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
79 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
80 /// let mut x = MaybeUninit::<&i32>::uninit();
81 /// // Set it to a valid value.
82 /// unsafe { x.as_mut_ptr().write(&0); }
83 /// // Extract the initialized data -- this is only allowed *after* properly
84 /// // initializing `x`!
85 /// let x = unsafe { x.assume_init() };
88 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
90 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without
91 /// any of the run-time tracking and without any of the safety checks.
95 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
96 /// from a function, pass it a pointer to some (uninitialized) memory to put the
97 /// result into. This can be useful when it is important for the caller to control
98 /// how the memory the result is stored in gets allocated, and you want to avoid
99 /// unnecessary moves.
102 /// use std::mem::MaybeUninit;
104 /// unsafe fn make_vec(out: *mut Vec<i32>) {
105 /// // `write` does not drop the old contents, which is important.
106 /// out.write(vec![1, 2, 3]);
109 /// let mut v = MaybeUninit::uninit();
110 /// unsafe { make_vec(v.as_mut_ptr()); }
111 /// // Now we know `v` is initialized! This also makes sure the vector gets
112 /// // properly dropped.
113 /// let v = unsafe { v.assume_init() };
114 /// assert_eq!(&v, &[1, 2, 3]);
117 /// ## Initializing an array element-by-element
119 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
122 /// use std::mem::{self, MaybeUninit};
125 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
126 /// // safe because the type we are claiming to have initialized here is a
127 /// // bunch of `MaybeUninit`s, which do not require initialization.
128 /// let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
129 /// MaybeUninit::uninit().assume_init()
132 /// // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
133 /// // assignment instead of `ptr::write` does not cause the old
134 /// // uninitialized value to be dropped. Also if there is a panic during
135 /// // this loop, we have a memory leak, but there is no memory safety
137 /// for elem in &mut data[..] {
138 /// *elem = MaybeUninit::new(vec![42]);
141 /// // Everything is initialized. Transmute the array to the
142 /// // initialized type.
143 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
146 /// assert_eq!(&data[0], &[42]);
149 /// You can also work with partially initialized arrays, which could
150 /// be found in low-level datastructures.
153 /// use std::mem::MaybeUninit;
156 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
157 /// // safe because the type we are claiming to have initialized here is a
158 /// // bunch of `MaybeUninit`s, which do not require initialization.
159 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
160 /// // Count the number of elements we have assigned.
161 /// let mut data_len: usize = 0;
163 /// for elem in &mut data[0..500] {
164 /// *elem = MaybeUninit::new(String::from("hello"));
168 /// // For each item in the array, drop if we allocated it.
169 /// for elem in &mut data[0..data_len] {
170 /// unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
174 /// ## Initializing a struct field-by-field
176 /// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field:
179 /// use std::mem::MaybeUninit;
180 /// use std::ptr::addr_of_mut;
182 /// #[derive(Debug, PartialEq)]
189 /// let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
190 /// let ptr = uninit.as_mut_ptr();
192 /// // Initializing the `name` field
193 /// // Using `write` instead of assignment via `=` to not call `drop` on the
194 /// // old, uninitialized value.
195 /// unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); }
197 /// // Initializing the `list` field
198 /// // If there is a panic here, then the `String` in the `name` field leaks.
199 /// unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); }
201 /// // All the fields are initialized, so we call `assume_init` to get an initialized Foo.
202 /// unsafe { uninit.assume_init() }
208 /// name: "Bob".to_string(),
209 /// list: vec![0, 1, 2]
213 /// [`std::ptr::addr_of_mut`]: crate::ptr::addr_of_mut
214 /// [ub]: ../../reference/behavior-considered-undefined.html
218 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
221 /// use std::mem::{MaybeUninit, size_of, align_of};
222 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
223 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
226 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
227 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
228 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
229 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
230 /// optimizations, potentially resulting in a larger size:
233 /// # use std::mem::{MaybeUninit, size_of};
234 /// assert_eq!(size_of::<Option<bool>>(), 1);
235 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
238 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
240 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
241 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
242 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
243 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
244 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
245 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
246 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
247 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
248 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
249 /// guarantee may evolve.
250 #[stable(feature = "maybe_uninit", since = "1.36.0")]
251 // Lang item so we can wrap other types in it. This is useful for generators.
252 #[lang = "maybe_uninit"]
255 pub union MaybeUninit<T> {
257 value: ManuallyDrop<T>,
260 #[stable(feature = "maybe_uninit", since = "1.36.0")]
261 impl<T: Copy> Clone for MaybeUninit<T> {
263 fn clone(&self) -> Self {
264 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
269 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
270 impl<T> fmt::Debug for MaybeUninit<T> {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 f.pad(type_name::<Self>())
276 impl<T> MaybeUninit<T> {
277 /// Creates a new `MaybeUninit<T>` initialized with the given value.
278 /// It is safe to call [`assume_init`] on the return value of this function.
280 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
281 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
286 /// use std::mem::MaybeUninit;
288 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
291 /// [`assume_init`]: MaybeUninit::assume_init
292 #[stable(feature = "maybe_uninit", since = "1.36.0")]
293 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
295 pub const fn new(val: T) -> MaybeUninit<T> {
296 MaybeUninit { value: ManuallyDrop::new(val) }
299 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
301 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
302 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
304 /// See the [type-level documentation][MaybeUninit] for some examples.
309 /// use std::mem::MaybeUninit;
311 /// let v: MaybeUninit<String> = MaybeUninit::uninit();
313 #[stable(feature = "maybe_uninit", since = "1.36.0")]
314 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
316 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
317 pub const fn uninit() -> MaybeUninit<T> {
318 MaybeUninit { uninit: () }
321 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
323 /// Note: in a future Rust version this method may become unnecessary
325 /// [inline const expressions](https://github.com/rust-lang/rust/issues/76001).
326 /// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
331 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
333 /// use std::mem::MaybeUninit;
336 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
339 /// /// Returns a (possibly smaller) slice of data that was actually read
340 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
342 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
343 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
347 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
348 /// let data = read(&mut buf);
350 #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
351 #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
353 pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
354 // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
355 unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
358 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
359 /// filled with `0` bytes. It depends on `T` whether that already makes for
360 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
361 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
364 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
365 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
369 /// Correct usage of this function: initializing a struct with zero, where all
370 /// fields of the struct can hold the bit-pattern 0 as a valid value.
373 /// use std::mem::MaybeUninit;
375 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
376 /// let x = unsafe { x.assume_init() };
377 /// assert_eq!(x, (0, false));
380 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
381 /// when `0` is not a valid bit-pattern for the type:
384 /// use std::mem::MaybeUninit;
386 /// enum NotZero { One = 1, Two = 2 }
388 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
389 /// let x = unsafe { x.assume_init() };
390 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
391 /// // This is undefined behavior. ⚠️
393 #[stable(feature = "maybe_uninit", since = "1.36.0")]
395 #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
396 pub fn zeroed() -> MaybeUninit<T> {
397 let mut u = MaybeUninit::<T>::uninit();
398 // SAFETY: `u.as_mut_ptr()` points to allocated memory.
400 u.as_mut_ptr().write_bytes(0u8, 1);
405 /// Sets the value of the `MaybeUninit<T>`.
407 /// This overwrites any previous value without dropping it, so be careful
408 /// not to use this twice unless you want to skip running the destructor.
409 /// For your convenience, this also returns a mutable reference to the
410 /// (now safely initialized) contents of `self`.
412 /// As the content is stored inside a `MaybeUninit`, the destructor is not
413 /// ran for the inner data if the MaybeUninit leaves scope without a call to
414 /// [`assume_init`], [`assume_init_drop`], or similar. Code that receives
415 /// the mutable reference returned by this function needs to keep this in
416 /// mind. The safety model of Rust regards leaks as safe, but they are
417 /// usually still undesirable. This being said, the mutable reference
418 /// behaves like any other mutable reference would, so assigning a new value
419 /// to it will drop the old content.
421 /// [`assume_init`]: Self::assume_init
422 /// [`assume_init_drop`]: Self::assume_init_drop
426 /// Correct usage of this method:
429 /// #![feature(maybe_uninit_extra)]
430 /// use std::mem::MaybeUninit;
432 /// let mut x = MaybeUninit::<Vec<u8>>::uninit();
435 /// let hello = x.write((&b"Hello, world!").to_vec());
436 /// // Setting hello does not leak prior allocations, but drops them
437 /// *hello = (&b"Hello").to_vec();
438 /// hello[0] = 'h' as u8;
440 /// // x is initialized now:
441 /// let s = unsafe { x.assume_init() };
442 /// assert_eq!(b"hello", s.as_slice());
445 /// This usage of the method causes a leak:
448 /// #![feature(maybe_uninit_extra)]
449 /// use std::mem::MaybeUninit;
451 /// let mut x = MaybeUninit::<String>::uninit();
453 /// x.write("Hello".to_string());
454 /// // This leaks the contained string:
455 /// x.write("hello".to_string());
456 /// // x is initialized now:
457 /// let s = unsafe { x.assume_init() };
459 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
460 #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
462 pub const fn write(&mut self, val: T) -> &mut T {
463 *self = MaybeUninit::new(val);
464 // SAFETY: We just initialized this value.
465 unsafe { self.assume_init_mut() }
468 /// Gets a pointer to the contained value. Reading from this pointer or turning it
469 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
470 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
471 /// (except inside an `UnsafeCell<T>`).
475 /// Correct usage of this method:
478 /// use std::mem::MaybeUninit;
480 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
481 /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
482 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
483 /// let x_vec = unsafe { &*x.as_ptr() };
484 /// assert_eq!(x_vec.len(), 3);
487 /// *Incorrect* usage of this method:
490 /// use std::mem::MaybeUninit;
492 /// let x = MaybeUninit::<Vec<u32>>::uninit();
493 /// let x_vec = unsafe { &*x.as_ptr() };
494 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
497 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
498 /// until they are, it is advisable to avoid them.)
499 #[stable(feature = "maybe_uninit", since = "1.36.0")]
500 #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
502 pub const fn as_ptr(&self) -> *const T {
503 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
504 self as *const _ as *const T
507 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
508 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
512 /// Correct usage of this method:
515 /// use std::mem::MaybeUninit;
517 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
518 /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
519 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
520 /// // This is okay because we initialized it.
521 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
523 /// assert_eq!(x_vec.len(), 4);
526 /// *Incorrect* usage of this method:
529 /// use std::mem::MaybeUninit;
531 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
532 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
533 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
536 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
537 /// until they are, it is advisable to avoid them.)
538 #[stable(feature = "maybe_uninit", since = "1.36.0")]
539 #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
541 pub const fn as_mut_ptr(&mut self) -> *mut T {
542 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
543 self as *mut _ as *mut T
546 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
547 /// to ensure that the data will get dropped, because the resulting `T` is
548 /// subject to the usual drop handling.
552 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
553 /// state. Calling this when the content is not yet fully initialized causes immediate undefined
554 /// behavior. The [type-level documentation][inv] contains more information about
555 /// this initialization invariant.
557 /// [inv]: #initialization-invariant
559 /// On top of that, remember that most types have additional invariants beyond merely
560 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
561 /// is considered initialized (under the current implementation; this does not constitute
562 /// a stable guarantee) because the only requirement the compiler knows about it
563 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
564 /// *immediate* undefined behavior, but will cause undefined behavior with most
565 /// safe operations (including dropping it).
567 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
571 /// Correct usage of this method:
574 /// use std::mem::MaybeUninit;
576 /// let mut x = MaybeUninit::<bool>::uninit();
577 /// unsafe { x.as_mut_ptr().write(true); }
578 /// let x_init = unsafe { x.assume_init() };
579 /// assert_eq!(x_init, true);
582 /// *Incorrect* usage of this method:
585 /// use std::mem::MaybeUninit;
587 /// let x = MaybeUninit::<Vec<u32>>::uninit();
588 /// let x_init = unsafe { x.assume_init() };
589 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
591 #[stable(feature = "maybe_uninit", since = "1.36.0")]
592 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
594 #[rustc_diagnostic_item = "assume_init"]
595 pub const unsafe fn assume_init(self) -> T {
596 // SAFETY: the caller must guarantee that `self` is initialized.
597 // This also means that `self` must be a `value` variant.
599 intrinsics::assert_inhabited::<T>();
600 ManuallyDrop::into_inner(self.value)
604 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
605 /// to the usual drop handling.
607 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
608 /// prevents duplicating the content of the `MaybeUninit<T>`.
612 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
613 /// state. Calling this when the content is not yet fully initialized causes undefined
614 /// behavior. The [type-level documentation][inv] contains more information about
615 /// this initialization invariant.
617 /// Moreover, similar to the [`ptr::read`] function, this function creates a
618 /// bitwise copy of the contents, regardless whether the contained type
619 /// implements the [`Copy`] trait or not. When using multiple copies of the
620 /// data (by calling `assume_init_read` multiple times, or first calling
621 /// `assume_init_read` and then [`assume_init`]), it is your responsibility
622 /// to ensure that that data may indeed be duplicated.
624 /// [inv]: #initialization-invariant
625 /// [`assume_init`]: MaybeUninit::assume_init
629 /// Correct usage of this method:
632 /// #![feature(maybe_uninit_extra)]
633 /// use std::mem::MaybeUninit;
635 /// let mut x = MaybeUninit::<u32>::uninit();
637 /// let x1 = unsafe { x.assume_init_read() };
638 /// // `u32` is `Copy`, so we may read multiple times.
639 /// let x2 = unsafe { x.assume_init_read() };
640 /// assert_eq!(x1, x2);
642 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
644 /// let x1 = unsafe { x.assume_init_read() };
645 /// // Duplicating a `None` value is okay, so we may read multiple times.
646 /// let x2 = unsafe { x.assume_init_read() };
647 /// assert_eq!(x1, x2);
650 /// *Incorrect* usage of this method:
653 /// #![feature(maybe_uninit_extra)]
654 /// use std::mem::MaybeUninit;
656 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
657 /// x.write(Some(vec![0, 1, 2]));
658 /// let x1 = unsafe { x.assume_init_read() };
659 /// let x2 = unsafe { x.assume_init_read() };
660 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
661 /// // they both get dropped!
663 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
664 #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
666 pub const unsafe fn assume_init_read(&self) -> T {
667 // SAFETY: the caller must guarantee that `self` is initialized.
668 // Reading from `self.as_ptr()` is safe since `self` should be initialized.
670 intrinsics::assert_inhabited::<T>();
675 /// Drops the contained value in place.
677 /// If you have ownership of the `MaybeUninit`, you can also use
678 /// [`assume_init`] as an alternative.
682 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
683 /// in an initialized state. Calling this when the content is not yet fully
684 /// initialized causes undefined behavior.
686 /// On top of that, all additional invariants of the type `T` must be
687 /// satisfied, as the `Drop` implementation of `T` (or its members) may
688 /// rely on this. For example, setting a [`Vec<T>`] to an invalid but
689 /// non-null address makes it initialized (under the current implementation;
690 /// this does not constitute a stable guarantee), because the only
691 /// requirement the compiler knows about it is that the data pointer must be
692 /// non-null. Dropping such a `Vec<T>` however will cause undefined
695 /// [`assume_init`]: MaybeUninit::assume_init
696 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
697 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
698 pub unsafe fn assume_init_drop(&mut self) {
699 // SAFETY: the caller must guarantee that `self` is initialized and
700 // satisfies all invariants of `T`.
701 // Dropping the value in place is safe if that is the case.
702 unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
705 /// Gets a shared reference to the contained value.
707 /// This can be useful when we want to access a `MaybeUninit` that has been
708 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
709 /// of `.assume_init()`).
713 /// Calling this when the content is not yet fully initialized causes undefined
714 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
715 /// is in an initialized state.
719 /// ### Correct usage of this method:
722 /// use std::mem::MaybeUninit;
724 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
725 /// // Initialize `x`:
726 /// unsafe { x.as_mut_ptr().write(vec![1, 2, 3]); }
727 /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
728 /// // create a shared reference to it:
729 /// let x: &Vec<u32> = unsafe {
730 /// // SAFETY: `x` has been initialized.
731 /// x.assume_init_ref()
733 /// assert_eq!(x, &vec![1, 2, 3]);
736 /// ### *Incorrect* usages of this method:
739 /// use std::mem::MaybeUninit;
741 /// let x = MaybeUninit::<Vec<u32>>::uninit();
742 /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
743 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
747 /// use std::{cell::Cell, mem::MaybeUninit};
749 /// let b = MaybeUninit::<Cell<bool>>::uninit();
750 /// // Initialize the `MaybeUninit` using `Cell::set`:
752 /// b.assume_init_ref().set(true);
753 /// // ^^^^^^^^^^^^^^^
754 /// // Reference to an uninitialized `Cell<bool>`: UB!
757 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
758 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
760 pub const unsafe fn assume_init_ref(&self) -> &T {
761 // SAFETY: the caller must guarantee that `self` is initialized.
762 // This also means that `self` must be a `value` variant.
764 intrinsics::assert_inhabited::<T>();
769 /// Gets a mutable (unique) reference to the contained value.
771 /// This can be useful when we want to access a `MaybeUninit` that has been
772 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
773 /// of `.assume_init()`).
777 /// Calling this when the content is not yet fully initialized causes undefined
778 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
779 /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
780 /// initialize a `MaybeUninit`.
784 /// ### Correct usage of this method:
787 /// use std::mem::MaybeUninit;
789 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] }
792 /// /// Initializes *all* the bytes of the input buffer.
793 /// fn initialize_buffer(buf: *mut [u8; 1024]);
796 /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
798 /// // Initialize `buf`:
799 /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
800 /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
801 /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes.
802 /// // To assert our buffer has been initialized without copying it, we upgrade
803 /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`:
804 /// let buf: &mut [u8; 1024] = unsafe {
805 /// // SAFETY: `buf` has been initialized.
806 /// buf.assume_init_mut()
809 /// // Now we can use `buf` as a normal slice:
810 /// buf.sort_unstable();
812 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
813 /// "buffer is sorted",
817 /// ### *Incorrect* usages of this method:
819 /// You cannot use `.assume_init_mut()` to initialize a value:
822 /// use std::mem::MaybeUninit;
824 /// let mut b = MaybeUninit::<bool>::uninit();
826 /// *b.assume_init_mut() = true;
827 /// // We have created a (mutable) reference to an uninitialized `bool`!
828 /// // This is undefined behavior. ⚠️
832 /// For instance, you cannot [`Read`] into an uninitialized buffer:
834 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
837 /// use std::{io, mem::MaybeUninit};
839 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
841 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
842 /// reader.read_exact(unsafe { buffer.assume_init_mut() })?;
843 /// // ^^^^^^^^^^^^^^^^^^^^^^^^
844 /// // (mutable) reference to uninitialized memory!
845 /// // This is undefined behavior.
846 /// Ok(unsafe { buffer.assume_init() })
850 /// Nor can you use direct field access to do field-by-field gradual initialization:
853 /// use std::{mem::MaybeUninit, ptr};
860 /// let foo: Foo = unsafe {
861 /// let mut foo = MaybeUninit::<Foo>::uninit();
862 /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
863 /// // ^^^^^^^^^^^^^^^^^^^^^
864 /// // (mutable) reference to uninitialized memory!
865 /// // This is undefined behavior.
866 /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
867 /// // ^^^^^^^^^^^^^^^^^^^^^
868 /// // (mutable) reference to uninitialized memory!
869 /// // This is undefined behavior.
870 /// foo.assume_init()
873 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
874 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
876 pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
877 // SAFETY: the caller must guarantee that `self` is initialized.
878 // This also means that `self` must be a `value` variant.
880 intrinsics::assert_inhabited::<T>();
881 &mut *self.as_mut_ptr()
885 /// Extracts the values from an array of `MaybeUninit` containers.
889 /// It is up to the caller to guarantee that all elements of the array are
890 /// in an initialized state.
895 /// #![feature(maybe_uninit_uninit_array)]
896 /// #![feature(maybe_uninit_array_assume_init)]
897 /// use std::mem::MaybeUninit;
899 /// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
900 /// array[0] = MaybeUninit::new(0);
901 /// array[1] = MaybeUninit::new(1);
902 /// array[2] = MaybeUninit::new(2);
904 /// // SAFETY: Now safe as we initialised all elements
905 /// let array = unsafe {
906 /// MaybeUninit::array_assume_init(array)
909 /// assert_eq!(array, [0, 1, 2]);
911 #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
913 pub unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
915 // * The caller guarantees that all elements of the array are initialized
916 // * `MaybeUninit<T>` and T are guaranteed to have the same layout
917 // * `MaybeUninit` does not drop, so there are no double-frees
918 // And thus the conversion is safe
920 intrinsics::assert_inhabited::<[T; N]>();
921 (&array as *const _ as *const [T; N]).read()
925 /// Assuming all the elements are initialized, get a slice to them.
929 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
930 /// really are in an initialized state.
931 /// Calling this when the content is not yet fully initialized causes undefined behavior.
933 /// See [`assume_init_ref`] for more details and examples.
935 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
936 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
937 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
939 pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
940 // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
941 // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
942 // The pointer obtained is valid since it refers to memory owned by `slice` which is a
943 // reference and thus guaranteed to be valid for reads.
944 unsafe { &*(slice as *const [Self] as *const [T]) }
947 /// Assuming all the elements are initialized, get a mutable slice to them.
951 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
952 /// really are in an initialized state.
953 /// Calling this when the content is not yet fully initialized causes undefined behavior.
955 /// See [`assume_init_mut`] for more details and examples.
957 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
958 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
959 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
961 pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
962 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
963 // mutable reference which is also guaranteed to be valid for writes.
964 unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
967 /// Gets a pointer to the first element of the array.
968 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
969 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
971 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
972 this.as_ptr() as *const T
975 /// Gets a mutable pointer to the first element of the array.
976 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
977 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
979 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
980 this.as_mut_ptr() as *mut T
983 /// Copies the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
985 /// If `T` does not implement `Copy`, use [`write_slice_cloned`]
987 /// This is similar to [`slice::copy_from_slice`].
991 /// This function will panic if the two slices have different lengths.
996 /// #![feature(maybe_uninit_write_slice)]
997 /// use std::mem::MaybeUninit;
999 /// let mut dst = [MaybeUninit::uninit(); 32];
1000 /// let src = [0; 32];
1002 /// let init = MaybeUninit::write_slice(&mut dst, &src);
1004 /// assert_eq!(init, src);
1008 /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
1009 /// use std::mem::MaybeUninit;
1011 /// let mut vec = Vec::with_capacity(32);
1012 /// let src = [0; 16];
1014 /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);
1016 /// // SAFETY: we have just copied all the elements of len into the spare capacity
1017 /// // the first src.len() elements of the vec are valid now.
1019 /// vec.set_len(src.len());
1022 /// assert_eq!(vec, src);
1025 /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned
1026 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1027 pub fn write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1031 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1032 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1034 this.copy_from_slice(uninit_src);
1036 // SAFETY: Valid elements have just been copied into `this` so it is initialized
1037 unsafe { MaybeUninit::slice_assume_init_mut(this) }
1040 /// Clones the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
1041 /// Any already initialized elements will not be dropped.
1043 /// If `T` implements `Copy`, use [`write_slice`]
1045 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1049 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1051 /// If there is a panic, the already cloned elements will be dropped.
1056 /// #![feature(maybe_uninit_write_slice)]
1057 /// use std::mem::MaybeUninit;
1059 /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()];
1060 /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()];
1062 /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src);
1064 /// assert_eq!(init, src);
1068 /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
1069 /// use std::mem::MaybeUninit;
1071 /// let mut vec = Vec::with_capacity(32);
1072 /// let src = ["rust", "is", "a", "pretty", "cool", "language"];
1074 /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src);
1076 /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1077 /// // the first src.len() elements of the vec are valid now.
1079 /// vec.set_len(src.len());
1082 /// assert_eq!(vec, src);
1085 /// [`write_slice`]: MaybeUninit::write_slice
1086 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1087 pub fn write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1091 // unlike copy_from_slice this does not call clone_from_slice on the slice
1092 // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1094 struct Guard<'a, T> {
1095 slice: &'a mut [MaybeUninit<T>],
1099 impl<'a, T> Drop for Guard<'a, T> {
1100 fn drop(&mut self) {
1101 let initialized_part = &mut self.slice[..self.initialized];
1102 // SAFETY: this raw slice will contain only initialized objects
1103 // that's why, it is allowed to drop it.
1105 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part));
1110 assert_eq!(this.len(), src.len(), "destination and source slices have different lengths");
1111 // NOTE: We need to explicitly slice them to the same length
1112 // for bounds checking to be elided, and the optimizer will
1113 // generate memcpy for simple cases (for example T = u8).
1114 let len = this.len();
1115 let src = &src[..len];
1117 // guard is needed b/c panic might happen during a clone
1118 let mut guard = Guard { slice: this, initialized: 0 };
1121 guard.slice[i].write(src[i].clone());
1122 guard.initialized += 1;
1125 super::forget(guard);
1127 // SAFETY: Valid elements have just been written into `this` so it is initialized
1128 unsafe { MaybeUninit::slice_assume_init_mut(this) }