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 the compiler knows that
43 /// it does not have a fixed value. This makes it undefined behavior to have
44 /// uninitialized data in a variable even if that variable has an integer type,
45 /// which otherwise can hold any *fixed* bit pattern:
48 /// # #![allow(invalid_value)]
49 /// use std::mem::{self, MaybeUninit};
51 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
52 /// // The equivalent code with `MaybeUninit<i32>`:
53 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
55 /// (Notice that the rules around uninitialized integers are not finalized yet, but
56 /// until they are, it is advisable to avoid them.)
58 /// On top of that, remember that most types have additional invariants beyond merely
59 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
60 /// is considered initialized (under the current implementation; this does not constitute
61 /// a stable guarantee) because the only requirement the compiler knows about it
62 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
63 /// *immediate* undefined behavior, but will cause undefined behavior with most
64 /// safe operations (including dropping it).
66 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
70 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
71 /// It is a signal to the compiler indicating that the data here might *not*
75 /// use std::mem::MaybeUninit;
77 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
78 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
79 /// let mut x = MaybeUninit::<&i32>::uninit();
80 /// // Set it to a valid value.
81 /// unsafe { x.as_mut_ptr().write(&0); }
82 /// // Extract the initialized data -- this is only allowed *after* properly
83 /// // initializing `x`!
84 /// let x = unsafe { x.assume_init() };
87 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
89 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without
90 /// any of the run-time tracking and without any of the safety checks.
94 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
95 /// from a function, pass it a pointer to some (uninitialized) memory to put the
96 /// result into. This can be useful when it is important for the caller to control
97 /// how the memory the result is stored in gets allocated, and you want to avoid
98 /// unnecessary moves.
101 /// use std::mem::MaybeUninit;
103 /// unsafe fn make_vec(out: *mut Vec<i32>) {
104 /// // `write` does not drop the old contents, which is important.
105 /// out.write(vec![1, 2, 3]);
108 /// let mut v = MaybeUninit::uninit();
109 /// unsafe { make_vec(v.as_mut_ptr()); }
110 /// // Now we know `v` is initialized! This also makes sure the vector gets
111 /// // properly dropped.
112 /// let v = unsafe { v.assume_init() };
113 /// assert_eq!(&v, &[1, 2, 3]);
116 /// ## Initializing an array element-by-element
118 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
121 /// use std::mem::{self, MaybeUninit};
124 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
125 /// // safe because the type we are claiming to have initialized here is a
126 /// // bunch of `MaybeUninit`s, which do not require initialization.
127 /// let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
128 /// MaybeUninit::uninit().assume_init()
131 /// // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
132 /// // assignment instead of `ptr::write` does not cause the old
133 /// // uninitialized value to be dropped. Also if there is a panic during
134 /// // this loop, we have a memory leak, but there is no memory safety
136 /// for elem in &mut data[..] {
137 /// *elem = MaybeUninit::new(vec![42]);
140 /// // Everything is initialized. Transmute the array to the
141 /// // initialized type.
142 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
145 /// assert_eq!(&data[0], &[42]);
148 /// You can also work with partially initialized arrays, which could
149 /// be found in low-level datastructures.
152 /// use std::mem::MaybeUninit;
155 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
156 /// // safe because the type we are claiming to have initialized here is a
157 /// // bunch of `MaybeUninit`s, which do not require initialization.
158 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
159 /// // Count the number of elements we have assigned.
160 /// let mut data_len: usize = 0;
162 /// for elem in &mut data[0..500] {
163 /// *elem = MaybeUninit::new(String::from("hello"));
167 /// // For each item in the array, drop if we allocated it.
168 /// for elem in &mut data[0..data_len] {
169 /// unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
173 /// ## Initializing a struct field-by-field
175 /// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field:
178 /// use std::mem::MaybeUninit;
179 /// use std::ptr::addr_of_mut;
181 /// #[derive(Debug, PartialEq)]
188 /// let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
189 /// let ptr = uninit.as_mut_ptr();
191 /// // Initializing the `name` field
192 /// unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); }
194 /// // Initializing the `list` field
195 /// // If there is a panic here, then the `String` in the `name` field leaks.
196 /// unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); }
198 /// // All the fields are initialized, so we call `assume_init` to get an initialized Foo.
199 /// unsafe { uninit.assume_init() }
205 /// name: "Bob".to_string(),
206 /// list: vec![0, 1, 2]
210 /// [`std::ptr::addr_of_mut`]: crate::ptr::addr_of_mut
211 /// [ub]: ../../reference/behavior-considered-undefined.html
215 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
218 /// use std::mem::{MaybeUninit, size_of, align_of};
219 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
220 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
223 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
224 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
225 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
226 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
227 /// optimizations, potentially resulting in a larger size:
230 /// # use std::mem::{MaybeUninit, size_of};
231 /// assert_eq!(size_of::<Option<bool>>(), 1);
232 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
235 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
237 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
238 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
239 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
240 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
241 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
242 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
243 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
244 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
245 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
246 /// guarantee may evolve.
247 #[stable(feature = "maybe_uninit", since = "1.36.0")]
248 // Lang item so we can wrap other types in it. This is useful for generators.
249 #[lang = "maybe_uninit"]
252 pub union MaybeUninit<T> {
254 value: ManuallyDrop<T>,
257 #[stable(feature = "maybe_uninit", since = "1.36.0")]
258 impl<T: Copy> Clone for MaybeUninit<T> {
260 fn clone(&self) -> Self {
261 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
266 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
267 impl<T> fmt::Debug for MaybeUninit<T> {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 f.pad(type_name::<Self>())
273 impl<T> MaybeUninit<T> {
274 /// Creates a new `MaybeUninit<T>` initialized with the given value.
275 /// It is safe to call [`assume_init`] on the return value of this function.
277 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
278 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
283 /// use std::mem::MaybeUninit;
285 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
288 /// [`assume_init`]: MaybeUninit::assume_init
289 #[stable(feature = "maybe_uninit", since = "1.36.0")]
290 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
292 pub const fn new(val: T) -> MaybeUninit<T> {
293 MaybeUninit { value: ManuallyDrop::new(val) }
296 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
298 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
299 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
301 /// See the [type-level documentation][MaybeUninit] for some examples.
306 /// use std::mem::MaybeUninit;
308 /// let v: MaybeUninit<String> = MaybeUninit::uninit();
310 #[stable(feature = "maybe_uninit", since = "1.36.0")]
311 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
313 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
314 pub const fn uninit() -> MaybeUninit<T> {
315 MaybeUninit { uninit: () }
318 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
320 /// Note: in a future Rust version this method may become unnecessary
321 /// when array literal syntax allows
322 /// [repeating const expressions](https://github.com/rust-lang/rust/issues/49147).
323 /// The example below could then use `let mut buf = [MaybeUninit::<u8>::uninit(); 32];`.
328 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
330 /// use std::mem::MaybeUninit;
333 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
336 /// /// Returns a (possibly smaller) slice of data that was actually read
337 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
339 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
340 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
344 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
345 /// let data = read(&mut buf);
347 #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
348 #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
350 pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
351 // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
352 unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
355 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
356 /// filled with `0` bytes. It depends on `T` whether that already makes for
357 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
358 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
361 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
362 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
366 /// Correct usage of this function: initializing a struct with zero, where all
367 /// fields of the struct can hold the bit-pattern 0 as a valid value.
370 /// use std::mem::MaybeUninit;
372 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
373 /// let x = unsafe { x.assume_init() };
374 /// assert_eq!(x, (0, false));
377 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
378 /// when `0` is not a valid bit-pattern for the type:
381 /// use std::mem::MaybeUninit;
383 /// enum NotZero { One = 1, Two = 2 }
385 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
386 /// let x = unsafe { x.assume_init() };
387 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
388 /// // This is undefined behavior. ⚠️
390 #[stable(feature = "maybe_uninit", since = "1.36.0")]
392 #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
393 pub fn zeroed() -> MaybeUninit<T> {
394 let mut u = MaybeUninit::<T>::uninit();
395 // SAFETY: `u.as_mut_ptr()` points to allocated memory.
397 u.as_mut_ptr().write_bytes(0u8, 1);
402 /// Sets the value of the `MaybeUninit<T>`. This overwrites any previous value
403 /// without dropping it, so be careful not to use this twice unless you want to
404 /// skip running the destructor. For your convenience, this also returns a mutable
405 /// reference to the (now safely initialized) contents of `self`.
406 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
407 #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
409 pub const fn write(&mut self, val: T) -> &mut T {
410 *self = MaybeUninit::new(val);
411 // SAFETY: We just initialized this value.
412 unsafe { self.assume_init_mut() }
415 /// Gets a pointer to the contained value. Reading from this pointer or turning it
416 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
417 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
418 /// (except inside an `UnsafeCell<T>`).
422 /// Correct usage of this method:
425 /// use std::mem::MaybeUninit;
427 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
428 /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
429 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
430 /// let x_vec = unsafe { &*x.as_ptr() };
431 /// assert_eq!(x_vec.len(), 3);
434 /// *Incorrect* usage of this method:
437 /// use std::mem::MaybeUninit;
439 /// let x = MaybeUninit::<Vec<u32>>::uninit();
440 /// let x_vec = unsafe { &*x.as_ptr() };
441 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
444 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
445 /// until they are, it is advisable to avoid them.)
446 #[stable(feature = "maybe_uninit", since = "1.36.0")]
447 #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
449 pub const fn as_ptr(&self) -> *const T {
450 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
451 self as *const _ as *const T
454 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
455 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
459 /// Correct usage of this method:
462 /// use std::mem::MaybeUninit;
464 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
465 /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
466 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
467 /// // This is okay because we initialized it.
468 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
470 /// assert_eq!(x_vec.len(), 4);
473 /// *Incorrect* usage of this method:
476 /// use std::mem::MaybeUninit;
478 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
479 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
480 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
483 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
484 /// until they are, it is advisable to avoid them.)
485 #[stable(feature = "maybe_uninit", since = "1.36.0")]
486 #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
488 pub const fn as_mut_ptr(&mut self) -> *mut T {
489 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
490 self as *mut _ as *mut T
493 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
494 /// to ensure that the data will get dropped, because the resulting `T` is
495 /// subject to the usual drop handling.
499 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
500 /// state. Calling this when the content is not yet fully initialized causes immediate undefined
501 /// behavior. The [type-level documentation][inv] contains more information about
502 /// this initialization invariant.
504 /// [inv]: #initialization-invariant
506 /// On top of that, remember that most types have additional invariants beyond merely
507 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
508 /// is considered initialized (under the current implementation; this does not constitute
509 /// a stable guarantee) because the only requirement the compiler knows about it
510 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
511 /// *immediate* undefined behavior, but will cause undefined behavior with most
512 /// safe operations (including dropping it).
514 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
518 /// Correct usage of this method:
521 /// use std::mem::MaybeUninit;
523 /// let mut x = MaybeUninit::<bool>::uninit();
524 /// unsafe { x.as_mut_ptr().write(true); }
525 /// let x_init = unsafe { x.assume_init() };
526 /// assert_eq!(x_init, true);
529 /// *Incorrect* usage of this method:
532 /// use std::mem::MaybeUninit;
534 /// let x = MaybeUninit::<Vec<u32>>::uninit();
535 /// let x_init = unsafe { x.assume_init() };
536 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
538 #[stable(feature = "maybe_uninit", since = "1.36.0")]
539 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
541 #[rustc_diagnostic_item = "assume_init"]
542 pub const unsafe fn assume_init(self) -> T {
543 // SAFETY: the caller must guarantee that `self` is initialized.
544 // This also means that `self` must be a `value` variant.
546 intrinsics::assert_inhabited::<T>();
547 ManuallyDrop::into_inner(self.value)
551 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
552 /// to the usual drop handling.
554 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
555 /// prevents duplicating the content of the `MaybeUninit<T>`.
559 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
560 /// state. Calling this when the content is not yet fully initialized causes undefined
561 /// behavior. The [type-level documentation][inv] contains more information about
562 /// this initialization invariant.
564 /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit<T>`. When using
565 /// multiple copies of the data (by calling `assume_init_read` multiple times, or first
566 /// calling `assume_init_read` and then [`assume_init`]), it is your responsibility
567 /// to ensure that that data may indeed be duplicated.
569 /// [inv]: #initialization-invariant
570 /// [`assume_init`]: MaybeUninit::assume_init
574 /// Correct usage of this method:
577 /// #![feature(maybe_uninit_extra)]
578 /// use std::mem::MaybeUninit;
580 /// let mut x = MaybeUninit::<u32>::uninit();
582 /// let x1 = unsafe { x.assume_init_read() };
583 /// // `u32` is `Copy`, so we may read multiple times.
584 /// let x2 = unsafe { x.assume_init_read() };
585 /// assert_eq!(x1, x2);
587 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
589 /// let x1 = unsafe { x.assume_init_read() };
590 /// // Duplicating a `None` value is okay, so we may read multiple times.
591 /// let x2 = unsafe { x.assume_init_read() };
592 /// assert_eq!(x1, x2);
595 /// *Incorrect* usage of this method:
598 /// #![feature(maybe_uninit_extra)]
599 /// use std::mem::MaybeUninit;
601 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
602 /// x.write(Some(vec![0, 1, 2]));
603 /// let x1 = unsafe { x.assume_init_read() };
604 /// let x2 = unsafe { x.assume_init_read() };
605 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
606 /// // they both get dropped!
608 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
609 #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
611 pub const unsafe fn assume_init_read(&self) -> T {
612 // SAFETY: the caller must guarantee that `self` is initialized.
613 // Reading from `self.as_ptr()` is safe since `self` should be initialized.
615 intrinsics::assert_inhabited::<T>();
620 /// Drops the contained value in place.
622 /// If you have ownership of the `MaybeUninit`, you can use [`assume_init`] instead.
626 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
627 /// in an initialized state. Calling this when the content is not yet fully
628 /// initialized causes undefined behavior.
630 /// On top of that, all additional invariants of the type `T` must be
631 /// satisfied, as the `Drop` implementation of `T` (or its members) may
632 /// rely on this. For example, a `1`-initialized [`Vec<T>`] is considered
633 /// initialized (under the current implementation; this does not constitute
634 /// a stable guarantee) because the only requirement the compiler knows
635 /// about it is that the data pointer must be non-null. Dropping such a
636 /// `Vec<T>` however will cause undefined behaviour.
638 /// [`assume_init`]: MaybeUninit::assume_init
639 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
640 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
641 pub unsafe fn assume_init_drop(&mut self) {
642 // SAFETY: the caller must guarantee that `self` is initialized and
643 // satisfies all invariants of `T`.
644 // Dropping the value in place is safe if that is the case.
645 unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
648 /// Gets a shared reference to the contained value.
650 /// This can be useful when we want to access a `MaybeUninit` that has been
651 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
652 /// of `.assume_init()`).
656 /// Calling this when the content is not yet fully initialized causes undefined
657 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
658 /// is in an initialized state.
662 /// ### Correct usage of this method:
665 /// #![feature(maybe_uninit_ref)]
666 /// use std::mem::MaybeUninit;
668 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
669 /// // Initialize `x`:
670 /// unsafe { x.as_mut_ptr().write(vec![1, 2, 3]); }
671 /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
672 /// // create a shared reference to it:
673 /// let x: &Vec<u32> = unsafe {
674 /// // SAFETY: `x` has been initialized.
675 /// x.assume_init_ref()
677 /// assert_eq!(x, &vec![1, 2, 3]);
680 /// ### *Incorrect* usages of this method:
683 /// #![feature(maybe_uninit_ref)]
684 /// use std::mem::MaybeUninit;
686 /// let x = MaybeUninit::<Vec<u32>>::uninit();
687 /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
688 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
692 /// #![feature(maybe_uninit_ref)]
693 /// use std::{cell::Cell, mem::MaybeUninit};
695 /// let b = MaybeUninit::<Cell<bool>>::uninit();
696 /// // Initialize the `MaybeUninit` using `Cell::set`:
698 /// b.assume_init_ref().set(true);
699 /// // ^^^^^^^^^^^^^^^
700 /// // Reference to an uninitialized `Cell<bool>`: UB!
703 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
704 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
706 pub const unsafe fn assume_init_ref(&self) -> &T {
707 // SAFETY: the caller must guarantee that `self` is initialized.
708 // This also means that `self` must be a `value` variant.
710 intrinsics::assert_inhabited::<T>();
715 /// Gets a mutable (unique) reference to the contained value.
717 /// This can be useful when we want to access a `MaybeUninit` that has been
718 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
719 /// of `.assume_init()`).
723 /// Calling this when the content is not yet fully initialized causes undefined
724 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
725 /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
726 /// initialize a `MaybeUninit`.
730 /// ### Correct usage of this method:
733 /// #![feature(maybe_uninit_ref)]
734 /// use std::mem::MaybeUninit;
736 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 2048]) { *buf = [0; 2048] }
739 /// /// Initializes *all* the bytes of the input buffer.
740 /// fn initialize_buffer(buf: *mut [u8; 2048]);
743 /// let mut buf = MaybeUninit::<[u8; 2048]>::uninit();
745 /// // Initialize `buf`:
746 /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
747 /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
748 /// // However, using `.assume_init()` may trigger a `memcpy` of the 2048 bytes.
749 /// // To assert our buffer has been initialized without copying it, we upgrade
750 /// // the `&mut MaybeUninit<[u8; 2048]>` to a `&mut [u8; 2048]`:
751 /// let buf: &mut [u8; 2048] = unsafe {
752 /// // SAFETY: `buf` has been initialized.
753 /// buf.assume_init_mut()
756 /// // Now we can use `buf` as a normal slice:
757 /// buf.sort_unstable();
759 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
760 /// "buffer is sorted",
764 /// ### *Incorrect* usages of this method:
766 /// You cannot use `.assume_init_mut()` to initialize a value:
769 /// #![feature(maybe_uninit_ref)]
770 /// use std::mem::MaybeUninit;
772 /// let mut b = MaybeUninit::<bool>::uninit();
774 /// *b.assume_init_mut() = true;
775 /// // We have created a (mutable) reference to an uninitialized `bool`!
776 /// // This is undefined behavior. ⚠️
780 /// For instance, you cannot [`Read`] into an uninitialized buffer:
782 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
785 /// #![feature(maybe_uninit_ref)]
786 /// use std::{io, mem::MaybeUninit};
788 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
790 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
791 /// reader.read_exact(unsafe { buffer.assume_init_mut() })?;
792 /// // ^^^^^^^^^^^^^^^^^^^^^^^^
793 /// // (mutable) reference to uninitialized memory!
794 /// // This is undefined behavior.
795 /// Ok(unsafe { buffer.assume_init() })
799 /// Nor can you use direct field access to do field-by-field gradual initialization:
802 /// #![feature(maybe_uninit_ref)]
803 /// use std::{mem::MaybeUninit, ptr};
810 /// let foo: Foo = unsafe {
811 /// let mut foo = MaybeUninit::<Foo>::uninit();
812 /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
813 /// // ^^^^^^^^^^^^^^^^^^^^^
814 /// // (mutable) reference to uninitialized memory!
815 /// // This is undefined behavior.
816 /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
817 /// // ^^^^^^^^^^^^^^^^^^^^^
818 /// // (mutable) reference to uninitialized memory!
819 /// // This is undefined behavior.
820 /// foo.assume_init()
823 // FIXME(#76092): We currently rely on the above being incorrect, i.e., we have references
824 // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make
825 // a final decision about the rules before stabilization.
826 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
827 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
829 pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
830 // SAFETY: the caller must guarantee that `self` is initialized.
831 // This also means that `self` must be a `value` variant.
833 intrinsics::assert_inhabited::<T>();
834 &mut *self.as_mut_ptr()
838 /// Extracts the values from an array of `MaybeUninit` containers.
842 /// It is up to the caller to guarantee that all elements of the array are
843 /// in an initialized state.
848 /// #![feature(maybe_uninit_uninit_array)]
849 /// #![feature(maybe_uninit_array_assume_init)]
850 /// use std::mem::MaybeUninit;
852 /// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
853 /// array[0] = MaybeUninit::new(0);
854 /// array[1] = MaybeUninit::new(1);
855 /// array[2] = MaybeUninit::new(2);
857 /// // SAFETY: Now safe as we initialised all elements
858 /// let array = unsafe {
859 /// MaybeUninit::array_assume_init(array)
862 /// assert_eq!(array, [0, 1, 2]);
864 #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
866 pub unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
868 // * The caller guarantees that all elements of the array are initialized
869 // * `MaybeUninit<T>` and T are guaranteed to have the same layout
870 // * MaybeUnint does not drop, so there are no double-frees
871 // And thus the conversion is safe
873 intrinsics::assert_inhabited::<[T; N]>();
874 (&array as *const _ as *const [T; N]).read()
878 /// Assuming all the elements are initialized, get a slice to them.
882 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
883 /// really are in an initialized state.
884 /// Calling this when the content is not yet fully initialized causes undefined behavior.
886 /// See [`assume_init_ref`] for more details and examples.
888 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
889 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
890 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
892 pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
893 // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
894 // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
895 // The pointer obtained is valid since it refers to memory owned by `slice` which is a
896 // reference and thus guaranteed to be valid for reads.
897 unsafe { &*(slice as *const [Self] as *const [T]) }
900 /// Assuming all the elements are initialized, get a mutable slice to them.
904 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
905 /// really are in an initialized state.
906 /// Calling this when the content is not yet fully initialized causes undefined behavior.
908 /// See [`assume_init_mut`] for more details and examples.
910 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
911 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
912 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
914 pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
915 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
916 // mutable reference which is also guaranteed to be valid for writes.
917 unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
920 /// Gets a pointer to the first element of the array.
921 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
922 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
924 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
925 this.as_ptr() as *const T
928 /// Gets a mutable pointer to the first element of the array.
929 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
930 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
932 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
933 this.as_mut_ptr() as *mut T
936 /// Copies the elements from `src` to `this`, returning a mutable reference to the now initalized contents of `this`.
938 /// If `T` does not implement `Copy`, use [`write_slice_cloned`]
940 /// This is similar to [`slice::copy_from_slice`].
944 /// This function will panic if the two slices have different lengths.
949 /// #![feature(maybe_uninit_write_slice)]
950 /// use std::mem::MaybeUninit;
952 /// let mut dst = [MaybeUninit::uninit(); 32];
953 /// let src = [0; 32];
955 /// let init = MaybeUninit::write_slice(&mut dst, &src);
957 /// assert_eq!(init, src);
961 /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
962 /// use std::mem::MaybeUninit;
964 /// let mut vec = Vec::with_capacity(32);
965 /// let src = [0; 16];
967 /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);
969 /// // SAFETY: we have just copied all the elements of len into the spare capacity
970 /// // the first src.len() elements of the vec are valid now.
972 /// vec.set_len(src.len());
975 /// assert_eq!(vec, src);
978 /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned
979 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
980 pub fn write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
984 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
985 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
987 this.copy_from_slice(uninit_src);
989 // SAFETY: Valid elements have just been copied into `this` so it is initalized
990 unsafe { MaybeUninit::slice_assume_init_mut(this) }
993 /// Clones the elements from `src` to `this`, returning a mutable reference to the now initalized contents of `this`.
994 /// Any already initalized elements will not be dropped.
996 /// If `T` implements `Copy`, use [`write_slice`]
998 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1002 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1004 /// If there is a panic, the already cloned elements will be dropped.
1009 /// #![feature(maybe_uninit_write_slice)]
1010 /// use std::mem::MaybeUninit;
1012 /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()];
1013 /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()];
1015 /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src);
1017 /// assert_eq!(init, src);
1021 /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
1022 /// use std::mem::MaybeUninit;
1024 /// let mut vec = Vec::with_capacity(32);
1025 /// let src = ["rust", "is", "a", "pretty", "cool", "language"];
1027 /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src);
1029 /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1030 /// // the first src.len() elements of the vec are valid now.
1032 /// vec.set_len(src.len());
1035 /// assert_eq!(vec, src);
1038 /// [`write_slice`]: MaybeUninit::write_slice
1039 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1040 pub fn write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1044 // unlike copy_from_slice this does not call clone_from_slice on the slice
1045 // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1047 struct Guard<'a, T> {
1048 slice: &'a mut [MaybeUninit<T>],
1052 impl<'a, T> Drop for Guard<'a, T> {
1053 fn drop(&mut self) {
1054 let initialized_part = &mut self.slice[..self.initialized];
1055 // SAFETY: this raw slice will contain only initialized objects
1056 // that's why, it is allowed to drop it.
1058 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part));
1063 assert_eq!(this.len(), src.len(), "destination and source slices have different lengths");
1064 // NOTE: We need to explicitly slice them to the same length
1065 // for bounds checking to be elided, and the optimizer will
1066 // generate memcpy for simple cases (for example T = u8).
1067 let len = this.len();
1068 let src = &src[..len];
1070 // guard is needed b/c panic might happen during a clone
1071 let mut guard = Guard { slice: this, initialized: 0 };
1074 guard.slice[i].write(src[i].clone());
1075 guard.initialized += 1;
1078 super::forget(guard);
1080 // SAFETY: Valid elements have just been written into `this` so it is initalized
1081 unsafe { MaybeUninit::slice_assume_init_mut(this) }