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 are not
441    /// guaranteed to be zeroed.
442    ///
443    /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
444    /// It is your responsibility to make sure `T` gets dropped if it got initialized.
445    ///
446    /// # Example
447    ///
448    /// Correct usage of this function: initializing a struct with zero, where all
449    /// fields of the struct can hold the bit-pattern 0 as a valid value.
450    ///
451    /// ```rust
452    /// use std::mem::MaybeUninit;
453    ///
454    /// let x = MaybeUninit::<(u8, bool)>::zeroed();
455    /// let x = unsafe { x.assume_init() };
456    /// assert_eq!(x, (0, false));
457    /// ```
458    ///
459    /// This can be used in const contexts, such as to indicate the end of static arrays for
460    /// plugin registration.
461    ///
462    /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
463    /// when `0` is not a valid bit-pattern for the type:
464    ///
465    /// ```rust,no_run
466    /// use std::mem::MaybeUninit;
467    ///
468    /// enum NotZero { One = 1, Two = 2 }
469    ///
470    /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
471    /// let x = unsafe { x.assume_init() };
472    /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
473    /// // This is undefined behavior. ⚠️
474    /// ```
475    #[inline]
476    #[must_use]
477    #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
478    #[stable(feature = "maybe_uninit", since = "1.36.0")]
479    #[rustc_const_stable(feature = "const_maybe_uninit_zeroed", since = "1.75.0")]
480    pub const fn zeroed() -> MaybeUninit<T> {
481        let mut u = MaybeUninit::<T>::uninit();
482        // SAFETY: `u.as_mut_ptr()` points to allocated memory.
483        unsafe { u.as_mut_ptr().write_bytes(0u8, 1) };
484        u
485    }
486
487    /// Sets the value of the `MaybeUninit<T>`.
488    ///
489    /// This overwrites any previous value without dropping it, so be careful
490    /// not to use this twice unless you want to skip running the destructor.
491    /// For your convenience, this also returns a mutable reference to the
492    /// (now safely initialized) contents of `self`.
493    ///
494    /// As the content is stored inside a `ManuallyDrop`, the destructor is not
495    /// run for the inner data if the MaybeUninit leaves scope without a call to
496    /// [`assume_init`], [`assume_init_drop`], or similar. Code that receives
497    /// the mutable reference returned by this function needs to keep this in
498    /// mind. The safety model of Rust regards leaks as safe, but they are
499    /// usually still undesirable. This being said, the mutable reference
500    /// behaves like any other mutable reference would, so assigning a new value
501    /// to it will drop the old content.
502    ///
503    /// [`assume_init`]: Self::assume_init
504    /// [`assume_init_drop`]: Self::assume_init_drop
505    ///
506    /// # Examples
507    ///
508    /// Correct usage of this method:
509    ///
510    /// ```rust
511    /// use std::mem::MaybeUninit;
512    ///
513    /// let mut x = MaybeUninit::<Vec<u8>>::uninit();
514    ///
515    /// {
516    ///     let hello = x.write((&b"Hello, world!").to_vec());
517    ///     // Setting hello does not leak prior allocations, but drops them
518    ///     *hello = (&b"Hello").to_vec();
519    ///     hello[0] = 'h' as u8;
520    /// }
521    /// // x is initialized now:
522    /// let s = unsafe { x.assume_init() };
523    /// assert_eq!(b"hello", s.as_slice());
524    /// ```
525    ///
526    /// This usage of the method causes a leak:
527    ///
528    /// ```rust
529    /// use std::mem::MaybeUninit;
530    ///
531    /// let mut x = MaybeUninit::<String>::uninit();
532    ///
533    /// x.write("Hello".to_string());
534    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
535    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
536    /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
537    /// // This leaks the contained string:
538    /// x.write("hello".to_string());
539    /// // x is initialized now:
540    /// let s = unsafe { x.assume_init() };
541    /// ```
542    ///
543    /// This method can be used to avoid unsafe in some cases. The example below
544    /// shows a part of an implementation of a fixed sized arena that lends out
545    /// pinned references.
546    /// With `write`, we can avoid the need to write through a raw pointer:
547    ///
548    /// ```rust
549    /// use core::pin::Pin;
550    /// use core::mem::MaybeUninit;
551    ///
552    /// struct PinArena<T> {
553    ///     memory: Box<[MaybeUninit<T>]>,
554    ///     len: usize,
555    /// }
556    ///
557    /// impl <T> PinArena<T> {
558    ///     pub fn capacity(&self) -> usize {
559    ///         self.memory.len()
560    ///     }
561    ///     pub fn push(&mut self, val: T) -> Pin<&mut T> {
562    ///         if self.len >= self.capacity() {
563    ///             panic!("Attempted to push to a full pin arena!");
564    ///         }
565    ///         let ref_ = self.memory[self.len].write(val);
566    ///         self.len += 1;
567    ///         unsafe { Pin::new_unchecked(ref_) }
568    ///     }
569    /// }
570    /// ```
571    #[inline(always)]
572    #[stable(feature = "maybe_uninit_write", since = "1.55.0")]
573    #[rustc_const_stable(feature = "const_maybe_uninit_write", since = "1.85.0")]
574    pub const fn write(&mut self, val: T) -> &mut T {
575        *self = MaybeUninit::new(val);
576        // SAFETY: We just initialized this value.
577        unsafe { self.assume_init_mut() }
578    }
579
580    /// Gets a pointer to the contained value. Reading from this pointer or turning it
581    /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
582    /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
583    /// (except inside an `UnsafeCell<T>`).
584    ///
585    /// # Examples
586    ///
587    /// Correct usage of this method:
588    ///
589    /// ```rust
590    /// use std::mem::MaybeUninit;
591    ///
592    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
593    /// x.write(vec![0, 1, 2]);
594    /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
595    /// let x_vec = unsafe { &*x.as_ptr() };
596    /// assert_eq!(x_vec.len(), 3);
597    /// # // Prevent leaks for Miri
598    /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
599    /// ```
600    ///
601    /// *Incorrect* usage of this method:
602    ///
603    /// ```rust,no_run
604    /// use std::mem::MaybeUninit;
605    ///
606    /// let x = MaybeUninit::<Vec<u32>>::uninit();
607    /// let x_vec = unsafe { &*x.as_ptr() };
608    /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
609    /// ```
610    ///
611    /// (Notice that the rules around references to uninitialized data are not finalized yet, but
612    /// until they are, it is advisable to avoid them.)
613    #[stable(feature = "maybe_uninit", since = "1.36.0")]
614    #[rustc_const_stable(feature = "const_maybe_uninit_as_ptr", since = "1.59.0")]
615    #[rustc_as_ptr]
616    #[inline(always)]
617    pub const fn as_ptr(&self) -> *const T {
618        // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
619        self as *const _ as *const T
620    }
621
622    /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
623    /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
624    ///
625    /// # Examples
626    ///
627    /// Correct usage of this method:
628    ///
629    /// ```rust
630    /// use std::mem::MaybeUninit;
631    ///
632    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
633    /// x.write(vec![0, 1, 2]);
634    /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
635    /// // This is okay because we initialized it.
636    /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
637    /// x_vec.push(3);
638    /// assert_eq!(x_vec.len(), 4);
639    /// # // Prevent leaks for Miri
640    /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
641    /// ```
642    ///
643    /// *Incorrect* usage of this method:
644    ///
645    /// ```rust,no_run
646    /// use std::mem::MaybeUninit;
647    ///
648    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
649    /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
650    /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
651    /// ```
652    ///
653    /// (Notice that the rules around references to uninitialized data are not finalized yet, but
654    /// until they are, it is advisable to avoid them.)
655    #[stable(feature = "maybe_uninit", since = "1.36.0")]
656    #[rustc_const_stable(feature = "const_maybe_uninit_as_mut_ptr", since = "1.83.0")]
657    #[rustc_as_ptr]
658    #[inline(always)]
659    pub const fn as_mut_ptr(&mut self) -> *mut T {
660        // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
661        self as *mut _ as *mut T
662    }
663
664    /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
665    /// to ensure that the data will get dropped, because the resulting `T` is
666    /// subject to the usual drop handling.
667    ///
668    /// # Safety
669    ///
670    /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
671    /// state, i.e., a state that is considered ["valid" for type `T`][validity]. Calling this when
672    /// the content is not yet fully initialized causes immediate undefined behavior. The
673    /// [type-level documentation][inv] contains more information about this initialization
674    /// invariant.
675    ///
676    /// It is a common mistake to assume that this function is safe to call on integers because they
677    /// can hold all bit patterns. It is also a common mistake to think that calling this function
678    /// is UB if any byte is uninitialized. Both of these assumptions are wrong. If that is
679    /// surprising to you, please read the [type-level documentation][inv].
680    ///
681    /// [inv]: #initialization-invariant
682    /// [validity]: ../../reference/behavior-considered-undefined.html#r-undefined.validity
683    ///
684    /// On top of that, remember that most types have additional invariants beyond merely
685    /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
686    /// is considered initialized (under the current implementation; this does not constitute
687    /// a stable guarantee) because the only requirement the compiler knows about it
688    /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
689    /// *immediate* undefined behavior, but will cause undefined behavior with most
690    /// safe operations (including dropping it).
691    ///
692    /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
693    ///
694    /// # Examples
695    ///
696    /// Correct usage of this method:
697    ///
698    /// ```rust
699    /// use std::mem::MaybeUninit;
700    ///
701    /// let mut x = MaybeUninit::<bool>::uninit();
702    /// x.write(true);
703    /// let x_init = unsafe { x.assume_init() };
704    /// assert_eq!(x_init, true);
705    /// ```
706    ///
707    /// *Incorrect* usage of this method:
708    ///
709    /// ```rust,no_run
710    /// # #![allow(invalid_value)]
711    /// use std::mem::MaybeUninit;
712    ///
713    /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
714    /// ```
715    ///
716    /// See the [type-level documentation][#examples] for more examples.
717    #[stable(feature = "maybe_uninit", since = "1.36.0")]
718    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_by_value", since = "1.59.0")]
719    #[inline(always)]
720    #[rustc_diagnostic_item = "assume_init"]
721    #[track_caller]
722    pub const unsafe fn assume_init(self) -> T {
723        // SAFETY: the caller must guarantee that `self` is initialized.
724        // This also means that `self` must be a `value` variant.
725        unsafe {
726            intrinsics::assert_inhabited::<T>();
727            // We do this via a raw ptr read instead of `ManuallyDrop::into_inner` so that there's
728            // no trace of `ManuallyDrop` in Miri's error messages here.
729            (&raw const self.value).cast::<T>().read()
730        }
731    }
732
733    /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
734    /// to the usual drop handling.
735    ///
736    /// Whenever possible, it is preferable to use [`assume_init`] instead, which
737    /// prevents duplicating the content of the `MaybeUninit<T>`.
738    ///
739    /// # Safety
740    ///
741    /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
742    /// state. Calling this when the content is not yet fully initialized causes undefined
743    /// behavior. The [type-level documentation][inv] contains more information about
744    /// this initialization invariant.
745    ///
746    /// Moreover, similar to the [`ptr::read`] function, this function creates a
747    /// bitwise copy of the contents, regardless whether the contained type
748    /// implements the [`Copy`] trait or not. When using multiple copies of the
749    /// data (by calling `assume_init_read` multiple times, or first calling
750    /// `assume_init_read` and then [`assume_init`]), it is your responsibility
751    /// to ensure that data may indeed be duplicated.
752    ///
753    /// [inv]: #initialization-invariant
754    /// [`assume_init`]: MaybeUninit::assume_init
755    ///
756    /// # Examples
757    ///
758    /// Correct usage of this method:
759    ///
760    /// ```rust
761    /// use std::mem::MaybeUninit;
762    ///
763    /// let mut x = MaybeUninit::<u32>::uninit();
764    /// x.write(13);
765    /// let x1 = unsafe { x.assume_init_read() };
766    /// // `u32` is `Copy`, so we may read multiple times.
767    /// let x2 = unsafe { x.assume_init_read() };
768    /// assert_eq!(x1, x2);
769    ///
770    /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
771    /// x.write(None);
772    /// let x1 = unsafe { x.assume_init_read() };
773    /// // Duplicating a `None` value is okay, so we may read multiple times.
774    /// let x2 = unsafe { x.assume_init_read() };
775    /// assert_eq!(x1, x2);
776    /// ```
777    ///
778    /// *Incorrect* usage of this method:
779    ///
780    /// ```rust,no_run
781    /// use std::mem::MaybeUninit;
782    ///
783    /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
784    /// x.write(Some(vec![0, 1, 2]));
785    /// let x1 = unsafe { x.assume_init_read() };
786    /// let x2 = unsafe { x.assume_init_read() };
787    /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
788    /// // they both get dropped!
789    /// ```
790    #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
791    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_read", since = "1.75.0")]
792    #[inline(always)]
793    #[track_caller]
794    pub const unsafe fn assume_init_read(&self) -> T {
795        // SAFETY: the caller must guarantee that `self` is initialized.
796        // Reading from `self.as_ptr()` is safe since `self` should be initialized.
797        unsafe {
798            intrinsics::assert_inhabited::<T>();
799            self.as_ptr().read()
800        }
801    }
802
803    /// Drops the contained value in place.
804    ///
805    /// If you have ownership of the `MaybeUninit`, you can also use
806    /// [`assume_init`] as an alternative.
807    ///
808    /// # Safety
809    ///
810    /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
811    /// in an initialized state. Calling this when the content is not yet fully
812    /// initialized causes undefined behavior.
813    ///
814    /// On top of that, all additional invariants of the type `T` must be
815    /// satisfied, as the `Drop` implementation of `T` (or its members) may
816    /// rely on this. For example, setting a `Vec<T>` to an invalid but
817    /// non-null address makes it initialized (under the current implementation;
818    /// this does not constitute a stable guarantee), because the only
819    /// requirement the compiler knows about it is that the data pointer must be
820    /// non-null. Dropping such a `Vec<T>` however will cause undefined
821    /// behavior.
822    ///
823    /// [`assume_init`]: MaybeUninit::assume_init
824    #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
825    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
826    pub const unsafe fn assume_init_drop(&mut self)
827    where
828        T: [const] Destruct,
829    {
830        // SAFETY: the caller must guarantee that `self` is initialized and
831        // satisfies all invariants of `T`.
832        // Dropping the value in place is safe if that is the case.
833        unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
834    }
835
836    /// Gets a shared reference to the contained value.
837    ///
838    /// This can be useful when we want to access a `MaybeUninit` that has been
839    /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
840    /// of `.assume_init()`).
841    ///
842    /// # Safety
843    ///
844    /// Calling this when the content is not yet fully initialized causes undefined
845    /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
846    /// is in an initialized state.
847    ///
848    /// # Examples
849    ///
850    /// ### Correct usage of this method:
851    ///
852    /// ```rust
853    /// use std::mem::MaybeUninit;
854    ///
855    /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
856    /// # let mut x_mu = x;
857    /// # let mut x = &mut x_mu;
858    /// // Initialize `x`:
859    /// x.write(vec![1, 2, 3]);
860    /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
861    /// // create a shared reference to it:
862    /// let x: &Vec<u32> = unsafe {
863    ///     // SAFETY: `x` has been initialized.
864    ///     x.assume_init_ref()
865    /// };
866    /// assert_eq!(x, &vec![1, 2, 3]);
867    /// # // Prevent leaks for Miri
868    /// # unsafe { MaybeUninit::assume_init_drop(&mut x_mu); }
869    /// ```
870    ///
871    /// ### *Incorrect* usages of this method:
872    ///
873    /// ```rust,no_run
874    /// use std::mem::MaybeUninit;
875    ///
876    /// let x = MaybeUninit::<Vec<u32>>::uninit();
877    /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
878    /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
879    /// ```
880    ///
881    /// ```rust,no_run
882    /// use std::{cell::Cell, mem::MaybeUninit};
883    ///
884    /// let b = MaybeUninit::<Cell<bool>>::uninit();
885    /// // Initialize the `MaybeUninit` using `Cell::set`:
886    /// unsafe {
887    ///     b.assume_init_ref().set(true);
888    ///     //^^^^^^^^^^^^^^^ Reference to an uninitialized `Cell<bool>`: UB!
889    /// }
890    /// ```
891    #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
892    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_ref", since = "1.59.0")]
893    #[inline(always)]
894    pub const unsafe fn assume_init_ref(&self) -> &T {
895        // SAFETY: the caller must guarantee that `self` is initialized.
896        // This also means that `self` must be a `value` variant.
897        unsafe {
898            intrinsics::assert_inhabited::<T>();
899            &*self.as_ptr()
900        }
901    }
902
903    /// Gets a mutable (unique) reference to the contained value.
904    ///
905    /// This can be useful when we want to access a `MaybeUninit` that has been
906    /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
907    /// of `.assume_init()`).
908    ///
909    /// # Safety
910    ///
911    /// Calling this when the content is not yet fully initialized causes undefined
912    /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
913    /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
914    /// initialize a `MaybeUninit`.
915    ///
916    /// # Examples
917    ///
918    /// ### Correct usage of this method:
919    ///
920    /// ```rust
921    /// # #![allow(unexpected_cfgs)]
922    /// use std::mem::MaybeUninit;
923    ///
924    /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { unsafe { *buf = [0; 1024] } }
925    /// # #[cfg(FALSE)]
926    /// extern "C" {
927    ///     /// Initializes *all* the bytes of the input buffer.
928    ///     fn initialize_buffer(buf: *mut [u8; 1024]);
929    /// }
930    ///
931    /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
932    ///
933    /// // Initialize `buf`:
934    /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
935    /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
936    /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes.
937    /// // To assert our buffer has been initialized without copying it, we upgrade
938    /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`:
939    /// let buf: &mut [u8; 1024] = unsafe {
940    ///     // SAFETY: `buf` has been initialized.
941    ///     buf.assume_init_mut()
942    /// };
943    ///
944    /// // Now we can use `buf` as a normal slice:
945    /// buf.sort_unstable();
946    /// assert!(
947    ///     buf.windows(2).all(|pair| pair[0] <= pair[1]),
948    ///     "buffer is sorted",
949    /// );
950    /// ```
951    ///
952    /// ### *Incorrect* usages of this method:
953    ///
954    /// You cannot use `.assume_init_mut()` to initialize a value:
955    ///
956    /// ```rust,no_run
957    /// use std::mem::MaybeUninit;
958    ///
959    /// let mut b = MaybeUninit::<bool>::uninit();
960    /// unsafe {
961    ///     *b.assume_init_mut() = true;
962    ///     // We have created a (mutable) reference to an uninitialized `bool`!
963    ///     // This is undefined behavior. ⚠️
964    /// }
965    /// ```
966    ///
967    /// For instance, you cannot [`Read`] into an uninitialized buffer:
968    ///
969    /// [`Read`]: ../../std/io/trait.Read.html
970    ///
971    /// ```rust,no_run
972    /// use std::{io, mem::MaybeUninit};
973    ///
974    /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
975    /// {
976    ///     let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
977    ///     reader.read_exact(unsafe { buffer.assume_init_mut() })?;
978    ///     //                         ^^^^^^^^^^^^^^^^^^^^^^^^
979    ///     // (mutable) reference to uninitialized memory!
980    ///     // This is undefined behavior.
981    ///     Ok(unsafe { buffer.assume_init() })
982    /// }
983    /// ```
984    ///
985    /// Nor can you use direct field access to do field-by-field gradual initialization:
986    ///
987    /// ```rust,no_run
988    /// use std::{mem::MaybeUninit, ptr};
989    ///
990    /// struct Foo {
991    ///     a: u32,
992    ///     b: u8,
993    /// }
994    ///
995    /// let foo: Foo = unsafe {
996    ///     let mut foo = MaybeUninit::<Foo>::uninit();
997    ///     ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
998    ///     //              ^^^^^^^^^^^^^^^^^^^^^
999    ///     // (mutable) reference to uninitialized memory!
1000    ///     // This is undefined behavior.
1001    ///     ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
1002    ///     //              ^^^^^^^^^^^^^^^^^^^^^
1003    ///     // (mutable) reference to uninitialized memory!
1004    ///     // This is undefined behavior.
1005    ///     foo.assume_init()
1006    /// };
1007    /// ```
1008    #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
1009    #[rustc_const_stable(feature = "const_maybe_uninit_assume_init", since = "1.84.0")]
1010    #[inline(always)]
1011    pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
1012        // SAFETY: the caller must guarantee that `self` is initialized.
1013        // This also means that `self` must be a `value` variant.
1014        unsafe {
1015            intrinsics::assert_inhabited::<T>();
1016            &mut *self.as_mut_ptr()
1017        }
1018    }
1019
1020    /// Extracts the values from an array of `MaybeUninit` containers.
1021    ///
1022    /// # Safety
1023    ///
1024    /// It is up to the caller to guarantee that all elements of the array are
1025    /// in an initialized state.
1026    ///
1027    /// # Examples
1028    ///
1029    /// ```
1030    /// #![feature(maybe_uninit_array_assume_init)]
1031    /// use std::mem::MaybeUninit;
1032    ///
1033    /// let mut array: [MaybeUninit<i32>; 3] = [MaybeUninit::uninit(); 3];
1034    /// array[0].write(0);
1035    /// array[1].write(1);
1036    /// array[2].write(2);
1037    ///
1038    /// // SAFETY: Now safe as we initialised all elements
1039    /// let array = unsafe {
1040    ///     MaybeUninit::array_assume_init(array)
1041    /// };
1042    ///
1043    /// assert_eq!(array, [0, 1, 2]);
1044    /// ```
1045    #[unstable(feature = "maybe_uninit_array_assume_init", issue = "96097")]
1046    #[inline(always)]
1047    #[track_caller]
1048    pub const unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
1049        // SAFETY:
1050        // * The caller guarantees that all elements of the array are initialized
1051        // * `MaybeUninit<T>` and T are guaranteed to have the same layout
1052        // * `MaybeUninit` does not drop, so there are no double-frees
1053        // And thus the conversion is safe
1054        unsafe {
1055            intrinsics::assert_inhabited::<[T; N]>();
1056            intrinsics::transmute_unchecked(array)
1057        }
1058    }
1059
1060    /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1061    ///
1062    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1063    /// contain padding bytes which are left uninitialized.
1064    ///
1065    /// # Examples
1066    ///
1067    /// ```
1068    /// #![feature(maybe_uninit_as_bytes)]
1069    /// use std::mem::MaybeUninit;
1070    ///
1071    /// let val = 0x12345678_i32;
1072    /// let uninit = MaybeUninit::new(val);
1073    /// let uninit_bytes = uninit.as_bytes();
1074    /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1075    /// assert_eq!(bytes, val.to_ne_bytes());
1076    /// ```
1077    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1078    pub const fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1079        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1080        unsafe {
1081            slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of::<T>())
1082        }
1083    }
1084
1085    /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized
1086    /// bytes.
1087    ///
1088    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1089    /// contain padding bytes which are left uninitialized.
1090    ///
1091    /// # Examples
1092    ///
1093    /// ```
1094    /// #![feature(maybe_uninit_as_bytes)]
1095    /// use std::mem::MaybeUninit;
1096    ///
1097    /// let val = 0x12345678_i32;
1098    /// let mut uninit = MaybeUninit::new(val);
1099    /// let uninit_bytes = uninit.as_bytes_mut();
1100    /// if cfg!(target_endian = "little") {
1101    ///     uninit_bytes[0].write(0xcd);
1102    /// } else {
1103    ///     uninit_bytes[3].write(0xcd);
1104    /// }
1105    /// let val2 = unsafe { uninit.assume_init() };
1106    /// assert_eq!(val2, 0x123456cd);
1107    /// ```
1108    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1109    pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1110        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1111        unsafe {
1112            slice::from_raw_parts_mut(
1113                self.as_mut_ptr().cast::<MaybeUninit<u8>>(),
1114                super::size_of::<T>(),
1115            )
1116        }
1117    }
1118}
1119
1120impl<T> [MaybeUninit<T>] {
1121    /// Copies the elements from `src` to `self`,
1122    /// returning a mutable reference to the now initialized contents of `self`.
1123    ///
1124    /// If `T` does not implement `Copy`, use [`write_clone_of_slice`] instead.
1125    ///
1126    /// This is similar to [`slice::copy_from_slice`].
1127    ///
1128    /// # Panics
1129    ///
1130    /// This function will panic if the two slices have different lengths.
1131    ///
1132    /// # Examples
1133    ///
1134    /// ```
1135    /// use std::mem::MaybeUninit;
1136    ///
1137    /// let mut dst = [MaybeUninit::uninit(); 32];
1138    /// let src = [0; 32];
1139    ///
1140    /// let init = dst.write_copy_of_slice(&src);
1141    ///
1142    /// assert_eq!(init, src);
1143    /// ```
1144    ///
1145    /// ```
1146    /// let mut vec = Vec::with_capacity(32);
1147    /// let src = [0; 16];
1148    ///
1149    /// vec.spare_capacity_mut()[..src.len()].write_copy_of_slice(&src);
1150    ///
1151    /// // SAFETY: we have just copied all the elements of len into the spare capacity
1152    /// // the first src.len() elements of the vec are valid now.
1153    /// unsafe {
1154    ///     vec.set_len(src.len());
1155    /// }
1156    ///
1157    /// assert_eq!(vec, src);
1158    /// ```
1159    ///
1160    /// [`write_clone_of_slice`]: slice::write_clone_of_slice
1161    #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1162    #[rustc_const_stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1163    pub const fn write_copy_of_slice(&mut self, src: &[T]) -> &mut [T]
1164    where
1165        T: Copy,
1166    {
1167        // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1168        let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1169
1170        self.copy_from_slice(uninit_src);
1171
1172        // SAFETY: Valid elements have just been copied into `self` so it is initialized
1173        unsafe { self.assume_init_mut() }
1174    }
1175
1176    /// Clones the elements from `src` to `self`,
1177    /// returning a mutable reference to the now initialized contents of `self`.
1178    /// Any already initialized elements will not be dropped.
1179    ///
1180    /// If `T` implements `Copy`, use [`write_copy_of_slice`] instead.
1181    ///
1182    /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1183    ///
1184    /// # Panics
1185    ///
1186    /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1187    ///
1188    /// If there is a panic, the already cloned elements will be dropped.
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```
1193    /// use std::mem::MaybeUninit;
1194    ///
1195    /// let mut dst = [const { MaybeUninit::uninit() }; 5];
1196    /// let src = ["wibbly", "wobbly", "timey", "wimey", "stuff"].map(|s| s.to_string());
1197    ///
1198    /// let init = dst.write_clone_of_slice(&src);
1199    ///
1200    /// assert_eq!(init, src);
1201    ///
1202    /// # // Prevent leaks for Miri
1203    /// # unsafe { std::ptr::drop_in_place(init); }
1204    /// ```
1205    ///
1206    /// ```
1207    /// let mut vec = Vec::with_capacity(32);
1208    /// let src = ["rust", "is", "a", "pretty", "cool", "language"].map(|s| s.to_string());
1209    ///
1210    /// vec.spare_capacity_mut()[..src.len()].write_clone_of_slice(&src);
1211    ///
1212    /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1213    /// // the first src.len() elements of the vec are valid now.
1214    /// unsafe {
1215    ///     vec.set_len(src.len());
1216    /// }
1217    ///
1218    /// assert_eq!(vec, src);
1219    /// ```
1220    ///
1221    /// [`write_copy_of_slice`]: slice::write_copy_of_slice
1222    #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1223    pub fn write_clone_of_slice(&mut self, src: &[T]) -> &mut [T]
1224    where
1225        T: Clone,
1226    {
1227        // unlike copy_from_slice this does not call clone_from_slice on the slice
1228        // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1229
1230        assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
1231
1232        // NOTE: We need to explicitly slice them to the same length
1233        // for bounds checking to be elided, and the optimizer will
1234        // generate memcpy for simple cases (for example T = u8).
1235        let len = self.len();
1236        let src = &src[..len];
1237
1238        // guard is needed b/c panic might happen during a clone
1239        let mut guard = Guard { slice: self, initialized: 0 };
1240
1241        for i in 0..len {
1242            guard.slice[i].write(src[i].clone());
1243            guard.initialized += 1;
1244        }
1245
1246        super::forget(guard);
1247
1248        // SAFETY: Valid elements have just been written into `self` so it is initialized
1249        unsafe { self.assume_init_mut() }
1250    }
1251
1252    /// Fills a slice with elements by cloning `value`, returning a mutable reference to the now
1253    /// initialized contents of the slice.
1254    /// Any previously initialized elements will not be dropped.
1255    ///
1256    /// This is similar to [`slice::fill`].
1257    ///
1258    /// # Panics
1259    ///
1260    /// This function will panic if any call to `Clone` panics.
1261    ///
1262    /// If such a panic occurs, any elements previously initialized during this operation will be
1263    /// dropped.
1264    ///
1265    /// # Examples
1266    ///
1267    /// ```
1268    /// #![feature(maybe_uninit_fill)]
1269    /// use std::mem::MaybeUninit;
1270    ///
1271    /// let mut buf = [const { MaybeUninit::uninit() }; 10];
1272    /// let initialized = buf.write_filled(1);
1273    /// assert_eq!(initialized, &mut [1; 10]);
1274    /// ```
1275    #[doc(alias = "memset")]
1276    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1277    pub fn write_filled(&mut self, value: T) -> &mut [T]
1278    where
1279        T: Clone,
1280    {
1281        SpecFill::spec_fill(self, value);
1282        // SAFETY: Valid elements have just been filled into `self` so it is initialized
1283        unsafe { self.assume_init_mut() }
1284    }
1285
1286    /// Fills a slice with elements returned by calling a closure for each index.
1287    ///
1288    /// This method uses a closure to create new values. If you'd rather `Clone` a given value, use
1289    /// [slice::write_filled]. If you want to use the `Default` trait to generate values, you can
1290    /// pass [`|_| Default::default()`][Default::default] as the argument.
1291    ///
1292    /// # Panics
1293    ///
1294    /// This function will panic if any call to the provided closure panics.
1295    ///
1296    /// If such a panic occurs, any elements previously initialized during this operation will be
1297    /// dropped.
1298    ///
1299    /// # Examples
1300    ///
1301    /// ```
1302    /// #![feature(maybe_uninit_fill)]
1303    /// use std::mem::MaybeUninit;
1304    ///
1305    /// let mut buf = [const { MaybeUninit::<usize>::uninit() }; 5];
1306    /// let initialized = buf.write_with(|idx| idx + 1);
1307    /// assert_eq!(initialized, &mut [1, 2, 3, 4, 5]);
1308    /// ```
1309    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1310    pub fn write_with<F>(&mut self, mut f: F) -> &mut [T]
1311    where
1312        F: FnMut(usize) -> T,
1313    {
1314        let mut guard = Guard { slice: self, initialized: 0 };
1315
1316        for (idx, element) in guard.slice.iter_mut().enumerate() {
1317            element.write(f(idx));
1318            guard.initialized += 1;
1319        }
1320
1321        super::forget(guard);
1322
1323        // SAFETY: Valid elements have just been written into `this` so it is initialized
1324        unsafe { self.assume_init_mut() }
1325    }
1326
1327    /// Fills a slice with elements yielded by an iterator until either all elements have been
1328    /// initialized or the iterator is empty.
1329    ///
1330    /// Returns two slices. The first slice contains the initialized portion of the original slice.
1331    /// The second slice is the still-uninitialized remainder of the original slice.
1332    ///
1333    /// # Panics
1334    ///
1335    /// This function panics if the iterator's `next` function panics.
1336    ///
1337    /// If such a panic occurs, any elements previously initialized during this operation will be
1338    /// dropped.
1339    ///
1340    /// # Examples
1341    ///
1342    /// Completely filling the slice:
1343    ///
1344    /// ```
1345    /// #![feature(maybe_uninit_fill)]
1346    /// use std::mem::MaybeUninit;
1347    ///
1348    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1349    ///
1350    /// let iter = [1, 2, 3].into_iter().cycle();
1351    /// let (initialized, remainder) = buf.write_iter(iter);
1352    ///
1353    /// assert_eq!(initialized, &mut [1, 2, 3, 1, 2]);
1354    /// assert_eq!(remainder.len(), 0);
1355    /// ```
1356    ///
1357    /// Partially filling the slice:
1358    ///
1359    /// ```
1360    /// #![feature(maybe_uninit_fill)]
1361    /// use std::mem::MaybeUninit;
1362    ///
1363    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1364    /// let iter = [1, 2];
1365    /// let (initialized, remainder) = buf.write_iter(iter);
1366    ///
1367    /// assert_eq!(initialized, &mut [1, 2]);
1368    /// assert_eq!(remainder.len(), 3);
1369    /// ```
1370    ///
1371    /// Checking an iterator after filling a slice:
1372    ///
1373    /// ```
1374    /// #![feature(maybe_uninit_fill)]
1375    /// use std::mem::MaybeUninit;
1376    ///
1377    /// let mut buf = [const { MaybeUninit::uninit() }; 3];
1378    /// let mut iter = [1, 2, 3, 4, 5].into_iter();
1379    /// let (initialized, remainder) = buf.write_iter(iter.by_ref());
1380    ///
1381    /// assert_eq!(initialized, &mut [1, 2, 3]);
1382    /// assert_eq!(remainder.len(), 0);
1383    /// assert_eq!(iter.as_slice(), &[4, 5]);
1384    /// ```
1385    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1386    pub fn write_iter<I>(&mut self, it: I) -> (&mut [T], &mut [MaybeUninit<T>])
1387    where
1388        I: IntoIterator<Item = T>,
1389    {
1390        let iter = it.into_iter();
1391        let mut guard = Guard { slice: self, initialized: 0 };
1392
1393        for (element, val) in guard.slice.iter_mut().zip(iter) {
1394            element.write(val);
1395            guard.initialized += 1;
1396        }
1397
1398        let initialized_len = guard.initialized;
1399        super::forget(guard);
1400
1401        // SAFETY: guard.initialized <= self.len()
1402        let (initted, remainder) = unsafe { self.split_at_mut_unchecked(initialized_len) };
1403
1404        // SAFETY: Valid elements have just been written into `init`, so that portion
1405        // of `this` is initialized.
1406        (unsafe { initted.assume_init_mut() }, remainder)
1407    }
1408
1409    /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1410    ///
1411    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1412    /// contain padding bytes which are left uninitialized.
1413    ///
1414    /// # Examples
1415    ///
1416    /// ```
1417    /// #![feature(maybe_uninit_as_bytes)]
1418    /// use std::mem::MaybeUninit;
1419    ///
1420    /// let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)];
1421    /// let uninit_bytes = uninit.as_bytes();
1422    /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1423    /// let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap());
1424    /// let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap());
1425    /// assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]);
1426    /// ```
1427    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1428    pub const fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1429        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1430        unsafe {
1431            slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of_val(self))
1432        }
1433    }
1434
1435    /// Returns the contents of this `MaybeUninit` slice as a mutable slice of potentially
1436    /// uninitialized bytes.
1437    ///
1438    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1439    /// contain padding bytes which are left uninitialized.
1440    ///
1441    /// # Examples
1442    ///
1443    /// ```
1444    /// #![feature(maybe_uninit_as_bytes)]
1445    /// use std::mem::MaybeUninit;
1446    ///
1447    /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()];
1448    /// let uninit_bytes = uninit.as_bytes_mut();
1449    /// uninit_bytes.write_copy_of_slice(&[0x12, 0x34, 0x56, 0x78]);
1450    /// let vals = unsafe { uninit.assume_init_ref() };
1451    /// if cfg!(target_endian = "little") {
1452    ///     assert_eq!(vals, &[0x3412u16, 0x7856u16]);
1453    /// } else {
1454    ///     assert_eq!(vals, &[0x1234u16, 0x5678u16]);
1455    /// }
1456    /// ```
1457    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1458    pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1459        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1460        unsafe {
1461            slice::from_raw_parts_mut(
1462                self.as_mut_ptr() as *mut MaybeUninit<u8>,
1463                super::size_of_val(self),
1464            )
1465        }
1466    }
1467
1468    /// Drops the contained values in place.
1469    ///
1470    /// # Safety
1471    ///
1472    /// It is up to the caller to guarantee that every `MaybeUninit<T>` in the slice
1473    /// really is in an initialized state. Calling this when the content is not yet
1474    /// fully initialized causes undefined behavior.
1475    ///
1476    /// On top of that, all additional invariants of the type `T` must be
1477    /// satisfied, as the `Drop` implementation of `T` (or its members) may
1478    /// rely on this. For example, setting a `Vec<T>` to an invalid but
1479    /// non-null address makes it initialized (under the current implementation;
1480    /// this does not constitute a stable guarantee), because the only
1481    /// requirement the compiler knows about it is that the data pointer must be
1482    /// non-null. Dropping such a `Vec<T>` however will cause undefined
1483    /// behaviour.
1484    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1485    #[inline(always)]
1486    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1487    pub const unsafe fn assume_init_drop(&mut self)
1488    where
1489        T: [const] Destruct,
1490    {
1491        if !self.is_empty() {
1492            // SAFETY: the caller must guarantee that every element of `self`
1493            // is initialized and satisfies all invariants of `T`.
1494            // Dropping the value in place is safe if that is the case.
1495            unsafe { ptr::drop_in_place(self as *mut [MaybeUninit<T>] as *mut [T]) }
1496        }
1497    }
1498
1499    /// Gets a shared reference to the contained value.
1500    ///
1501    /// # Safety
1502    ///
1503    /// Calling this when the content is not yet fully initialized causes undefined
1504    /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in
1505    /// the slice really is in an initialized state.
1506    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1507    #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1508    #[inline(always)]
1509    pub const unsafe fn assume_init_ref(&self) -> &[T] {
1510        // SAFETY: casting `slice` to a `*const [T]` is safe since the caller guarantees that
1511        // `slice` is initialized, and `MaybeUninit` is guaranteed to have the same layout as `T`.
1512        // The pointer obtained is valid since it refers to memory owned by `slice` which is a
1513        // reference and thus guaranteed to be valid for reads.
1514        unsafe { &*(self as *const Self as *const [T]) }
1515    }
1516
1517    /// Gets a mutable (unique) reference to the contained value.
1518    ///
1519    /// # Safety
1520    ///
1521    /// Calling this when the content is not yet fully initialized causes undefined
1522    /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in the
1523    /// slice really is in an initialized state. For instance, `.assume_init_mut()` cannot
1524    /// be used to initialize a `MaybeUninit` slice.
1525    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1526    #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1527    #[inline(always)]
1528    pub const unsafe fn assume_init_mut(&mut self) -> &mut [T] {
1529        // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
1530        // mutable reference which is also guaranteed to be valid for writes.
1531        unsafe { &mut *(self as *mut Self as *mut [T]) }
1532    }
1533}
1534
1535impl<T, const N: usize> MaybeUninit<[T; N]> {
1536    /// Transposes a `MaybeUninit<[T; N]>` into a `[MaybeUninit<T>; N]`.
1537    ///
1538    /// # Examples
1539    ///
1540    /// ```
1541    /// #![feature(maybe_uninit_uninit_array_transpose)]
1542    /// # use std::mem::MaybeUninit;
1543    ///
1544    /// let data: [MaybeUninit<u8>; 1000] = MaybeUninit::uninit().transpose();
1545    /// ```
1546    #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1547    #[inline]
1548    pub const fn transpose(self) -> [MaybeUninit<T>; N] {
1549        // SAFETY: T and MaybeUninit<T> have the same layout
1550        unsafe { intrinsics::transmute_unchecked(self) }
1551    }
1552}
1553
1554#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1555impl<T, const N: usize> From<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1556    #[inline]
1557    fn from(arr: [MaybeUninit<T>; N]) -> Self {
1558        arr.transpose()
1559    }
1560}
1561
1562#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1563impl<T, const N: usize> AsRef<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1564    #[inline]
1565    fn as_ref(&self) -> &[MaybeUninit<T>; N] {
1566        // SAFETY: T and MaybeUninit<T> have the same layout
1567        unsafe { &*ptr::from_ref(self).cast() }
1568    }
1569}
1570
1571#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1572impl<T, const N: usize> AsRef<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1573    #[inline]
1574    fn as_ref(&self) -> &[MaybeUninit<T>] {
1575        &*AsRef::<[MaybeUninit<T>; N]>::as_ref(self)
1576    }
1577}
1578
1579#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1580impl<T, const N: usize> AsMut<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1581    #[inline]
1582    fn as_mut(&mut self) -> &mut [MaybeUninit<T>; N] {
1583        // SAFETY: T and MaybeUninit<T> have the same layout
1584        unsafe { &mut *ptr::from_mut(self).cast() }
1585    }
1586}
1587
1588#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1589impl<T, const N: usize> AsMut<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1590    #[inline]
1591    fn as_mut(&mut self) -> &mut [MaybeUninit<T>] {
1592        &mut *AsMut::<[MaybeUninit<T>; N]>::as_mut(self)
1593    }
1594}
1595
1596#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1597impl<T, const N: usize> From<MaybeUninit<[T; N]>> for [MaybeUninit<T>; N] {
1598    #[inline]
1599    fn from(arr: MaybeUninit<[T; N]>) -> Self {
1600        arr.transpose()
1601    }
1602}
1603
1604impl<T, const N: usize> [MaybeUninit<T>; N] {
1605    /// Transposes a `[MaybeUninit<T>; N]` into a `MaybeUninit<[T; N]>`.
1606    ///
1607    /// # Examples
1608    ///
1609    /// ```
1610    /// #![feature(maybe_uninit_uninit_array_transpose)]
1611    /// # use std::mem::MaybeUninit;
1612    ///
1613    /// let data = [MaybeUninit::<u8>::uninit(); 1000];
1614    /// let data: MaybeUninit<[u8; 1000]> = data.transpose();
1615    /// ```
1616    #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1617    #[inline]
1618    pub const fn transpose(self) -> MaybeUninit<[T; N]> {
1619        // SAFETY: T and MaybeUninit<T> have the same layout
1620        unsafe { intrinsics::transmute_unchecked(self) }
1621    }
1622}
1623
1624struct Guard<'a, T> {
1625    slice: &'a mut [MaybeUninit<T>],
1626    initialized: usize,
1627}
1628
1629impl<'a, T> Drop for Guard<'a, T> {
1630    fn drop(&mut self) {
1631        let initialized_part = &mut self.slice[..self.initialized];
1632        // SAFETY: this raw sub-slice will contain only initialized objects.
1633        unsafe {
1634            initialized_part.assume_init_drop();
1635        }
1636    }
1637}
1638
1639trait SpecFill<T> {
1640    fn spec_fill(&mut self, value: T);
1641}
1642
1643impl<T: Clone> SpecFill<T> for [MaybeUninit<T>] {
1644    default fn spec_fill(&mut self, value: T) {
1645        let mut guard = Guard { slice: self, initialized: 0 };
1646
1647        if let Some((last, elems)) = guard.slice.split_last_mut() {
1648            for el in elems {
1649                el.write(value.clone());
1650                guard.initialized += 1;
1651            }
1652
1653            last.write(value);
1654        }
1655        super::forget(guard);
1656    }
1657}
1658
1659impl<T: TrivialClone> SpecFill<T> for [MaybeUninit<T>] {
1660    fn spec_fill(&mut self, value: T) {
1661        // SAFETY: because `T` is `TrivialClone`, this is equivalent to calling
1662        // `T::clone` for every element. Notably, `TrivialClone` also implies
1663        // that the `clone` implementation will not panic, so we can avoid
1664        // initialization guards and such.
1665        self.fill_with(|| MaybeUninit::new(unsafe { ptr::read(&value) }));
1666    }
1667}