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