Skip to main content

core/mem/
maybe_uninit.rs

1use crate::any::type_name;
2use crate::clone::TrivialClone;
3use crate::marker::Destruct;
4use crate::mem::ManuallyDrop;
5use crate::{fmt, intrinsics, ptr, slice};
6
7/// A wrapper type to construct uninitialized instances of `T`.
8///
9/// # Initialization invariant
10///
11/// The compiler, in general, assumes that a variable is [properly initialized or "valid"][validity]
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,
16/// no matter whether that reference ever gets used to access memory:
17///
18/// ```rust,no_run
19/// # #![allow(invalid_value)]
20/// use std::mem::{self, MaybeUninit};
21///
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! ⚠️
25/// ```
26///
27/// This is exploited by the compiler for various optimizations, such as eliding
28/// run-time checks and optimizing `enum` layout.
29///
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:
32///
33/// ```rust,no_run
34/// # #![allow(invalid_value)]
35/// use std::mem::{self, MaybeUninit};
36///
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! ⚠️
40/// ```
41///
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:
47///
48/// ```rust,no_run
49/// # #![allow(invalid_value)]
50/// use std::mem::{self, MaybeUninit};
51///
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! ⚠️
55/// ```
56///
57/// Conversely, sometimes it is okay to not initialize *all* bytes of a `MaybeUninit`
58/// before calling `assume_init`. For instance, padding bytes do not have to be initialized.
59/// See the field-by-field struct initialization example below for a case of that.
60///
61/// On top of that, remember that most types have additional invariants beyond merely
62/// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
63/// is considered initialized (under the current implementation; this does not constitute
64/// a stable guarantee) because the only requirement the compiler knows about it
65/// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
66/// *immediate* undefined behavior, but will cause undefined behavior with most
67/// safe operations (including dropping it).
68///
69/// [`Vec<T>`]: ../../std/vec/struct.Vec.html
70///
71/// # Examples
72///
73/// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
74/// It is a signal to the compiler indicating that the data here might *not*
75/// be initialized:
76///
77/// ```rust
78/// use std::mem::MaybeUninit;
79///
80/// // Create an explicitly uninitialized reference. The compiler knows that data inside
81/// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
82/// let mut x = MaybeUninit::<&i32>::uninit();
83/// // Set it to a valid value.
84/// x.write(&0);
85/// // Extract the initialized data -- this is only allowed *after* properly
86/// // initializing `x`!
87/// let x = unsafe { x.assume_init() };
88/// ```
89///
90/// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
91///
92/// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without
93/// any of the run-time tracking and without any of the safety checks.
94///
95/// ## out-pointers
96///
97/// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
98/// from a function, pass it a pointer to some (uninitialized) memory to put the
99/// result into. This can be useful when it is important for the caller to control
100/// how the memory the result is stored in gets allocated, and you want to avoid
101/// unnecessary moves.
102///
103/// ```
104/// use std::mem::MaybeUninit;
105///
106/// unsafe fn make_vec(out: *mut Vec<i32>) {
107///     // `write` does not drop the old contents, which is important.
108///     unsafe { out.write(vec![1, 2, 3]); }
109/// }
110///
111/// let mut v = MaybeUninit::uninit();
112/// unsafe { make_vec(v.as_mut_ptr()); }
113/// // Now we know `v` is initialized! This also makes sure the vector gets
114/// // properly dropped.
115/// let v = unsafe { v.assume_init() };
116/// assert_eq!(&v, &[1, 2, 3]);
117/// ```
118///
119/// ## Initializing an array element-by-element
120///
121/// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
122///
123/// ```
124/// use std::mem::{self, MaybeUninit};
125///
126/// let data = {
127///     // Create an uninitialized array of `MaybeUninit`.
128///     let mut data: [MaybeUninit<Vec<u32>>; 1000] = [const { MaybeUninit::uninit() }; 1000];
129///
130///     // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop,
131///     // we have a memory leak, but there is no memory safety issue.
132///     for elem in &mut data[..] {
133///         elem.write(vec![42]);
134///     }
135///
136///     // Everything is initialized. Transmute the array to the
137///     // initialized type.
138///     unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
139/// };
140///
141/// assert_eq!(&data[0], &[42]);
142/// ```
143///
144/// You can also work with partially initialized arrays, which could
145/// be found in low-level datastructures.
146///
147/// ```
148/// use std::mem::MaybeUninit;
149///
150/// // Create an uninitialized array of `MaybeUninit`.
151/// let mut data: [MaybeUninit<String>; 1000] = [const { MaybeUninit::uninit() }; 1000];
152/// // Count the number of elements we have assigned.
153/// let mut data_len: usize = 0;
154///
155/// for elem in &mut data[0..500] {
156///     elem.write(String::from("hello"));
157///     data_len += 1;
158/// }
159///
160/// // For each item in the array, drop if we allocated it.
161/// for elem in &mut data[0..data_len] {
162///     unsafe { elem.assume_init_drop(); }
163/// }
164/// ```
165///
166/// ## Initializing a struct field-by-field
167///
168/// You can use `MaybeUninit<T>` and the [`&raw mut`] syntax to initialize structs field by field:
169///
170/// ```rust
171/// use std::mem::MaybeUninit;
172///
173/// #[derive(Debug, PartialEq)]
174/// pub struct Foo {
175///     name: String,
176///     list: Vec<u8>,
177/// }
178///
179/// let foo = {
180///     let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
181///     let ptr = uninit.as_mut_ptr();
182///
183///     // Initializing the `name` field
184///     // Using `write` instead of assignment via `=` to not call `drop` on the
185///     // old, uninitialized value.
186///     unsafe { (&raw mut (*ptr).name).write("Bob".to_string()); }
187///
188///     // Initializing the `list` field
189///     // If there is a panic here, then the `String` in the `name` field leaks.
190///     unsafe { (&raw mut (*ptr).list).write(vec![0, 1, 2]); }
191///
192///     // All the fields are initialized, so we call `assume_init` to get an initialized Foo.
193///     unsafe { uninit.assume_init() }
194/// };
195///
196/// assert_eq!(
197///     foo,
198///     Foo {
199///         name: "Bob".to_string(),
200///         list: vec![0, 1, 2]
201///     }
202/// );
203/// ```
204/// [`&raw mut`]: https://doc.rust-lang.org/reference/types/pointer.html#r-type.pointer.raw.constructor
205/// [validity]: ../../reference/behavior-considered-undefined.html#r-undefined.validity
206///
207/// Note that we have not initialized the padding, but that's fine -- it does not have to be
208/// initialized. In fact, even if we had initialized the padding in `uninit`, those bytes would be
209/// lost when copying the result: no matter the contents of the padding bytes in `uninit`, they will
210/// always be uninitialized in `foo`.
211///
212/// # Layout
213///
214/// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
215///
216/// ```rust
217/// use std::mem::MaybeUninit;
218/// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
219/// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
220/// ```
221///
222/// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
223/// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
224/// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
225/// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
226/// optimizations, potentially resulting in a larger size:
227///
228/// ```rust
229/// # use std::mem::MaybeUninit;
230/// assert_eq!(size_of::<Option<bool>>(), 1);
231/// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
232/// ```
233///
234/// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
235///
236/// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
237/// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
238/// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
239/// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
240/// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
241/// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
242/// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
243/// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
244/// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
245/// guarantee may evolve.
246///
247/// Note that even though `T` and `MaybeUninit<T>` are ABI compatible it is still unsound to
248/// transmute `&mut T` to `&mut MaybeUninit<T>` and expose that to safe code because it would allow
249/// safe code to access uninitialized memory:
250///
251/// ```rust,no_run
252/// use core::mem::MaybeUninit;
253///
254/// fn unsound_transmute<T>(val: &mut T) -> &mut MaybeUninit<T> {
255///     unsafe { core::mem::transmute(val) }
256/// }
257///
258/// fn main() {
259///     let mut code = 0;
260///     let code = &mut code;
261///     let code2 = unsound_transmute(code);
262///     *code2 = MaybeUninit::uninit();
263///     std::process::exit(*code); // UB! Accessing uninitialized memory.
264/// }
265/// ```
266///
267/// # Validity
268///
269/// `MaybeUninit<T>` has no validity requirements – any sequence of [bytes] of
270/// the appropriate length, initialized or uninitialized, are a valid
271/// representation.
272///
273/// Moving or copying a value of type `MaybeUninit<T>` (i.e., performing a
274/// "typed copy") will exactly preserve the contents, including the
275/// [provenance], of all non-padding bytes of type `T` in the value's
276/// representation.
277///
278/// Therefore `MaybeUninit` can be used to perform a round trip of a value from
279/// type `T` to type `MaybeUninit<U>` then back to type `T`, while preserving
280/// the original value, if two conditions are met. One, type `U` must have the
281/// same size as type `T`. Two, for all byte offsets where type `U` has padding,
282/// the corresponding bytes in the representation of the value must be
283/// uninitialized.
284///
285/// For example, due to the fact that the type `[u8; size_of::<T>]` has no
286/// padding, the following is sound for any type `T` and will return the
287/// original value:
288///
289/// ```rust,no_run
290/// # use core::mem::{MaybeUninit, transmute};
291/// # struct T;
292/// fn identity(t: T) -> T {
293///     unsafe {
294///         let u: MaybeUninit<[u8; size_of::<T>()]> = transmute(t);
295///         transmute(u) // OK.
296///     }
297/// }
298/// ```
299///
300/// Note: Copying a value that contains references may implicitly reborrow them
301/// causing the provenance of the returned value to differ from that of the
302/// original. This applies equally to the trivial identity function:
303///
304/// ```rust,no_run
305/// fn trivial_identity<T>(t: T) -> T { t }
306/// ```
307///
308/// Note: Moving or copying a value whose representation has initialized bytes
309/// at byte offsets where the type has padding may lose the value of those
310/// bytes, so while the original value will be preserved, the original
311/// *representation* of that value as bytes may not be. Again, this applies
312/// equally to `trivial_identity`.
313///
314/// Note: Performing this round trip when type `U` has padding at byte offsets
315/// where the representation of the original value has initialized bytes may
316/// produce undefined behavior or a different value. For example, the following
317/// is unsound since `T` requires all bytes to be initialized:
318///
319/// ```rust,no_run
320/// # use core::mem::{MaybeUninit, transmute};
321/// #[repr(C)] struct T([u8; 4]);
322/// #[repr(C)] struct U(u8, u16);
323/// fn unsound_identity(t: T) -> T {
324///     unsafe {
325///         let u: MaybeUninit<U> = transmute(t);
326///         transmute(u) // UB.
327///     }
328/// }
329/// ```
330///
331/// Conversely, the following is sound since `T` allows uninitialized bytes in
332/// the representation of a value, but the round trip may alter the value:
333///
334/// ```rust,no_run
335/// # use core::mem::{MaybeUninit, transmute};
336/// #[repr(C)] struct T(MaybeUninit<[u8; 4]>);
337/// #[repr(C)] struct U(u8, u16);
338/// fn non_identity(t: T) -> T {
339///     unsafe {
340///         // May lose an initialized byte.
341///         let u: MaybeUninit<U> = transmute(t);
342///         transmute(u)
343///     }
344/// }
345/// ```
346///
347/// [bytes]: ../../reference/memory-model.html#bytes
348/// [provenance]: crate::ptr#provenance
349#[stable(feature = "maybe_uninit", since = "1.36.0")]
350// Lang item so we can wrap other types in it. This is useful for coroutines.
351#[lang = "maybe_uninit"]
352#[derive(Copy)]
353#[repr(transparent)]
354#[rustc_pub_transparent]
355pub union MaybeUninit<T> {
356    uninit: (),
357    value: ManuallyDrop<T>,
358}
359
360#[stable(feature = "maybe_uninit", since = "1.36.0")]
361impl<T: Copy> Clone for MaybeUninit<T> {
362    #[inline(always)]
363    fn clone(&self) -> Self {
364        // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
365        *self
366    }
367}
368
369// SAFETY: the clone implementation is a copy, see above.
370#[doc(hidden)]
371#[unstable(feature = "trivial_clone", issue = "none")]
372unsafe impl<T> TrivialClone for MaybeUninit<T> where MaybeUninit<T>: Clone {}
373
374#[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
375impl<T> fmt::Debug for MaybeUninit<T> {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        // NB: there is no `.pad_fmt` so we can't use a simpler `format_args!("MaybeUninit<{..}>").
378        let full_name = type_name::<Self>();
379        let prefix_len = full_name.find("MaybeUninit").unwrap();
380        f.pad(&full_name[prefix_len..])
381    }
382}
383
384impl<T> MaybeUninit<T> {
385    /// Creates a new `MaybeUninit<T>` initialized with the given value.
386    /// It is safe to call [`assume_init`] on the return value of this function.
387    ///
388    /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
389    /// It is your responsibility to make sure `T` gets dropped if it got initialized.
390    ///
391    /// # Example
392    ///
393    /// ```
394    /// use std::mem::MaybeUninit;
395    ///
396    /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
397    /// # // Prevent leaks for Miri
398    /// # unsafe { let _ = MaybeUninit::assume_init(v); }
399    /// ```
400    ///
401    /// [`assume_init`]: MaybeUninit::assume_init
402    #[stable(feature = "maybe_uninit", since = "1.36.0")]
403    #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
404    #[must_use = "use `forget` to avoid running Drop code"]
405    #[inline(always)]
406    pub const fn new(val: T) -> MaybeUninit<T> {
407        MaybeUninit { value: ManuallyDrop::new(val) }
408    }
409
410    /// Creates a new `MaybeUninit<T>` in an uninitialized state.
411    ///
412    /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
413    /// It is your responsibility to make sure `T` gets dropped if it got initialized.
414    ///
415    /// See the [type-level documentation][MaybeUninit] for some examples.
416    ///
417    /// # Example
418    ///
419    /// ```
420    /// use std::mem::MaybeUninit;
421    ///
422    /// let v: MaybeUninit<String> = MaybeUninit::uninit();
423    /// ```
424    #[stable(feature = "maybe_uninit", since = "1.36.0")]
425    #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
426    #[must_use]
427    #[inline(always)]
428    #[rustc_diagnostic_item = "maybe_uninit_uninit"]
429    pub const fn uninit() -> MaybeUninit<T> {
430        MaybeUninit { uninit: () }
431    }
432
433    /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
434    /// filled with `0` bytes. It depends on `T` whether that already makes for
435    /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
436    /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
437    /// be null.
438    ///
439    /// Note that if `T` has padding bytes, those bytes are *not* preserved when the
440    /// `MaybeUninit<T>` value is returned from this function, so those bytes will *not* be zeroed.
441    ///
442    /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
443    /// It is your responsibility to make sure `T` gets dropped if it got initialized.
444    ///
445    /// # Example
446    ///
447    /// Correct usage of this function: initializing a struct with zero, where all
448    /// fields of the struct can hold the bit-pattern 0 as a valid value.
449    ///
450    /// ```rust
451    /// use std::mem::MaybeUninit;
452    ///
453    /// let x = MaybeUninit::<(u8, bool)>::zeroed();
454    /// let x = unsafe { x.assume_init() };
455    /// assert_eq!(x, (0, false));
456    /// ```
457    ///
458    /// This can be used in const contexts, such as to indicate the end of static arrays for
459    /// plugin registration.
460    ///
461    /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
462    /// when `0` is not a valid bit-pattern for the type:
463    ///
464    /// ```rust,no_run
465    /// use std::mem::MaybeUninit;
466    ///
467    /// enum NotZero { One = 1, Two = 2 }
468    ///
469    /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
470    /// let x = unsafe { x.assume_init() };
471    /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
472    /// // This is undefined behavior. ⚠️
473    /// ```
474    #[inline]
475    #[must_use]
476    #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
477    #[stable(feature = "maybe_uninit", since = "1.36.0")]
478    #[rustc_const_stable(feature = "const_maybe_uninit_zeroed", since = "1.75.0")]
479    pub const fn zeroed() -> MaybeUninit<T> {
480        let mut u = MaybeUninit::<T>::uninit();
481        // SAFETY: `u.as_mut_ptr()` points to allocated memory.
482        unsafe { u.as_mut_ptr().write_bytes(0u8, 1) };
483        u
484    }
485
486    /// Sets the value of the `MaybeUninit<T>`.
487    ///
488    /// This overwrites any previous value without dropping it, so be careful
489    /// not to use this twice unless you want to skip running the destructor.
490    /// For your convenience, this also returns a mutable reference to the
491    /// (now safely initialized) contents of `self`.
492    ///
493    /// As the content is stored inside a `ManuallyDrop`, the destructor is not
494    /// run for the inner data if the MaybeUninit leaves scope without a call to
495    /// [`assume_init`], [`assume_init_drop`], or similar. Code that receives
496    /// the mutable reference returned by this function needs to keep this in
497    /// mind. The safety model of Rust regards leaks as safe, but they are
498    /// usually still undesirable. This being said, the mutable reference
499    /// behaves like any other mutable reference would, so assigning a new value
500    /// to it will drop the old content.
501    ///
502    /// [`assume_init`]: Self::assume_init
503    /// [`assume_init_drop`]: Self::assume_init_drop
504    ///
505    /// # Examples
506    ///
507    /// Correct usage of this method:
508    ///
509    /// ```rust
510    /// use std::mem::MaybeUninit;
511    ///
512    /// let mut x = MaybeUninit::<Vec<u8>>::uninit();
513    ///
514    /// {
515    ///     let hello = x.write((&b"Hello, world!").to_vec());
516    ///     // Setting hello does not leak prior allocations, but drops them
517    ///     *hello = (&b"Hello").to_vec();
518    ///     hello[0] = 'h' as u8;
519    /// }
520    /// // x is initialized now:
521    /// let s = unsafe { x.assume_init() };
522    /// assert_eq!(b"hello", s.as_slice());
523    /// ```
524    ///
525    /// This usage of the method causes a leak:
526    ///
527    /// ```rust
528    /// use std::mem::MaybeUninit;
529    ///
530    /// let mut x = MaybeUninit::<String>::uninit();
531    ///
532    /// x.write("Hello".to_string());
533    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
534    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
535    /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
536    /// // This leaks the contained string:
537    /// x.write("hello".to_string());
538    /// // x is initialized now:
539    /// let s = unsafe { x.assume_init() };
540    /// ```
541    ///
542    /// This method can be used to avoid unsafe in some cases. The example below
543    /// shows a part of an implementation of a fixed sized arena that lends out
544    /// pinned references.
545    /// With `write`, we can avoid the need to write through a raw pointer:
546    ///
547    /// ```rust
548    /// use core::pin::Pin;
549    /// use core::mem::MaybeUninit;
550    ///
551    /// struct PinArena<T> {
552    ///     memory: Box<[MaybeUninit<T>]>,
553    ///     len: usize,
554    /// }
555    ///
556    /// impl <T> PinArena<T> {
557    ///     pub fn capacity(&self) -> usize {
558    ///         self.memory.len()
559    ///     }
560    ///     pub fn push(&mut self, val: T) -> Pin<&mut T> {
561    ///         if self.len >= self.capacity() {
562    ///             panic!("Attempted to push to a full pin arena!");
563    ///         }
564    ///         let ref_ = self.memory[self.len].write(val);
565    ///         self.len += 1;
566    ///         unsafe { Pin::new_unchecked(ref_) }
567    ///     }
568    /// }
569    /// ```
570    #[inline(always)]
571    #[stable(feature = "maybe_uninit_write", since = "1.55.0")]
572    #[rustc_const_stable(feature = "const_maybe_uninit_write", since = "1.85.0")]
573    pub const fn write(&mut self, val: T) -> &mut T {
574        *self = MaybeUninit::new(val);
575        // SAFETY: We just initialized this value.
576        unsafe { self.assume_init_mut() }
577    }
578
579    /// Gets a pointer to the contained value. Reading from this pointer or turning it
580    /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
581    /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
582    /// (except inside an `UnsafeCell<T>`).
583    ///
584    /// # Examples
585    ///
586    /// Correct usage of this method:
587    ///
588    /// ```rust
589    /// use std::mem::MaybeUninit;
590    ///
591    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
592    /// x.write(vec![0, 1, 2]);
593    /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
594    /// let x_vec = unsafe { &*x.as_ptr() };
595    /// assert_eq!(x_vec.len(), 3);
596    /// # // Prevent leaks for Miri
597    /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
598    /// ```
599    ///
600    /// *Incorrect* usage of this method:
601    ///
602    /// ```rust,no_run
603    /// use std::mem::MaybeUninit;
604    ///
605    /// let x = MaybeUninit::<Vec<u32>>::uninit();
606    /// let x_vec = unsafe { &*x.as_ptr() };
607    /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
608    /// ```
609    ///
610    /// (Notice that the rules around references to uninitialized data are not finalized yet, but
611    /// until they are, it is advisable to avoid them.)
612    #[stable(feature = "maybe_uninit", since = "1.36.0")]
613    #[rustc_const_stable(feature = "const_maybe_uninit_as_ptr", since = "1.59.0")]
614    #[rustc_as_ptr]
615    #[inline(always)]
616    pub const fn as_ptr(&self) -> *const T {
617        // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
618        self as *const _ as *const T
619    }
620
621    /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
622    /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
623    ///
624    /// # Examples
625    ///
626    /// Correct usage of this method:
627    ///
628    /// ```rust
629    /// use std::mem::MaybeUninit;
630    ///
631    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
632    /// x.write(vec![0, 1, 2]);
633    /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
634    /// // This is okay because we initialized it.
635    /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
636    /// x_vec.push(3);
637    /// assert_eq!(x_vec.len(), 4);
638    /// # // Prevent leaks for Miri
639    /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
640    /// ```
641    ///
642    /// *Incorrect* usage of this method:
643    ///
644    /// ```rust,no_run
645    /// use std::mem::MaybeUninit;
646    ///
647    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
648    /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
649    /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
650    /// ```
651    ///
652    /// (Notice that the rules around references to uninitialized data are not finalized yet, but
653    /// until they are, it is advisable to avoid them.)
654    #[stable(feature = "maybe_uninit", since = "1.36.0")]
655    #[rustc_const_stable(feature = "const_maybe_uninit_as_mut_ptr", since = "1.83.0")]
656    #[rustc_as_ptr]
657    #[inline(always)]
658    pub const fn as_mut_ptr(&mut self) -> *mut T {
659        // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
660        self as *mut _ as *mut T
661    }
662
663    /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
664    /// to ensure that the data will get dropped, because the resulting `T` is
665    /// subject to the usual drop handling.
666    ///
667    /// # Safety
668    ///
669    /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
670    /// state, i.e., a state that is considered ["valid" for type `T`][validity]. Calling this when
671    /// the content is not yet fully initialized causes immediate undefined behavior. The
672    /// [type-level documentation][inv] contains more information about this initialization
673    /// invariant.
674    ///
675    /// It is a common mistake to assume that this function is safe to call on integers because they
676    /// can hold all bit patterns. It is also a common mistake to think that calling this function
677    /// is UB if any byte is uninitialized. Both of these assumptions are wrong. If that is
678    /// surprising to you, please read the [type-level documentation][inv].
679    ///
680    /// [inv]: #initialization-invariant
681    /// [validity]: ../../reference/behavior-considered-undefined.html#r-undefined.validity
682    ///
683    /// On top of that, remember that most types have additional invariants beyond merely
684    /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
685    /// is considered initialized (under the current implementation; this does not constitute
686    /// a stable guarantee) because the only requirement the compiler knows about it
687    /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
688    /// *immediate* undefined behavior, but will cause undefined behavior with most
689    /// safe operations (including dropping it).
690    ///
691    /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
692    ///
693    /// # Examples
694    ///
695    /// Correct usage of this method:
696    ///
697    /// ```rust
698    /// use std::mem::MaybeUninit;
699    ///
700    /// let mut x = MaybeUninit::<bool>::uninit();
701    /// x.write(true);
702    /// let x_init = unsafe { x.assume_init() };
703    /// assert_eq!(x_init, true);
704    /// ```
705    ///
706    /// *Incorrect* usage of this method:
707    ///
708    /// ```rust,no_run
709    /// # #![allow(invalid_value)]
710    /// use std::mem::MaybeUninit;
711    ///
712    /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
713    /// ```
714    ///
715    /// See the [type-level documentation][#examples] for more examples.
716    #[stable(feature = "maybe_uninit", since = "1.36.0")]
717    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_by_value", since = "1.59.0")]
718    #[inline(always)]
719    #[rustc_diagnostic_item = "assume_init"]
720    #[track_caller]
721    pub const unsafe fn assume_init(self) -> T {
722        // SAFETY: the caller must guarantee that `self` is initialized.
723        // This also means that `self` must be a `value` variant.
724        unsafe {
725            intrinsics::assert_inhabited::<T>();
726            // We do this via a raw ptr read instead of `ManuallyDrop::into_inner` so that there's
727            // no trace of `ManuallyDrop` in Miri's error messages here.
728            (&raw const self.value).cast::<T>().read()
729        }
730    }
731
732    /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
733    /// to the usual drop handling.
734    ///
735    /// Whenever possible, it is preferable to use [`assume_init`] instead, which
736    /// prevents duplicating the content of the `MaybeUninit<T>`.
737    ///
738    /// # Safety
739    ///
740    /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
741    /// state. Calling this when the content is not yet fully initialized causes undefined
742    /// behavior. The [type-level documentation][inv] contains more information about
743    /// this initialization invariant.
744    ///
745    /// Moreover, similar to the [`ptr::read`] function, this function creates a
746    /// bitwise copy of the contents, regardless whether the contained type
747    /// implements the [`Copy`] trait or not. When using multiple copies of the
748    /// data (by calling `assume_init_read` multiple times, or first calling
749    /// `assume_init_read` and then [`assume_init`]), it is your responsibility
750    /// to ensure that data may indeed be duplicated.
751    ///
752    /// [inv]: #initialization-invariant
753    /// [`assume_init`]: MaybeUninit::assume_init
754    ///
755    /// # Examples
756    ///
757    /// Correct usage of this method:
758    ///
759    /// ```rust
760    /// use std::mem::MaybeUninit;
761    ///
762    /// let mut x = MaybeUninit::<u32>::uninit();
763    /// x.write(13);
764    /// let x1 = unsafe { x.assume_init_read() };
765    /// // `u32` is `Copy`, so we may read multiple times.
766    /// let x2 = unsafe { x.assume_init_read() };
767    /// assert_eq!(x1, x2);
768    ///
769    /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
770    /// x.write(None);
771    /// let x1 = unsafe { x.assume_init_read() };
772    /// // Duplicating a `None` value is okay, so we may read multiple times.
773    /// let x2 = unsafe { x.assume_init_read() };
774    /// assert_eq!(x1, x2);
775    /// ```
776    ///
777    /// *Incorrect* usage of this method:
778    ///
779    /// ```rust,no_run
780    /// use std::mem::MaybeUninit;
781    ///
782    /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
783    /// x.write(Some(vec![0, 1, 2]));
784    /// let x1 = unsafe { x.assume_init_read() };
785    /// let x2 = unsafe { x.assume_init_read() };
786    /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
787    /// // they both get dropped!
788    /// ```
789    #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
790    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_read", since = "1.75.0")]
791    #[inline(always)]
792    #[track_caller]
793    pub const unsafe fn assume_init_read(&self) -> T {
794        // SAFETY: the caller must guarantee that `self` is initialized.
795        // Reading from `self.as_ptr()` is safe since `self` should be initialized.
796        unsafe {
797            intrinsics::assert_inhabited::<T>();
798            self.as_ptr().read()
799        }
800    }
801
802    /// Drops the contained value in place.
803    ///
804    /// If you have ownership of the `MaybeUninit`, you can also use
805    /// [`assume_init`] as an alternative.
806    ///
807    /// # Safety
808    ///
809    /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
810    /// in an initialized state. Calling this when the content is not yet fully
811    /// initialized causes undefined behavior.
812    ///
813    /// On top of that, all additional invariants of the type `T` must be
814    /// satisfied, as the `Drop` implementation of `T` (or its members) may
815    /// rely on this. For example, setting a `Vec<T>` to an invalid but
816    /// non-null address makes it initialized (under the current implementation;
817    /// this does not constitute a stable guarantee), because the only
818    /// requirement the compiler knows about it is that the data pointer must be
819    /// non-null. Dropping such a `Vec<T>` however will cause undefined
820    /// behavior.
821    ///
822    /// [`assume_init`]: MaybeUninit::assume_init
823    #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
824    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
825    pub const unsafe fn assume_init_drop(&mut self)
826    where
827        T: [const] Destruct,
828    {
829        // SAFETY: the caller must guarantee that `self` is initialized and
830        // satisfies all invariants of `T`.
831        // Dropping the value in place is safe if that is the case.
832        unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
833    }
834
835    /// Gets a shared reference to the contained value.
836    ///
837    /// This can be useful when we want to access a `MaybeUninit` that has been
838    /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
839    /// of `.assume_init()`).
840    ///
841    /// # Safety
842    ///
843    /// Calling this when the content is not yet fully initialized causes undefined
844    /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
845    /// is in an initialized state.
846    ///
847    /// # Examples
848    ///
849    /// ### Correct usage of this method:
850    ///
851    /// ```rust
852    /// use std::mem::MaybeUninit;
853    ///
854    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
855    /// # let mut x_mu = x;
856    /// # let mut x = &mut x_mu;
857    /// // Initialize `x`:
858    /// x.write(vec![1, 2, 3]);
859    /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
860    /// // create a shared reference to it:
861    /// let x: &Vec<u32> = unsafe {
862    ///     // SAFETY: `x` has been initialized.
863    ///     x.assume_init_ref()
864    /// };
865    /// assert_eq!(x, &vec![1, 2, 3]);
866    /// # // Prevent leaks for Miri
867    /// # unsafe { MaybeUninit::assume_init_drop(&mut x_mu); }
868    /// ```
869    ///
870    /// ### *Incorrect* usages of this method:
871    ///
872    /// ```rust,no_run
873    /// use std::mem::MaybeUninit;
874    ///
875    /// let x = MaybeUninit::<Vec<u32>>::uninit();
876    /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
877    /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
878    /// ```
879    ///
880    /// ```rust,no_run
881    /// use std::{cell::Cell, mem::MaybeUninit};
882    ///
883    /// let b = MaybeUninit::<Cell<bool>>::uninit();
884    /// // Initialize the `MaybeUninit` using `Cell::set`:
885    /// unsafe {
886    ///     b.assume_init_ref().set(true);
887    ///     //^^^^^^^^^^^^^^^ Reference to an uninitialized `Cell<bool>`: UB!
888    /// }
889    /// ```
890    #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
891    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_ref", since = "1.59.0")]
892    #[inline(always)]
893    pub const unsafe fn assume_init_ref(&self) -> &T {
894        // SAFETY: the caller must guarantee that `self` is initialized.
895        // This also means that `self` must be a `value` variant.
896        unsafe {
897            intrinsics::assert_inhabited::<T>();
898            &*self.as_ptr()
899        }
900    }
901
902    /// Gets a mutable (unique) reference to the contained value.
903    ///
904    /// This can be useful when we want to access a `MaybeUninit` that has been
905    /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
906    /// of `.assume_init()`).
907    ///
908    /// # Safety
909    ///
910    /// Calling this when the content is not yet fully initialized causes undefined
911    /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
912    /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
913    /// initialize a `MaybeUninit`.
914    ///
915    /// # Examples
916    ///
917    /// ### Correct usage of this method:
918    ///
919    /// ```rust
920    /// # #![allow(unexpected_cfgs)]
921    /// use std::mem::MaybeUninit;
922    ///
923    /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { unsafe { *buf = [0; 1024] } }
924    /// # #[cfg(FALSE)]
925    /// extern "C" {
926    ///     /// Initializes *all* the bytes of the input buffer.
927    ///     fn initialize_buffer(buf: *mut [u8; 1024]);
928    /// }
929    ///
930    /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
931    ///
932    /// // Initialize `buf`:
933    /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
934    /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
935    /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes.
936    /// // To assert our buffer has been initialized without copying it, we upgrade
937    /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`:
938    /// let buf: &mut [u8; 1024] = unsafe {
939    ///     // SAFETY: `buf` has been initialized.
940    ///     buf.assume_init_mut()
941    /// };
942    ///
943    /// // Now we can use `buf` as a normal slice:
944    /// buf.sort_unstable();
945    /// assert!(
946    ///     buf.windows(2).all(|pair| pair[0] <= pair[1]),
947    ///     "buffer is sorted",
948    /// );
949    /// ```
950    ///
951    /// ### *Incorrect* usages of this method:
952    ///
953    /// You cannot use `.assume_init_mut()` to initialize a value:
954    ///
955    /// ```rust,no_run
956    /// use std::mem::MaybeUninit;
957    ///
958    /// let mut b = MaybeUninit::<bool>::uninit();
959    /// unsafe {
960    ///     *b.assume_init_mut() = true;
961    ///     // We have created a (mutable) reference to an uninitialized `bool`!
962    ///     // This is undefined behavior. ⚠️
963    /// }
964    /// ```
965    ///
966    /// For instance, you cannot [`Read`] into an uninitialized buffer:
967    ///
968    /// [`Read`]: ../../std/io/trait.Read.html
969    ///
970    /// ```rust,no_run
971    /// use std::{io, mem::MaybeUninit};
972    ///
973    /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
974    /// {
975    ///     let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
976    ///     reader.read_exact(unsafe { buffer.assume_init_mut() })?;
977    ///     //                         ^^^^^^^^^^^^^^^^^^^^^^^^
978    ///     // (mutable) reference to uninitialized memory!
979    ///     // This is undefined behavior.
980    ///     Ok(unsafe { buffer.assume_init() })
981    /// }
982    /// ```
983    ///
984    /// Nor can you use direct field access to do field-by-field gradual initialization:
985    ///
986    /// ```rust,no_run
987    /// use std::{mem::MaybeUninit, ptr};
988    ///
989    /// struct Foo {
990    ///     a: u32,
991    ///     b: u8,
992    /// }
993    ///
994    /// let foo: Foo = unsafe {
995    ///     let mut foo = MaybeUninit::<Foo>::uninit();
996    ///     ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
997    ///     //              ^^^^^^^^^^^^^^^^^^^^^
998    ///     // (mutable) reference to uninitialized memory!
999    ///     // This is undefined behavior.
1000    ///     ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
1001    ///     //              ^^^^^^^^^^^^^^^^^^^^^
1002    ///     // (mutable) reference to uninitialized memory!
1003    ///     // This is undefined behavior.
1004    ///     foo.assume_init()
1005    /// };
1006    /// ```
1007    #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
1008    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init", since = "1.84.0")]
1009    #[inline(always)]
1010    pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
1011        // SAFETY: the caller must guarantee that `self` is initialized.
1012        // This also means that `self` must be a `value` variant.
1013        unsafe {
1014            intrinsics::assert_inhabited::<T>();
1015            &mut *self.as_mut_ptr()
1016        }
1017    }
1018
1019    /// Extracts the values from an array of `MaybeUninit` containers.
1020    ///
1021    /// # Safety
1022    ///
1023    /// It is up to the caller to guarantee that all elements of the array are
1024    /// in an initialized state.
1025    ///
1026    /// # Examples
1027    ///
1028    /// ```
1029    /// #![feature(maybe_uninit_array_assume_init)]
1030    /// use std::mem::MaybeUninit;
1031    ///
1032    /// let mut array: [MaybeUninit<i32>; 3] = [MaybeUninit::uninit(); 3];
1033    /// array[0].write(0);
1034    /// array[1].write(1);
1035    /// array[2].write(2);
1036    ///
1037    /// // SAFETY: Now safe as we initialised all elements
1038    /// let array = unsafe {
1039    ///     MaybeUninit::array_assume_init(array)
1040    /// };
1041    ///
1042    /// assert_eq!(array, [0, 1, 2]);
1043    /// ```
1044    #[unstable(feature = "maybe_uninit_array_assume_init", issue = "96097")]
1045    #[inline(always)]
1046    #[track_caller]
1047    pub const unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
1048        // SAFETY:
1049        // * The caller guarantees that all elements of the array are initialized
1050        // * `MaybeUninit<T>` and T are guaranteed to have the same layout
1051        // * `MaybeUninit` does not drop, so there are no double-frees
1052        // And thus the conversion is safe
1053        unsafe {
1054            intrinsics::assert_inhabited::<[T; N]>();
1055            intrinsics::transmute_unchecked(array)
1056        }
1057    }
1058
1059    /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1060    ///
1061    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1062    /// contain padding bytes which are left uninitialized.
1063    ///
1064    /// # Examples
1065    ///
1066    /// ```
1067    /// #![feature(maybe_uninit_as_bytes)]
1068    /// use std::mem::MaybeUninit;
1069    ///
1070    /// let val = 0x12345678_i32;
1071    /// let uninit = MaybeUninit::new(val);
1072    /// let uninit_bytes = uninit.as_bytes();
1073    /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1074    /// assert_eq!(bytes, val.to_ne_bytes());
1075    /// ```
1076    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1077    pub const fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1078        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1079        unsafe {
1080            slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of::<T>())
1081        }
1082    }
1083
1084    /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized
1085    /// bytes.
1086    ///
1087    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1088    /// contain padding bytes which are left uninitialized.
1089    ///
1090    /// # Examples
1091    ///
1092    /// ```
1093    /// #![feature(maybe_uninit_as_bytes)]
1094    /// use std::mem::MaybeUninit;
1095    ///
1096    /// let val = 0x12345678_i32;
1097    /// let mut uninit = MaybeUninit::new(val);
1098    /// let uninit_bytes = uninit.as_bytes_mut();
1099    /// if cfg!(target_endian = "little") {
1100    ///     uninit_bytes[0].write(0xcd);
1101    /// } else {
1102    ///     uninit_bytes[3].write(0xcd);
1103    /// }
1104    /// let val2 = unsafe { uninit.assume_init() };
1105    /// assert_eq!(val2, 0x123456cd);
1106    /// ```
1107    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1108    pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1109        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1110        unsafe {
1111            slice::from_raw_parts_mut(
1112                self.as_mut_ptr().cast::<MaybeUninit<u8>>(),
1113                super::size_of::<T>(),
1114            )
1115        }
1116    }
1117}
1118
1119impl<T> [MaybeUninit<T>] {
1120    /// Copies the elements from `src` to `self`,
1121    /// returning a mutable reference to the now initialized contents of `self`.
1122    ///
1123    /// If `T` does not implement `Copy`, use [`write_clone_of_slice`] instead.
1124    ///
1125    /// This is similar to [`slice::copy_from_slice`].
1126    ///
1127    /// # Panics
1128    ///
1129    /// This function will panic if the two slices have different lengths.
1130    ///
1131    /// # Examples
1132    ///
1133    /// ```
1134    /// use std::mem::MaybeUninit;
1135    ///
1136    /// let mut dst = [MaybeUninit::uninit(); 32];
1137    /// let src = [0; 32];
1138    ///
1139    /// let init = dst.write_copy_of_slice(&src);
1140    ///
1141    /// assert_eq!(init, src);
1142    /// ```
1143    ///
1144    /// ```
1145    /// let mut vec = Vec::with_capacity(32);
1146    /// let src = [0; 16];
1147    ///
1148    /// vec.spare_capacity_mut()[..src.len()].write_copy_of_slice(&src);
1149    ///
1150    /// // SAFETY: we have just copied all the elements of len into the spare capacity
1151    /// // the first src.len() elements of the vec are valid now.
1152    /// unsafe {
1153    ///     vec.set_len(src.len());
1154    /// }
1155    ///
1156    /// assert_eq!(vec, src);
1157    /// ```
1158    ///
1159    /// [`write_clone_of_slice`]: slice::write_clone_of_slice
1160    #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1161    #[rustc_const_stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1162    pub const fn write_copy_of_slice(&mut self, src: &[T]) -> &mut [T]
1163    where
1164        T: Copy,
1165    {
1166        // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1167        let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1168
1169        self.copy_from_slice(uninit_src);
1170
1171        // SAFETY: Valid elements have just been copied into `self` so it is initialized
1172        unsafe { self.assume_init_mut() }
1173    }
1174
1175    /// Clones the elements from `src` to `self`,
1176    /// returning a mutable reference to the now initialized contents of `self`.
1177    /// Any already initialized elements will not be dropped.
1178    ///
1179    /// If `T` implements `Copy`, use [`write_copy_of_slice`] instead.
1180    ///
1181    /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1182    ///
1183    /// # Panics
1184    ///
1185    /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1186    ///
1187    /// If there is a panic, the already cloned elements will be dropped.
1188    ///
1189    /// # Examples
1190    ///
1191    /// ```
1192    /// use std::mem::MaybeUninit;
1193    ///
1194    /// let mut dst = [const { MaybeUninit::uninit() }; 5];
1195    /// let src = ["wibbly", "wobbly", "timey", "wimey", "stuff"].map(|s| s.to_string());
1196    ///
1197    /// let init = dst.write_clone_of_slice(&src);
1198    ///
1199    /// assert_eq!(init, src);
1200    ///
1201    /// # // Prevent leaks for Miri
1202    /// # unsafe { std::ptr::drop_in_place(init); }
1203    /// ```
1204    ///
1205    /// ```
1206    /// let mut vec = Vec::with_capacity(32);
1207    /// let src = ["rust", "is", "a", "pretty", "cool", "language"].map(|s| s.to_string());
1208    ///
1209    /// vec.spare_capacity_mut()[..src.len()].write_clone_of_slice(&src);
1210    ///
1211    /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1212    /// // the first src.len() elements of the vec are valid now.
1213    /// unsafe {
1214    ///     vec.set_len(src.len());
1215    /// }
1216    ///
1217    /// assert_eq!(vec, src);
1218    /// ```
1219    ///
1220    /// [`write_copy_of_slice`]: slice::write_copy_of_slice
1221    #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1222    pub fn write_clone_of_slice(&mut self, src: &[T]) -> &mut [T]
1223    where
1224        T: Clone,
1225    {
1226        // unlike copy_from_slice this does not call clone_from_slice on the slice
1227        // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1228
1229        assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
1230
1231        // NOTE: We need to explicitly slice them to the same length
1232        // for bounds checking to be elided, and the optimizer will
1233        // generate memcpy for simple cases (for example T = u8).
1234        let len = self.len();
1235        let src = &src[..len];
1236
1237        // guard is needed b/c panic might happen during a clone
1238        let mut guard = Guard { slice: self, initialized: 0 };
1239
1240        for i in 0..len {
1241            guard.slice[i].write(src[i].clone());
1242            guard.initialized += 1;
1243        }
1244
1245        super::forget(guard);
1246
1247        // SAFETY: Valid elements have just been written into `self` so it is initialized
1248        unsafe { self.assume_init_mut() }
1249    }
1250
1251    /// Fills a slice with elements by cloning `value`, returning a mutable reference to the now
1252    /// initialized contents of the slice.
1253    /// Any previously initialized elements will not be dropped.
1254    ///
1255    /// This is similar to [`slice::fill`].
1256    ///
1257    /// # Panics
1258    ///
1259    /// This function will panic if any call to `Clone` panics.
1260    ///
1261    /// If such a panic occurs, any elements previously initialized during this operation will be
1262    /// dropped.
1263    ///
1264    /// # Examples
1265    ///
1266    /// ```
1267    /// #![feature(maybe_uninit_fill)]
1268    /// use std::mem::MaybeUninit;
1269    ///
1270    /// let mut buf = [const { MaybeUninit::uninit() }; 10];
1271    /// let initialized = buf.write_filled(1);
1272    /// assert_eq!(initialized, &mut [1; 10]);
1273    /// ```
1274    #[doc(alias = "memset")]
1275    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1276    pub fn write_filled(&mut self, value: T) -> &mut [T]
1277    where
1278        T: Clone,
1279    {
1280        SpecFill::spec_fill(self, value);
1281        // SAFETY: Valid elements have just been filled into `self` so it is initialized
1282        unsafe { self.assume_init_mut() }
1283    }
1284
1285    /// Fills a slice with elements returned by calling a closure for each index.
1286    ///
1287    /// This method uses a closure to create new values. If you'd rather `Clone` a given value, use
1288    /// [slice::write_filled]. If you want to use the `Default` trait to generate values, you can
1289    /// pass [`|_| Default::default()`][Default::default] as the argument.
1290    ///
1291    /// # Panics
1292    ///
1293    /// This function will panic if any call to the provided closure panics.
1294    ///
1295    /// If such a panic occurs, any elements previously initialized during this operation will be
1296    /// dropped.
1297    ///
1298    /// # Examples
1299    ///
1300    /// ```
1301    /// #![feature(maybe_uninit_fill)]
1302    /// use std::mem::MaybeUninit;
1303    ///
1304    /// let mut buf = [const { MaybeUninit::<usize>::uninit() }; 5];
1305    /// let initialized = buf.write_with(|idx| idx + 1);
1306    /// assert_eq!(initialized, &mut [1, 2, 3, 4, 5]);
1307    /// ```
1308    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1309    pub fn write_with<F>(&mut self, mut f: F) -> &mut [T]
1310    where
1311        F: FnMut(usize) -> T,
1312    {
1313        let mut guard = Guard { slice: self, initialized: 0 };
1314
1315        for (idx, element) in guard.slice.iter_mut().enumerate() {
1316            element.write(f(idx));
1317            guard.initialized += 1;
1318        }
1319
1320        super::forget(guard);
1321
1322        // SAFETY: Valid elements have just been written into `this` so it is initialized
1323        unsafe { self.assume_init_mut() }
1324    }
1325
1326    /// Fills a slice with elements yielded by an iterator until either all elements have been
1327    /// initialized or the iterator is empty.
1328    ///
1329    /// Returns two slices. The first slice contains the initialized portion of the original slice.
1330    /// The second slice is the still-uninitialized remainder of the original slice.
1331    ///
1332    /// # Panics
1333    ///
1334    /// This function panics if the iterator's `next` function panics.
1335    ///
1336    /// If such a panic occurs, any elements previously initialized during this operation will be
1337    /// dropped.
1338    ///
1339    /// # Examples
1340    ///
1341    /// Completely filling the slice:
1342    ///
1343    /// ```
1344    /// #![feature(maybe_uninit_fill)]
1345    /// use std::mem::MaybeUninit;
1346    ///
1347    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1348    ///
1349    /// let iter = [1, 2, 3].into_iter().cycle();
1350    /// let (initialized, remainder) = buf.write_iter(iter);
1351    ///
1352    /// assert_eq!(initialized, &mut [1, 2, 3, 1, 2]);
1353    /// assert_eq!(remainder.len(), 0);
1354    /// ```
1355    ///
1356    /// Partially filling the slice:
1357    ///
1358    /// ```
1359    /// #![feature(maybe_uninit_fill)]
1360    /// use std::mem::MaybeUninit;
1361    ///
1362    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1363    /// let iter = [1, 2];
1364    /// let (initialized, remainder) = buf.write_iter(iter);
1365    ///
1366    /// assert_eq!(initialized, &mut [1, 2]);
1367    /// assert_eq!(remainder.len(), 3);
1368    /// ```
1369    ///
1370    /// Checking an iterator after filling a slice:
1371    ///
1372    /// ```
1373    /// #![feature(maybe_uninit_fill)]
1374    /// use std::mem::MaybeUninit;
1375    ///
1376    /// let mut buf = [const { MaybeUninit::uninit() }; 3];
1377    /// let mut iter = [1, 2, 3, 4, 5].into_iter();
1378    /// let (initialized, remainder) = buf.write_iter(iter.by_ref());
1379    ///
1380    /// assert_eq!(initialized, &mut [1, 2, 3]);
1381    /// assert_eq!(remainder.len(), 0);
1382    /// assert_eq!(iter.as_slice(), &[4, 5]);
1383    /// ```
1384    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1385    pub fn write_iter<I>(&mut self, it: I) -> (&mut [T], &mut [MaybeUninit<T>])
1386    where
1387        I: IntoIterator<Item = T>,
1388    {
1389        let iter = it.into_iter();
1390        let mut guard = Guard { slice: self, initialized: 0 };
1391
1392        for (element, val) in guard.slice.iter_mut().zip(iter) {
1393            element.write(val);
1394            guard.initialized += 1;
1395        }
1396
1397        let initialized_len = guard.initialized;
1398        super::forget(guard);
1399
1400        // SAFETY: guard.initialized <= self.len()
1401        let (initted, remainder) = unsafe { self.split_at_mut_unchecked(initialized_len) };
1402
1403        // SAFETY: Valid elements have just been written into `init`, so that portion
1404        // of `this` is initialized.
1405        (unsafe { initted.assume_init_mut() }, remainder)
1406    }
1407
1408    /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1409    ///
1410    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1411    /// contain padding bytes which are left uninitialized.
1412    ///
1413    /// # Examples
1414    ///
1415    /// ```
1416    /// #![feature(maybe_uninit_as_bytes)]
1417    /// use std::mem::MaybeUninit;
1418    ///
1419    /// let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)];
1420    /// let uninit_bytes = uninit.as_bytes();
1421    /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1422    /// let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap());
1423    /// let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap());
1424    /// assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]);
1425    /// ```
1426    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1427    pub const fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1428        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1429        unsafe {
1430            slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of_val(self))
1431        }
1432    }
1433
1434    /// Returns the contents of this `MaybeUninit` slice as a mutable slice of potentially
1435    /// uninitialized bytes.
1436    ///
1437    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1438    /// contain padding bytes which are left uninitialized.
1439    ///
1440    /// # Examples
1441    ///
1442    /// ```
1443    /// #![feature(maybe_uninit_as_bytes)]
1444    /// use std::mem::MaybeUninit;
1445    ///
1446    /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()];
1447    /// let uninit_bytes = uninit.as_bytes_mut();
1448    /// uninit_bytes.write_copy_of_slice(&[0x12, 0x34, 0x56, 0x78]);
1449    /// let vals = unsafe { uninit.assume_init_ref() };
1450    /// if cfg!(target_endian = "little") {
1451    ///     assert_eq!(vals, &[0x3412u16, 0x7856u16]);
1452    /// } else {
1453    ///     assert_eq!(vals, &[0x1234u16, 0x5678u16]);
1454    /// }
1455    /// ```
1456    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1457    pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1458        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1459        unsafe {
1460            slice::from_raw_parts_mut(
1461                self.as_mut_ptr() as *mut MaybeUninit<u8>,
1462                super::size_of_val(self),
1463            )
1464        }
1465    }
1466
1467    /// Drops the contained values in place.
1468    ///
1469    /// # Safety
1470    ///
1471    /// It is up to the caller to guarantee that every `MaybeUninit<T>` in the slice
1472    /// really is in an initialized state. Calling this when the content is not yet
1473    /// fully initialized causes undefined behavior.
1474    ///
1475    /// On top of that, all additional invariants of the type `T` must be
1476    /// satisfied, as the `Drop` implementation of `T` (or its members) may
1477    /// rely on this. For example, setting a `Vec<T>` to an invalid but
1478    /// non-null address makes it initialized (under the current implementation;
1479    /// this does not constitute a stable guarantee), because the only
1480    /// requirement the compiler knows about it is that the data pointer must be
1481    /// non-null. Dropping such a `Vec<T>` however will cause undefined
1482    /// behaviour.
1483    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1484    #[inline(always)]
1485    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1486    pub const unsafe fn assume_init_drop(&mut self)
1487    where
1488        T: [const] Destruct,
1489    {
1490        if !self.is_empty() {
1491            // SAFETY: the caller must guarantee that every element of `self`
1492            // is initialized and satisfies all invariants of `T`.
1493            // Dropping the value in place is safe if that is the case.
1494            unsafe { ptr::drop_in_place(self as *mut [MaybeUninit<T>] as *mut [T]) }
1495        }
1496    }
1497
1498    /// Gets a shared reference to the contained value.
1499    ///
1500    /// # Safety
1501    ///
1502    /// Calling this when the content is not yet fully initialized causes undefined
1503    /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in
1504    /// the slice really is in an initialized state.
1505    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1506    #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1507    #[inline(always)]
1508    pub const unsafe fn assume_init_ref(&self) -> &[T] {
1509        // SAFETY: casting `slice` to a `*const [T]` is safe since the caller guarantees that
1510        // `slice` is initialized, and `MaybeUninit` is guaranteed to have the same layout as `T`.
1511        // The pointer obtained is valid since it refers to memory owned by `slice` which is a
1512        // reference and thus guaranteed to be valid for reads.
1513        unsafe { &*(self as *const Self as *const [T]) }
1514    }
1515
1516    /// Gets a mutable (unique) reference to the contained value.
1517    ///
1518    /// # Safety
1519    ///
1520    /// Calling this when the content is not yet fully initialized causes undefined
1521    /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in the
1522    /// slice really is in an initialized state. For instance, `.assume_init_mut()` cannot
1523    /// be used to initialize a `MaybeUninit` slice.
1524    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1525    #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1526    #[inline(always)]
1527    pub const unsafe fn assume_init_mut(&mut self) -> &mut [T] {
1528        // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
1529        // mutable reference which is also guaranteed to be valid for writes.
1530        unsafe { &mut *(self as *mut Self as *mut [T]) }
1531    }
1532}
1533
1534impl<T, const N: usize> MaybeUninit<[T; N]> {
1535    /// Transposes a `MaybeUninit<[T; N]>` into a `[MaybeUninit<T>; N]`.
1536    ///
1537    /// # Examples
1538    ///
1539    /// ```
1540    /// #![feature(maybe_uninit_uninit_array_transpose)]
1541    /// # use std::mem::MaybeUninit;
1542    ///
1543    /// let data: [MaybeUninit<u8>; 1000] = MaybeUninit::uninit().transpose();
1544    /// ```
1545    #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1546    #[inline]
1547    pub const fn transpose(self) -> [MaybeUninit<T>; N] {
1548        // SAFETY: T and MaybeUninit<T> have the same layout
1549        unsafe { intrinsics::transmute_unchecked(self) }
1550    }
1551}
1552
1553#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1554impl<T, const N: usize> From<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1555    #[inline]
1556    fn from(arr: [MaybeUninit<T>; N]) -> Self {
1557        arr.transpose()
1558    }
1559}
1560
1561#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1562impl<T, const N: usize> AsRef<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1563    #[inline]
1564    fn as_ref(&self) -> &[MaybeUninit<T>; N] {
1565        // SAFETY: T and MaybeUninit<T> have the same layout
1566        unsafe { &*ptr::from_ref(self).cast() }
1567    }
1568}
1569
1570#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1571impl<T, const N: usize> AsRef<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1572    #[inline]
1573    fn as_ref(&self) -> &[MaybeUninit<T>] {
1574        &*AsRef::<[MaybeUninit<T>; N]>::as_ref(self)
1575    }
1576}
1577
1578#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1579impl<T, const N: usize> AsMut<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1580    #[inline]
1581    fn as_mut(&mut self) -> &mut [MaybeUninit<T>; N] {
1582        // SAFETY: T and MaybeUninit<T> have the same layout
1583        unsafe { &mut *ptr::from_mut(self).cast() }
1584    }
1585}
1586
1587#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1588impl<T, const N: usize> AsMut<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1589    #[inline]
1590    fn as_mut(&mut self) -> &mut [MaybeUninit<T>] {
1591        &mut *AsMut::<[MaybeUninit<T>; N]>::as_mut(self)
1592    }
1593}
1594
1595#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1596impl<T, const N: usize> From<MaybeUninit<[T; N]>> for [MaybeUninit<T>; N] {
1597    #[inline]
1598    fn from(arr: MaybeUninit<[T; N]>) -> Self {
1599        arr.transpose()
1600    }
1601}
1602
1603impl<T, const N: usize> [MaybeUninit<T>; N] {
1604    /// Transposes a `[MaybeUninit<T>; N]` into a `MaybeUninit<[T; N]>`.
1605    ///
1606    /// # Examples
1607    ///
1608    /// ```
1609    /// #![feature(maybe_uninit_uninit_array_transpose)]
1610    /// # use std::mem::MaybeUninit;
1611    ///
1612    /// let data = [MaybeUninit::<u8>::uninit(); 1000];
1613    /// let data: MaybeUninit<[u8; 1000]> = data.transpose();
1614    /// ```
1615    #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1616    #[inline]
1617    pub const fn transpose(self) -> MaybeUninit<[T; N]> {
1618        // SAFETY: T and MaybeUninit<T> have the same layout
1619        unsafe { intrinsics::transmute_unchecked(self) }
1620    }
1621}
1622
1623struct Guard<'a, T> {
1624    slice: &'a mut [MaybeUninit<T>],
1625    initialized: usize,
1626}
1627
1628impl<'a, T> Drop for Guard<'a, T> {
1629    fn drop(&mut self) {
1630        let initialized_part = &mut self.slice[..self.initialized];
1631        // SAFETY: this raw sub-slice will contain only initialized objects.
1632        unsafe {
1633            initialized_part.assume_init_drop();
1634        }
1635    }
1636}
1637
1638trait SpecFill<T> {
1639    fn spec_fill(&mut self, value: T);
1640}
1641
1642impl<T: Clone> SpecFill<T> for [MaybeUninit<T>] {
1643    default fn spec_fill(&mut self, value: T) {
1644        let mut guard = Guard { slice: self, initialized: 0 };
1645
1646        if let Some((last, elems)) = guard.slice.split_last_mut() {
1647            for el in elems {
1648                el.write(value.clone());
1649                guard.initialized += 1;
1650            }
1651
1652            last.write(value);
1653        }
1654        super::forget(guard);
1655    }
1656}
1657
1658impl<T: TrivialClone> SpecFill<T> for [MaybeUninit<T>] {
1659    fn spec_fill(&mut self, value: T) {
1660        // SAFETY: because `T` is `TrivialClone`, this is equivalent to calling
1661        // `T::clone` for every element. Notably, `TrivialClone` also implies
1662        // that the `clone` implementation will not panic, so we can avoid
1663        // initialization guards and such.
1664        self.fill_with(|| MaybeUninit::new(unsafe { ptr::read(&value) }));
1665    }
1666}