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