core/mem/
maybe_uninit.rs

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