Skip to main content

core/mem/
maybe_uninit.rs

1use crate::any::type_name;
2use crate::clone::TrivialClone;
3use crate::marker::{Destruct, Freeze};
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    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 transmute instead of `ManuallyDrop::into_inner` so that there's
728            // no trace of `ManuallyDrop` in Miri's error messages here.
729            transmute_neo(self)
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    /// This method requires `T: Freeze`. It's not available for types with interior mutability,
1066    /// such as `Cell<T>`.
1067    ///
1068    /// # Examples
1069    ///
1070    /// ```
1071    /// #![feature(maybe_uninit_as_bytes)]
1072    /// use std::mem::MaybeUninit;
1073    ///
1074    /// let val = 0x12345678_i32;
1075    /// let uninit = MaybeUninit::new(val);
1076    /// let uninit_bytes = uninit.as_bytes();
1077    /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1078    /// assert_eq!(bytes, val.to_ne_bytes());
1079    /// ```
1080    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1081    pub const fn as_bytes(&self) -> &[MaybeUninit<u8>]
1082    where
1083        T: Freeze,
1084    {
1085        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1086        unsafe {
1087            slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of::<T>())
1088        }
1089    }
1090
1091    /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized
1092    /// bytes.
1093    ///
1094    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1095    /// contain padding bytes which are left uninitialized.
1096    ///
1097    /// # Examples
1098    ///
1099    /// ```
1100    /// #![feature(maybe_uninit_as_bytes)]
1101    /// use std::mem::MaybeUninit;
1102    ///
1103    /// let val = 0x12345678_i32;
1104    /// let mut uninit = MaybeUninit::new(val);
1105    /// let uninit_bytes = uninit.as_bytes_mut();
1106    /// if cfg!(target_endian = "little") {
1107    ///     uninit_bytes[0].write(0xcd);
1108    /// } else {
1109    ///     uninit_bytes[3].write(0xcd);
1110    /// }
1111    /// let val2 = unsafe { uninit.assume_init() };
1112    /// assert_eq!(val2, 0x123456cd);
1113    /// ```
1114    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1115    pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1116        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1117        unsafe {
1118            slice::from_raw_parts_mut(
1119                self.as_mut_ptr().cast::<MaybeUninit<u8>>(),
1120                super::size_of::<T>(),
1121            )
1122        }
1123    }
1124
1125    /// Converts `&T` to `&MaybeUninit<T>`.
1126    ///
1127    /// The value stays initialized. This function changes only the type of the reference.
1128    ///
1129    /// There is no corresponding `from_mut` method, because it could allow writing uninitialized memory
1130    /// into the original value.
1131    ///
1132    /// # Examples
1133    ///
1134    /// ```
1135    /// #![feature(maybe_uninit_from_ref, maybe_uninit_as_bytes)]
1136    /// use std::mem::MaybeUninit;
1137    ///
1138    /// let val = 0x12345678_u32;
1139    /// let uninit = MaybeUninit::from_ref(&val);
1140    /// let bytes = uninit.as_bytes();
1141    ///
1142    /// // All bytes of a u32 are initialized, so assume_init is sound here:
1143    /// let byte_val = unsafe { bytes[0].assume_init() };
1144    /// assert_eq!(byte_val, val.to_ne_bytes()[0]);
1145    /// ```
1146    #[unstable(feature = "maybe_uninit_from_ref", issue = "165213")]
1147    #[inline]
1148    #[must_use]
1149    pub const fn from_ref(r: &T) -> &MaybeUninit<T> {
1150        // SAFETY: `MaybeUninit<T>` is repr(transparent) and every initialized T is a valid MaybeUninit<T>
1151        unsafe { &*ptr::from_ref(r).cast() }
1152    }
1153}
1154
1155impl<T> [MaybeUninit<T>] {
1156    /// Copies the elements from `src` to `self`,
1157    /// returning a mutable reference to the now initialized contents of `self`.
1158    ///
1159    /// If `T` does not implement `Copy`, use [`write_clone_of_slice`] instead.
1160    ///
1161    /// This is similar to [`slice::copy_from_slice`].
1162    ///
1163    /// # Panics
1164    ///
1165    /// This function will panic if the two slices have different lengths.
1166    ///
1167    /// # Examples
1168    ///
1169    /// ```
1170    /// use std::mem::MaybeUninit;
1171    ///
1172    /// let mut dst = [MaybeUninit::uninit(); 32];
1173    /// let src = [0; 32];
1174    ///
1175    /// let init = dst.write_copy_of_slice(&src);
1176    ///
1177    /// assert_eq!(init, src);
1178    /// ```
1179    ///
1180    /// ```
1181    /// let mut vec = Vec::with_capacity(32);
1182    /// let src = [0; 16];
1183    ///
1184    /// vec.spare_capacity_mut()[..src.len()].write_copy_of_slice(&src);
1185    ///
1186    /// // SAFETY: we have just copied all the elements of len into the spare capacity
1187    /// // the first src.len() elements of the vec are valid now.
1188    /// unsafe {
1189    ///     vec.set_len(src.len());
1190    /// }
1191    ///
1192    /// assert_eq!(vec, src);
1193    /// ```
1194    ///
1195    /// [`write_clone_of_slice`]: slice::write_clone_of_slice
1196    #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1197    #[rustc_const_stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1198    pub const fn write_copy_of_slice(&mut self, src: &[T]) -> &mut [T]
1199    where
1200        T: Copy,
1201    {
1202        // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1203        let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1204
1205        self.copy_from_slice(uninit_src);
1206
1207        // SAFETY: Valid elements have just been copied into `self` so it is initialized
1208        unsafe { self.assume_init_mut() }
1209    }
1210
1211    /// Clones the elements from `src` to `self`,
1212    /// returning a mutable reference to the now initialized contents of `self`.
1213    /// Any already initialized elements will not be dropped.
1214    ///
1215    /// If `T` implements `Copy`, use [`write_copy_of_slice`] instead.
1216    ///
1217    /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1218    ///
1219    /// # Panics
1220    ///
1221    /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1222    ///
1223    /// If there is a panic, the already cloned elements will be dropped.
1224    ///
1225    /// # Examples
1226    ///
1227    /// ```
1228    /// use std::mem::MaybeUninit;
1229    ///
1230    /// let mut dst = [const { MaybeUninit::uninit() }; 5];
1231    /// let src = ["wibbly", "wobbly", "timey", "wimey", "stuff"].map(|s| s.to_string());
1232    ///
1233    /// let init = dst.write_clone_of_slice(&src);
1234    ///
1235    /// assert_eq!(init, src);
1236    ///
1237    /// # // Prevent leaks for Miri
1238    /// # unsafe { std::ptr::drop_in_place(init); }
1239    /// ```
1240    ///
1241    /// ```
1242    /// let mut vec = Vec::with_capacity(32);
1243    /// let src = ["rust", "is", "a", "pretty", "cool", "language"].map(|s| s.to_string());
1244    ///
1245    /// vec.spare_capacity_mut()[..src.len()].write_clone_of_slice(&src);
1246    ///
1247    /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1248    /// // the first src.len() elements of the vec are valid now.
1249    /// unsafe {
1250    ///     vec.set_len(src.len());
1251    /// }
1252    ///
1253    /// assert_eq!(vec, src);
1254    /// ```
1255    ///
1256    /// [`write_copy_of_slice`]: slice::write_copy_of_slice
1257    #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1258    pub fn write_clone_of_slice(&mut self, src: &[T]) -> &mut [T]
1259    where
1260        T: Clone,
1261    {
1262        // unlike copy_from_slice this does not call clone_from_slice on the slice
1263        // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1264
1265        assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
1266
1267        // NOTE: We need to explicitly slice them to the same length
1268        // for bounds checking to be elided, and the optimizer will
1269        // generate memcpy for simple cases (for example T = u8).
1270        let len = self.len();
1271        let src = &src[..len];
1272
1273        // guard is needed b/c panic might happen during a clone
1274        let mut guard = Guard { slice: self, initialized: 0 };
1275
1276        for i in 0..len {
1277            guard.slice[i].write(src[i].clone());
1278            guard.initialized += 1;
1279        }
1280
1281        super::forget(guard);
1282
1283        // SAFETY: Valid elements have just been written into `self` so it is initialized
1284        unsafe { self.assume_init_mut() }
1285    }
1286
1287    /// Fills a slice with elements by cloning `value`, returning a mutable reference to the now
1288    /// initialized contents of the slice.
1289    /// Any previously initialized elements will not be dropped.
1290    ///
1291    /// This is similar to [`slice::fill`].
1292    ///
1293    /// # Panics
1294    ///
1295    /// This function will panic if any call to `Clone` panics.
1296    ///
1297    /// If such a panic occurs, any elements previously initialized during this operation will be
1298    /// dropped.
1299    ///
1300    /// # Examples
1301    ///
1302    /// ```
1303    /// #![feature(maybe_uninit_fill)]
1304    /// use std::mem::MaybeUninit;
1305    ///
1306    /// let mut buf = [const { MaybeUninit::uninit() }; 10];
1307    /// let initialized = buf.write_filled(1);
1308    /// assert_eq!(initialized, &mut [1; 10]);
1309    /// ```
1310    #[doc(alias = "memset")]
1311    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1312    pub fn write_filled(&mut self, value: T) -> &mut [T]
1313    where
1314        T: Clone,
1315    {
1316        SpecFill::spec_fill(self, value);
1317        // SAFETY: Valid elements have just been filled into `self` so it is initialized
1318        unsafe { self.assume_init_mut() }
1319    }
1320
1321    /// Fills a slice with elements returned by calling a closure for each index.
1322    ///
1323    /// This method uses a closure to create new values. If you'd rather `Clone` a given value, use
1324    /// [`slice::write_filled`]. If you want to use the `Default` trait to generate values, use
1325    /// [`slice::write_default`].
1326    ///
1327    /// # Panics
1328    ///
1329    /// This function will panic if any call to the provided closure panics.
1330    ///
1331    /// If such a panic occurs, any elements previously initialized during this operation will be
1332    /// dropped.
1333    ///
1334    /// # Examples
1335    ///
1336    /// ```
1337    /// #![feature(maybe_uninit_fill)]
1338    /// use std::mem::MaybeUninit;
1339    ///
1340    /// let mut buf = [const { MaybeUninit::<usize>::uninit() }; 5];
1341    /// let initialized = buf.write_with(|idx| idx + 1);
1342    /// assert_eq!(initialized, &mut [1, 2, 3, 4, 5]);
1343    /// ```
1344    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1345    pub fn write_with<F>(&mut self, mut f: F) -> &mut [T]
1346    where
1347        F: FnMut(usize) -> T,
1348    {
1349        let mut guard = Guard { slice: self, initialized: 0 };
1350
1351        for (idx, element) in guard.slice.iter_mut().enumerate() {
1352            element.write(f(idx));
1353            guard.initialized += 1;
1354        }
1355
1356        super::forget(guard);
1357
1358        // SAFETY: Valid elements have just been written into `this` so it is initialized
1359        unsafe { self.assume_init_mut() }
1360    }
1361
1362    /// Fills a slice with elements returned by calling [`Default::default`] for each index.
1363    ///
1364    /// # Panics
1365    ///
1366    /// This function will panic if any call to [`Default::default`] panics.
1367    ///
1368    /// If such a panic occurs, any elements previously initialized during this operation will be
1369    /// dropped.
1370    ///
1371    /// # Examples
1372    ///
1373    /// ```
1374    /// #![feature(maybe_uninit_fill)]
1375    /// use std::mem::MaybeUninit;
1376    ///
1377    /// let mut buf = [const { MaybeUninit::<usize>::uninit() }; 5];
1378    /// let initialized = buf.write_default();
1379    /// assert_eq!(initialized, &mut [0, 0, 0, 0, 0]);
1380    /// ```
1381    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1382    pub fn write_default(&mut self) -> &mut [T]
1383    where
1384        T: Default,
1385    {
1386        trait DefaultSpec: Default {
1387            fn write_default(buf: &mut [MaybeUninit<Self>]) -> &mut [Self];
1388        }
1389
1390        impl<T: Default> DefaultSpec for T {
1391            default fn write_default(buf: &mut [MaybeUninit<Self>]) -> &mut [Self] {
1392                buf.write_with(|_| T::default())
1393            }
1394        }
1395
1396        macro_rules! spec_default_zero {
1397            ($ty:ty) => {
1398                impl DefaultSpec for $ty {
1399                    fn write_default(buf: &mut [MaybeUninit<Self>]) -> &mut [Self] {
1400                        // SAFETY:
1401                        // `Default::default` is equivalent to zero-initialization
1402                        // for all these types, and this initializes the entire
1403                        // slice.
1404                        unsafe {
1405                            buf.as_mut_ptr().write_bytes(0, buf.len());
1406                            buf.assume_init_mut()
1407                        }
1408                    }
1409                }
1410            };
1411        }
1412
1413        spec_default_zero!(i8);
1414        spec_default_zero!(u8);
1415        spec_default_zero!(i16);
1416        spec_default_zero!(u16);
1417        spec_default_zero!(i32);
1418        spec_default_zero!(u32);
1419        spec_default_zero!(i64);
1420        spec_default_zero!(u64);
1421        spec_default_zero!(i128);
1422        spec_default_zero!(u128);
1423        spec_default_zero!(isize);
1424        spec_default_zero!(usize);
1425
1426        T::write_default(self)
1427    }
1428
1429    /// Fills a slice with elements yielded by an iterator until either all elements have been
1430    /// initialized or the iterator is empty.
1431    ///
1432    /// Returns two slices. The first slice contains the initialized portion of the original slice.
1433    /// The second slice is the still-uninitialized remainder of the original slice.
1434    ///
1435    /// # Panics
1436    ///
1437    /// This function panics if the iterator's `next` function panics.
1438    ///
1439    /// If such a panic occurs, any elements previously initialized during this operation will be
1440    /// dropped.
1441    ///
1442    /// # Examples
1443    ///
1444    /// Completely filling the slice:
1445    ///
1446    /// ```
1447    /// #![feature(maybe_uninit_fill)]
1448    /// use std::mem::MaybeUninit;
1449    ///
1450    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1451    ///
1452    /// let iter = [1, 2, 3].into_iter().cycle();
1453    /// let (initialized, remainder) = buf.write_iter(iter);
1454    ///
1455    /// assert_eq!(initialized, &mut [1, 2, 3, 1, 2]);
1456    /// assert_eq!(remainder.len(), 0);
1457    /// ```
1458    ///
1459    /// Partially filling the slice:
1460    ///
1461    /// ```
1462    /// #![feature(maybe_uninit_fill)]
1463    /// use std::mem::MaybeUninit;
1464    ///
1465    /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1466    /// let iter = [1, 2];
1467    /// let (initialized, remainder) = buf.write_iter(iter);
1468    ///
1469    /// assert_eq!(initialized, &mut [1, 2]);
1470    /// assert_eq!(remainder.len(), 3);
1471    /// ```
1472    ///
1473    /// Checking an iterator after filling a slice:
1474    ///
1475    /// ```
1476    /// #![feature(maybe_uninit_fill)]
1477    /// use std::mem::MaybeUninit;
1478    ///
1479    /// let mut buf = [const { MaybeUninit::uninit() }; 3];
1480    /// let mut iter = [1, 2, 3, 4, 5].into_iter();
1481    /// let (initialized, remainder) = buf.write_iter(iter.by_ref());
1482    ///
1483    /// assert_eq!(initialized, &mut [1, 2, 3]);
1484    /// assert_eq!(remainder.len(), 0);
1485    /// assert_eq!(iter.as_slice(), &[4, 5]);
1486    /// ```
1487    #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1488    pub fn write_iter<I>(&mut self, it: I) -> (&mut [T], &mut [MaybeUninit<T>])
1489    where
1490        I: IntoIterator<Item = T>,
1491    {
1492        let iter = it.into_iter();
1493        let mut guard = Guard { slice: self, initialized: 0 };
1494
1495        for (element, val) in guard.slice.iter_mut().zip(iter) {
1496            element.write(val);
1497            guard.initialized += 1;
1498        }
1499
1500        let initialized_len = guard.initialized;
1501        super::forget(guard);
1502
1503        // SAFETY: guard.initialized <= self.len()
1504        let (initted, remainder) = unsafe { self.split_at_mut_unchecked(initialized_len) };
1505
1506        // SAFETY: Valid elements have just been written into `init`, so that portion
1507        // of `this` is initialized.
1508        (unsafe { initted.assume_init_mut() }, remainder)
1509    }
1510
1511    /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1512    ///
1513    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1514    /// contain padding bytes which are left uninitialized.
1515    ///
1516    /// This method requires `T: Freeze`. It's not available for types with interior mutability,
1517    /// such as `Cell<T>`.
1518    ///
1519    /// # Examples
1520    ///
1521    /// ```
1522    /// #![feature(maybe_uninit_as_bytes)]
1523    /// use std::mem::MaybeUninit;
1524    ///
1525    /// let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)];
1526    /// let uninit_bytes = uninit.as_bytes();
1527    /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1528    /// let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap());
1529    /// let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap());
1530    /// assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]);
1531    /// ```
1532    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1533    pub const fn as_bytes(&self) -> &[MaybeUninit<u8>]
1534    where
1535        T: Freeze,
1536    {
1537        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1538        unsafe {
1539            slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of_val(self))
1540        }
1541    }
1542
1543    /// Returns the contents of this `MaybeUninit` slice as a mutable slice of potentially
1544    /// uninitialized bytes.
1545    ///
1546    /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1547    /// contain padding bytes which are left uninitialized.
1548    ///
1549    /// # Examples
1550    ///
1551    /// ```
1552    /// #![feature(maybe_uninit_as_bytes)]
1553    /// use std::mem::MaybeUninit;
1554    ///
1555    /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()];
1556    /// let uninit_bytes = uninit.as_bytes_mut();
1557    /// uninit_bytes.write_copy_of_slice(&[0x12, 0x34, 0x56, 0x78]);
1558    /// let vals = unsafe { uninit.assume_init_ref() };
1559    /// if cfg!(target_endian = "little") {
1560    ///     assert_eq!(vals, &[0x3412u16, 0x7856u16]);
1561    /// } else {
1562    ///     assert_eq!(vals, &[0x1234u16, 0x5678u16]);
1563    /// }
1564    /// ```
1565    #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1566    pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1567        // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1568        unsafe {
1569            slice::from_raw_parts_mut(
1570                self.as_mut_ptr() as *mut MaybeUninit<u8>,
1571                super::size_of_val(self),
1572            )
1573        }
1574    }
1575
1576    /// Drops the contained values in place.
1577    ///
1578    /// # Safety
1579    ///
1580    /// It is up to the caller to guarantee that every `MaybeUninit<T>` in the slice
1581    /// really is in an initialized state. Calling this when the content is not yet
1582    /// fully initialized causes undefined behavior.
1583    ///
1584    /// On top of that, all additional invariants of the type `T` must be
1585    /// satisfied, as the `Drop` implementation of `T` (or its members) may
1586    /// rely on this. For example, setting a `Vec<T>` to an invalid but
1587    /// non-null address makes it initialized (under the current implementation;
1588    /// this does not constitute a stable guarantee), because the only
1589    /// requirement the compiler knows about it is that the data pointer must be
1590    /// non-null. Dropping such a `Vec<T>` however will cause undefined
1591    /// behaviour.
1592    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1593    #[inline(always)]
1594    #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1595    pub const unsafe fn assume_init_drop(&mut self)
1596    where
1597        T: [const] Destruct,
1598    {
1599        if !self.is_empty() {
1600            // SAFETY: the caller must guarantee that every element of `self`
1601            // is initialized and satisfies all invariants of `T`.
1602            // Dropping the value in place is safe if that is the case.
1603            unsafe { ptr::drop_in_place(self as *mut [MaybeUninit<T>] as *mut [T]) }
1604        }
1605    }
1606
1607    /// Gets a shared reference to the contained value.
1608    ///
1609    /// # Safety
1610    ///
1611    /// Calling this when the content is not yet fully initialized causes undefined
1612    /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in
1613    /// the slice really is in an initialized state.
1614    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1615    #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1616    #[inline(always)]
1617    pub const unsafe fn assume_init_ref(&self) -> &[T] {
1618        // SAFETY: casting `slice` to a `*const [T]` is safe since the caller guarantees that
1619        // `slice` is initialized, and `MaybeUninit` is guaranteed to have the same layout as `T`.
1620        // The pointer obtained is valid since it refers to memory owned by `slice` which is a
1621        // reference and thus guaranteed to be valid for reads.
1622        unsafe { &*(self as *const Self as *const [T]) }
1623    }
1624
1625    /// Gets a mutable (unique) reference to the contained value.
1626    ///
1627    /// # Safety
1628    ///
1629    /// Calling this when the content is not yet fully initialized causes undefined
1630    /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in the
1631    /// slice really is in an initialized state. For instance, `.assume_init_mut()` cannot
1632    /// be used to initialize a `MaybeUninit` slice.
1633    #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1634    #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1635    #[inline(always)]
1636    pub const unsafe fn assume_init_mut(&mut self) -> &mut [T] {
1637        // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
1638        // mutable reference which is also guaranteed to be valid for writes.
1639        unsafe { &mut *(self as *mut Self as *mut [T]) }
1640    }
1641}
1642
1643impl<T, const N: usize> MaybeUninit<[T; N]> {
1644    /// Transposes a `MaybeUninit<[T; N]>` into a `[MaybeUninit<T>; N]`.
1645    ///
1646    /// # Examples
1647    ///
1648    /// ```
1649    /// #![feature(maybe_uninit_uninit_array_transpose)]
1650    /// # use std::mem::MaybeUninit;
1651    ///
1652    /// let data: [MaybeUninit<u8>; 1000] = MaybeUninit::uninit().transpose();
1653    /// ```
1654    #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1655    #[inline]
1656    pub const fn transpose(self) -> [MaybeUninit<T>; N] {
1657        // SAFETY: T and MaybeUninit<T> have the same layout
1658        unsafe { intrinsics::transmute_unchecked(self) }
1659    }
1660}
1661
1662#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1663impl<T, const N: usize> From<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1664    #[inline]
1665    fn from(arr: [MaybeUninit<T>; N]) -> Self {
1666        arr.transpose()
1667    }
1668}
1669
1670#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1671impl<T, const N: usize> AsRef<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1672    #[inline]
1673    fn as_ref(&self) -> &[MaybeUninit<T>; N] {
1674        // SAFETY: T and MaybeUninit<T> have the same layout
1675        unsafe { &*ptr::from_ref(self).cast() }
1676    }
1677}
1678
1679#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1680impl<T, const N: usize> AsRef<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1681    #[inline]
1682    fn as_ref(&self) -> &[MaybeUninit<T>] {
1683        AsRef::<[MaybeUninit<T>; N]>::as_ref(self)
1684    }
1685}
1686
1687#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1688impl<T, const N: usize> AsMut<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1689    #[inline]
1690    fn as_mut(&mut self) -> &mut [MaybeUninit<T>; N] {
1691        // SAFETY: T and MaybeUninit<T> have the same layout
1692        unsafe { &mut *ptr::from_mut(self).cast() }
1693    }
1694}
1695
1696#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1697impl<T, const N: usize> AsMut<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1698    #[inline]
1699    fn as_mut(&mut self) -> &mut [MaybeUninit<T>] {
1700        &mut *AsMut::<[MaybeUninit<T>; N]>::as_mut(self)
1701    }
1702}
1703
1704#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1705impl<T, const N: usize> From<MaybeUninit<[T; N]>> for [MaybeUninit<T>; N] {
1706    #[inline]
1707    fn from(arr: MaybeUninit<[T; N]>) -> Self {
1708        arr.transpose()
1709    }
1710}
1711
1712impl<T, const N: usize> [MaybeUninit<T>; N] {
1713    /// Transposes a `[MaybeUninit<T>; N]` into a `MaybeUninit<[T; N]>`.
1714    ///
1715    /// # Examples
1716    ///
1717    /// ```
1718    /// #![feature(maybe_uninit_uninit_array_transpose)]
1719    /// # use std::mem::MaybeUninit;
1720    ///
1721    /// let data = [MaybeUninit::<u8>::uninit(); 1000];
1722    /// let data: MaybeUninit<[u8; 1000]> = data.transpose();
1723    /// ```
1724    #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1725    #[inline]
1726    pub const fn transpose(self) -> MaybeUninit<[T; N]> {
1727        // SAFETY: T and MaybeUninit<T> have the same layout
1728        unsafe { intrinsics::transmute_unchecked(self) }
1729    }
1730}
1731
1732struct Guard<'a, T> {
1733    slice: &'a mut [MaybeUninit<T>],
1734    initialized: usize,
1735}
1736
1737impl<'a, T> Drop for Guard<'a, T> {
1738    fn drop(&mut self) {
1739        let initialized_part = &mut self.slice[..self.initialized];
1740        // SAFETY: this raw sub-slice will contain only initialized objects.
1741        unsafe {
1742            initialized_part.assume_init_drop();
1743        }
1744    }
1745}
1746
1747trait SpecFill<T> {
1748    fn spec_fill(&mut self, value: T);
1749}
1750
1751impl<T: Clone> SpecFill<T> for [MaybeUninit<T>] {
1752    default fn spec_fill(&mut self, value: T) {
1753        let mut guard = Guard { slice: self, initialized: 0 };
1754
1755        if let Some((last, elems)) = guard.slice.split_last_mut() {
1756            for el in elems {
1757                el.write(value.clone());
1758                guard.initialized += 1;
1759            }
1760
1761            last.write(value);
1762        }
1763        super::forget(guard);
1764    }
1765}
1766
1767impl<T: TrivialClone> SpecFill<T> for [MaybeUninit<T>] {
1768    fn spec_fill(&mut self, value: T) {
1769        // SAFETY: because `T` is `TrivialClone`, this is equivalent to calling
1770        // `T::clone` for every element. Notably, `TrivialClone` also implies
1771        // that the `clone` implementation will not panic, so we can avoid
1772        // initialization guards and such.
1773        self.fill_with(|| MaybeUninit::new(unsafe { ptr::read(&value) }));
1774    }
1775}