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 /// There is currently no supported way to create a raw pointer or reference
176 /// to a field of a struct inside `MaybeUninit<Struct>`. That means it is not possible
177 /// to create a struct by calling `MaybeUninit::uninit::<Struct>()` and then writing
180 /// [ub]: ../../reference/behavior-considered-undefined.html
184 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
187 /// use std::mem::{MaybeUninit, size_of, align_of};
188 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
189 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
192 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
193 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
194 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
195 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
196 /// optimizations, potentially resulting in a larger size:
199 /// # use std::mem::{MaybeUninit, size_of};
200 /// assert_eq!(size_of::<Option<bool>>(), 1);
201 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
204 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
206 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
207 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
208 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
209 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
210 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
211 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
212 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
213 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
214 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
215 /// guarantee may evolve.
216 #[stable(feature = "maybe_uninit", since = "1.36.0")]
217 // Lang item so we can wrap other types in it. This is useful for generators.
218 #[lang = "maybe_uninit"]
221 pub union MaybeUninit<T> {
223 value: ManuallyDrop<T>,
226 #[stable(feature = "maybe_uninit", since = "1.36.0")]
227 impl<T: Copy> Clone for MaybeUninit<T> {
229 fn clone(&self) -> Self {
230 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
235 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
236 impl<T> fmt::Debug for MaybeUninit<T> {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.pad(type_name::<Self>())
242 impl<T> MaybeUninit<T> {
243 /// Creates a new `MaybeUninit<T>` initialized with the given value.
244 /// It is safe to call [`assume_init`] on the return value of this function.
246 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
247 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
252 /// use std::mem::MaybeUninit;
254 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
257 /// [`assume_init`]: MaybeUninit::assume_init
258 #[stable(feature = "maybe_uninit", since = "1.36.0")]
259 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
261 pub const fn new(val: T) -> MaybeUninit<T> {
262 MaybeUninit { value: ManuallyDrop::new(val) }
265 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
267 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
268 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
270 /// See the [type-level documentation][MaybeUninit] for some examples.
275 /// use std::mem::MaybeUninit;
277 /// let v: MaybeUninit<String> = MaybeUninit::uninit();
279 #[stable(feature = "maybe_uninit", since = "1.36.0")]
280 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
282 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
283 pub const fn uninit() -> MaybeUninit<T> {
284 MaybeUninit { uninit: () }
287 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
289 /// Note: in a future Rust version this method may become unnecessary
290 /// when array literal syntax allows
291 /// [repeating const expressions](https://github.com/rust-lang/rust/issues/49147).
292 /// The example below could then use `let mut buf = [MaybeUninit::<u8>::uninit(); 32];`.
297 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
299 /// use std::mem::MaybeUninit;
302 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
305 /// /// Returns a (possibly smaller) slice of data that was actually read
306 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
308 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
309 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
313 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
314 /// let data = read(&mut buf);
316 #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
317 #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
319 pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
320 // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
321 unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
324 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
325 /// filled with `0` bytes. It depends on `T` whether that already makes for
326 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
327 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
330 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
331 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
335 /// Correct usage of this function: initializing a struct with zero, where all
336 /// fields of the struct can hold the bit-pattern 0 as a valid value.
339 /// use std::mem::MaybeUninit;
341 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
342 /// let x = unsafe { x.assume_init() };
343 /// assert_eq!(x, (0, false));
346 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
347 /// when `0` is not a valid bit-pattern for the type:
350 /// use std::mem::MaybeUninit;
352 /// enum NotZero { One = 1, Two = 2 }
354 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
355 /// let x = unsafe { x.assume_init() };
356 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
357 /// // This is undefined behavior. ⚠️
359 #[stable(feature = "maybe_uninit", since = "1.36.0")]
361 #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
362 pub fn zeroed() -> MaybeUninit<T> {
363 let mut u = MaybeUninit::<T>::uninit();
364 // SAFETY: `u.as_mut_ptr()` points to allocated memory.
366 u.as_mut_ptr().write_bytes(0u8, 1);
371 /// Sets the value of the `MaybeUninit<T>`. This overwrites any previous value
372 /// without dropping it, so be careful not to use this twice unless you want to
373 /// skip running the destructor. For your convenience, this also returns a mutable
374 /// reference to the (now safely initialized) contents of `self`.
375 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
376 #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
378 pub const fn write(&mut self, val: T) -> &mut T {
379 *self = MaybeUninit::new(val);
380 // SAFETY: We just initialized this value.
381 unsafe { self.assume_init_mut() }
384 /// Gets a pointer to the contained value. Reading from this pointer or turning it
385 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
386 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
387 /// (except inside an `UnsafeCell<T>`).
391 /// Correct usage of this method:
394 /// use std::mem::MaybeUninit;
396 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
397 /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
398 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
399 /// let x_vec = unsafe { &*x.as_ptr() };
400 /// assert_eq!(x_vec.len(), 3);
403 /// *Incorrect* usage of this method:
406 /// use std::mem::MaybeUninit;
408 /// let x = MaybeUninit::<Vec<u32>>::uninit();
409 /// let x_vec = unsafe { &*x.as_ptr() };
410 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
413 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
414 /// until they are, it is advisable to avoid them.)
415 #[stable(feature = "maybe_uninit", since = "1.36.0")]
416 #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
418 pub const fn as_ptr(&self) -> *const T {
419 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
420 self as *const _ as *const T
423 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
424 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
428 /// Correct usage of this method:
431 /// use std::mem::MaybeUninit;
433 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
434 /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
435 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
436 /// // This is okay because we initialized it.
437 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
439 /// assert_eq!(x_vec.len(), 4);
442 /// *Incorrect* usage of this method:
445 /// use std::mem::MaybeUninit;
447 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
448 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
449 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
452 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
453 /// until they are, it is advisable to avoid them.)
454 #[stable(feature = "maybe_uninit", since = "1.36.0")]
455 #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
457 pub const fn as_mut_ptr(&mut self) -> *mut T {
458 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
459 self as *mut _ as *mut T
462 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
463 /// to ensure that the data will get dropped, because the resulting `T` is
464 /// subject to the usual drop handling.
468 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
469 /// state. Calling this when the content is not yet fully initialized causes immediate undefined
470 /// behavior. The [type-level documentation][inv] contains more information about
471 /// this initialization invariant.
473 /// [inv]: #initialization-invariant
475 /// On top of that, remember that most types have additional invariants beyond merely
476 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
477 /// is considered initialized (under the current implementation; this does not constitute
478 /// a stable guarantee) because the only requirement the compiler knows about it
479 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
480 /// *immediate* undefined behavior, but will cause undefined behavior with most
481 /// safe operations (including dropping it).
483 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
487 /// Correct usage of this method:
490 /// use std::mem::MaybeUninit;
492 /// let mut x = MaybeUninit::<bool>::uninit();
493 /// unsafe { x.as_mut_ptr().write(true); }
494 /// let x_init = unsafe { x.assume_init() };
495 /// assert_eq!(x_init, true);
498 /// *Incorrect* usage of this method:
501 /// use std::mem::MaybeUninit;
503 /// let x = MaybeUninit::<Vec<u32>>::uninit();
504 /// let x_init = unsafe { x.assume_init() };
505 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
507 #[stable(feature = "maybe_uninit", since = "1.36.0")]
508 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
510 #[rustc_diagnostic_item = "assume_init"]
511 pub const unsafe fn assume_init(self) -> T {
512 // SAFETY: the caller must guarantee that `self` is initialized.
513 // This also means that `self` must be a `value` variant.
515 intrinsics::assert_inhabited::<T>();
516 ManuallyDrop::into_inner(self.value)
520 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
521 /// to the usual drop handling.
523 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
524 /// prevents duplicating the content of the `MaybeUninit<T>`.
528 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
529 /// state. Calling this when the content is not yet fully initialized causes undefined
530 /// behavior. The [type-level documentation][inv] contains more information about
531 /// this initialization invariant.
533 /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit<T>`. When using
534 /// multiple copies of the data (by calling `assume_init_read` multiple times, or first
535 /// calling `assume_init_read` and then [`assume_init`]), it is your responsibility
536 /// to ensure that that data may indeed be duplicated.
538 /// [inv]: #initialization-invariant
539 /// [`assume_init`]: MaybeUninit::assume_init
543 /// Correct usage of this method:
546 /// #![feature(maybe_uninit_extra)]
547 /// use std::mem::MaybeUninit;
549 /// let mut x = MaybeUninit::<u32>::uninit();
551 /// let x1 = unsafe { x.assume_init_read() };
552 /// // `u32` is `Copy`, so we may read multiple times.
553 /// let x2 = unsafe { x.assume_init_read() };
554 /// assert_eq!(x1, x2);
556 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
558 /// let x1 = unsafe { x.assume_init_read() };
559 /// // Duplicating a `None` value is okay, so we may read multiple times.
560 /// let x2 = unsafe { x.assume_init_read() };
561 /// assert_eq!(x1, x2);
564 /// *Incorrect* usage of this method:
567 /// #![feature(maybe_uninit_extra)]
568 /// use std::mem::MaybeUninit;
570 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
571 /// x.write(Some(vec![0, 1, 2]));
572 /// let x1 = unsafe { x.assume_init_read() };
573 /// let x2 = unsafe { x.assume_init_read() };
574 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
575 /// // they both get dropped!
577 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
578 #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
580 pub const unsafe fn assume_init_read(&self) -> T {
581 // SAFETY: the caller must guarantee that `self` is initialized.
582 // Reading from `self.as_ptr()` is safe since `self` should be initialized.
584 intrinsics::assert_inhabited::<T>();
589 /// Drops the contained value in place.
591 /// If you have ownership of the `MaybeUninit`, you can use [`assume_init`] instead.
595 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
596 /// in an initialized state. Calling this when the content is not yet fully
597 /// initialized causes undefined behavior.
599 /// On top of that, all additional invariants of the type `T` must be
600 /// satisfied, as the `Drop` implementation of `T` (or its members) may
601 /// rely on this. For example, a `1`-initialized [`Vec<T>`] is considered
602 /// initialized (under the current implementation; this does not constitute
603 /// a stable guarantee) because the only requirement the compiler knows
604 /// about it is that the data pointer must be non-null. Dropping such a
605 /// `Vec<T>` however will cause undefined behaviour.
607 /// [`assume_init`]: MaybeUninit::assume_init
608 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
609 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
610 pub unsafe fn assume_init_drop(&mut self) {
611 // SAFETY: the caller must guarantee that `self` is initialized and
612 // satisfies all invariants of `T`.
613 // Dropping the value in place is safe if that is the case.
614 unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
617 /// Gets a shared reference to the contained value.
619 /// This can be useful when we want to access a `MaybeUninit` that has been
620 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
621 /// of `.assume_init()`).
625 /// Calling this when the content is not yet fully initialized causes undefined
626 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
627 /// is in an initialized state.
631 /// ### Correct usage of this method:
634 /// #![feature(maybe_uninit_ref)]
635 /// use std::mem::MaybeUninit;
637 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
638 /// // Initialize `x`:
639 /// unsafe { x.as_mut_ptr().write(vec![1, 2, 3]); }
640 /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
641 /// // create a shared reference to it:
642 /// let x: &Vec<u32> = unsafe {
643 /// // SAFETY: `x` has been initialized.
644 /// x.assume_init_ref()
646 /// assert_eq!(x, &vec![1, 2, 3]);
649 /// ### *Incorrect* usages of this method:
652 /// #![feature(maybe_uninit_ref)]
653 /// use std::mem::MaybeUninit;
655 /// let x = MaybeUninit::<Vec<u32>>::uninit();
656 /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
657 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
661 /// #![feature(maybe_uninit_ref)]
662 /// use std::{cell::Cell, mem::MaybeUninit};
664 /// let b = MaybeUninit::<Cell<bool>>::uninit();
665 /// // Initialize the `MaybeUninit` using `Cell::set`:
667 /// b.assume_init_ref().set(true);
668 /// // ^^^^^^^^^^^^^^^
669 /// // Reference to an uninitialized `Cell<bool>`: UB!
672 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
673 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
675 pub const unsafe fn assume_init_ref(&self) -> &T {
676 // SAFETY: the caller must guarantee that `self` is initialized.
677 // This also means that `self` must be a `value` variant.
679 intrinsics::assert_inhabited::<T>();
684 /// Gets a mutable (unique) reference to the contained value.
686 /// This can be useful when we want to access a `MaybeUninit` that has been
687 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
688 /// of `.assume_init()`).
692 /// Calling this when the content is not yet fully initialized causes undefined
693 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
694 /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
695 /// initialize a `MaybeUninit`.
699 /// ### Correct usage of this method:
702 /// #![feature(maybe_uninit_ref)]
703 /// use std::mem::MaybeUninit;
705 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 2048]) { *buf = [0; 2048] }
708 /// /// Initializes *all* the bytes of the input buffer.
709 /// fn initialize_buffer(buf: *mut [u8; 2048]);
712 /// let mut buf = MaybeUninit::<[u8; 2048]>::uninit();
714 /// // Initialize `buf`:
715 /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
716 /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
717 /// // However, using `.assume_init()` may trigger a `memcpy` of the 2048 bytes.
718 /// // To assert our buffer has been initialized without copying it, we upgrade
719 /// // the `&mut MaybeUninit<[u8; 2048]>` to a `&mut [u8; 2048]`:
720 /// let buf: &mut [u8; 2048] = unsafe {
721 /// // SAFETY: `buf` has been initialized.
722 /// buf.assume_init_mut()
725 /// // Now we can use `buf` as a normal slice:
726 /// buf.sort_unstable();
728 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
729 /// "buffer is sorted",
733 /// ### *Incorrect* usages of this method:
735 /// You cannot use `.assume_init_mut()` to initialize a value:
738 /// #![feature(maybe_uninit_ref)]
739 /// use std::mem::MaybeUninit;
741 /// let mut b = MaybeUninit::<bool>::uninit();
743 /// *b.assume_init_mut() = true;
744 /// // We have created a (mutable) reference to an uninitialized `bool`!
745 /// // This is undefined behavior. ⚠️
749 /// For instance, you cannot [`Read`] into an uninitialized buffer:
751 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
754 /// #![feature(maybe_uninit_ref)]
755 /// use std::{io, mem::MaybeUninit};
757 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
759 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
760 /// reader.read_exact(unsafe { buffer.assume_init_mut() })?;
761 /// // ^^^^^^^^^^^^^^^^^^^^^^^^
762 /// // (mutable) reference to uninitialized memory!
763 /// // This is undefined behavior.
764 /// Ok(unsafe { buffer.assume_init() })
768 /// Nor can you use direct field access to do field-by-field gradual initialization:
771 /// #![feature(maybe_uninit_ref)]
772 /// use std::{mem::MaybeUninit, ptr};
779 /// let foo: Foo = unsafe {
780 /// let mut foo = MaybeUninit::<Foo>::uninit();
781 /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
782 /// // ^^^^^^^^^^^^^^^^^^^^^
783 /// // (mutable) reference to uninitialized memory!
784 /// // This is undefined behavior.
785 /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
786 /// // ^^^^^^^^^^^^^^^^^^^^^
787 /// // (mutable) reference to uninitialized memory!
788 /// // This is undefined behavior.
789 /// foo.assume_init()
792 // FIXME(#76092): We currently rely on the above being incorrect, i.e., we have references
793 // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make
794 // a final decision about the rules before stabilization.
795 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
796 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
798 pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
799 // SAFETY: the caller must guarantee that `self` is initialized.
800 // This also means that `self` must be a `value` variant.
802 intrinsics::assert_inhabited::<T>();
803 &mut *self.as_mut_ptr()
807 /// Extracts the values from an array of `MaybeUninit` containers.
811 /// It is up to the caller to guarantee that all elements of the array are
812 /// in an initialized state.
817 /// #![feature(maybe_uninit_uninit_array)]
818 /// #![feature(maybe_uninit_array_assume_init)]
819 /// use std::mem::MaybeUninit;
821 /// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
822 /// array[0] = MaybeUninit::new(0);
823 /// array[1] = MaybeUninit::new(1);
824 /// array[2] = MaybeUninit::new(2);
826 /// // SAFETY: Now safe as we initialised all elements
827 /// let array = unsafe {
828 /// MaybeUninit::array_assume_init(array)
831 /// assert_eq!(array, [0, 1, 2]);
833 #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
835 pub unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
837 // * The caller guarantees that all elements of the array are initialized
838 // * `MaybeUninit<T>` and T are guaranteed to have the same layout
839 // * MaybeUnint does not drop, so there are no double-frees
840 // And thus the conversion is safe
842 intrinsics::assert_inhabited::<T>();
843 (&array as *const _ as *const [T; N]).read()
847 /// Assuming all the elements are initialized, get a slice to them.
851 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
852 /// really are in an initialized state.
853 /// Calling this when the content is not yet fully initialized causes undefined behavior.
855 /// See [`assume_init_ref`] for more details and examples.
857 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
858 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
859 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
861 pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
862 // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
863 // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
864 // The pointer obtained is valid since it refers to memory owned by `slice` which is a
865 // reference and thus guaranteed to be valid for reads.
866 unsafe { &*(slice as *const [Self] as *const [T]) }
869 /// Assuming all the elements are initialized, get a mutable slice to them.
873 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
874 /// really are in an initialized state.
875 /// Calling this when the content is not yet fully initialized causes undefined behavior.
877 /// See [`assume_init_mut`] for more details and examples.
879 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
880 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
881 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
883 pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
884 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
885 // mutable reference which is also guaranteed to be valid for writes.
886 unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
889 /// Gets a pointer to the first element of the array.
890 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
891 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
893 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
894 this.as_ptr() as *const T
897 /// Gets a mutable pointer to the first element of the array.
898 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
899 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
901 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
902 this.as_mut_ptr() as *mut T
905 /// Copies the elements from `src` to `this`, returning a mutable reference to the now initalized contents of `this`.
907 /// If `T` does not implement `Copy`, use [`write_slice_cloned`]
909 /// This is similar to [`slice::copy_from_slice`].
913 /// This function will panic if the two slices have different lengths.
918 /// #![feature(maybe_uninit_write_slice)]
919 /// use std::mem::MaybeUninit;
921 /// let mut dst = [MaybeUninit::uninit(); 32];
922 /// let src = [0; 32];
924 /// let init = MaybeUninit::write_slice(&mut dst, &src);
926 /// assert_eq!(init, src);
930 /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
931 /// use std::mem::MaybeUninit;
933 /// let mut vec = Vec::with_capacity(32);
934 /// let src = [0; 16];
936 /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);
938 /// // SAFETY: we have just copied all the elements of len into the spare capacity
939 /// // the first src.len() elements of the vec are valid now.
941 /// vec.set_len(src.len());
944 /// assert_eq!(vec, src);
947 /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned
948 /// [`slice::copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
949 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
950 pub fn write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
954 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
955 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
957 this.copy_from_slice(uninit_src);
959 // SAFETY: Valid elements have just been copied into `this` so it is initalized
960 unsafe { MaybeUninit::slice_assume_init_mut(this) }
963 /// Clones the elements from `src` to `this`, returning a mutable reference to the now initalized contents of `this`.
964 /// Any already initalized elements will not be dropped.
966 /// If `T` implements `Copy`, use [`write_slice`]
968 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
972 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
974 /// If there is a panic, the already cloned elements will be dropped.
979 /// #![feature(maybe_uninit_write_slice)]
980 /// use std::mem::MaybeUninit;
982 /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()];
983 /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()];
985 /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src);
987 /// assert_eq!(init, src);
991 /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
992 /// use std::mem::MaybeUninit;
994 /// let mut vec = Vec::with_capacity(32);
995 /// let src = ["rust", "is", "a", "pretty", "cool", "language"];
997 /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src);
999 /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1000 /// // the first src.len() elements of the vec are valid now.
1002 /// vec.set_len(src.len());
1005 /// assert_eq!(vec, src);
1008 /// [`write_slice`]: MaybeUninit::write_slice
1009 /// [`slice::clone_from_slice`]: ../../std/primitive.slice.html#method.clone_from_slice
1010 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1011 pub fn write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1015 // unlike copy_from_slice this does not call clone_from_slice on the slice
1016 // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1018 struct Guard<'a, T> {
1019 slice: &'a mut [MaybeUninit<T>],
1023 impl<'a, T> Drop for Guard<'a, T> {
1024 fn drop(&mut self) {
1025 let initialized_part = &mut self.slice[..self.initialized];
1026 // SAFETY: this raw slice will contain only initialized objects
1027 // that's why, it is allowed to drop it.
1029 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part));
1034 assert_eq!(this.len(), src.len(), "destination and source slices have different lengths");
1035 // NOTE: We need to explicitly slice them to the same length
1036 // for bounds checking to be elided, and the optimizer will
1037 // generate memcpy for simple cases (for example T = u8).
1038 let len = this.len();
1039 let src = &src[..len];
1041 // guard is needed b/c panic might happen during a clone
1042 let mut guard = Guard { slice: this, initialized: 0 };
1045 guard.slice[i].write(src[i].clone());
1046 guard.initialized += 1;
1049 super::forget(guard);
1051 // SAFETY: Valid elements have just been written into `this` so it is initalized
1052 unsafe { MaybeUninit::slice_assume_init_mut(this) }