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