Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

core/mem/
maybe_uninit.rs

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