core/mem/maybe_uninit.rs
1use crate::any::type_name;
2use crate::clone::TrivialClone;
3use crate::marker::Destruct;
4use crate::mem::ManuallyDrop;
5use crate::{fmt, intrinsics, ptr, slice};
6
7/// A wrapper type to construct uninitialized instances of `T`.
8///
9/// # Initialization invariant
10///
11/// The compiler, in general, assumes that a variable is [properly initialized 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 will *not* be zeroed.
445 ///
446 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
447 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
448 ///
449 /// # Example
450 ///
451 /// Correct usage of this function: initializing a struct with zero, where all
452 /// fields of the struct can hold the bit-pattern 0 as a valid value.
453 ///
454 /// ```rust
455 /// use std::mem::MaybeUninit;
456 ///
457 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
458 /// let x = unsafe { x.assume_init() };
459 /// assert_eq!(x, (0, false));
460 /// ```
461 ///
462 /// This can be used in const contexts, such as to indicate the end of static arrays for
463 /// plugin registration.
464 ///
465 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
466 /// when `0` is not a valid bit-pattern for the type:
467 ///
468 /// ```rust,no_run
469 /// use std::mem::MaybeUninit;
470 ///
471 /// enum NotZero { One = 1, Two = 2 }
472 ///
473 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
474 /// let x = unsafe { x.assume_init() };
475 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
476 /// // This is undefined behavior. ⚠️
477 /// ```
478 #[inline]
479 #[must_use]
480 #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
481 #[stable(feature = "maybe_uninit", since = "1.36.0")]
482 #[rustc_const_stable(feature = "const_maybe_uninit_zeroed", since = "1.75.0")]
483 #[ferrocene::prevalidated]
484 pub const fn zeroed() -> MaybeUninit<T> {
485 let mut u = MaybeUninit::<T>::uninit();
486 // SAFETY: `u.as_mut_ptr()` points to allocated memory.
487 unsafe { u.as_mut_ptr().write_bytes(0u8, 1) };
488 u
489 }
490
491 /// Sets the value of the `MaybeUninit<T>`.
492 ///
493 /// This overwrites any previous value without dropping it, so be careful
494 /// not to use this twice unless you want to skip running the destructor.
495 /// For your convenience, this also returns a mutable reference to the
496 /// (now safely initialized) contents of `self`.
497 ///
498 /// As the content is stored inside a `ManuallyDrop`, the destructor is not
499 /// run for the inner data if the MaybeUninit leaves scope without a call to
500 /// [`assume_init`], [`assume_init_drop`], or similar. Code that receives
501 /// the mutable reference returned by this function needs to keep this in
502 /// mind. The safety model of Rust regards leaks as safe, but they are
503 /// usually still undesirable. This being said, the mutable reference
504 /// behaves like any other mutable reference would, so assigning a new value
505 /// to it will drop the old content.
506 ///
507 /// [`assume_init`]: Self::assume_init
508 /// [`assume_init_drop`]: Self::assume_init_drop
509 ///
510 /// # Examples
511 ///
512 /// Correct usage of this method:
513 ///
514 /// ```rust
515 /// use std::mem::MaybeUninit;
516 ///
517 /// let mut x = MaybeUninit::<Vec<u8>>::uninit();
518 ///
519 /// {
520 /// let hello = x.write((&b"Hello, world!").to_vec());
521 /// // Setting hello does not leak prior allocations, but drops them
522 /// *hello = (&b"Hello").to_vec();
523 /// hello[0] = 'h' as u8;
524 /// }
525 /// // x is initialized now:
526 /// let s = unsafe { x.assume_init() };
527 /// assert_eq!(b"hello", s.as_slice());
528 /// ```
529 ///
530 /// This usage of the method causes a leak:
531 ///
532 /// ```rust
533 /// use std::mem::MaybeUninit;
534 ///
535 /// let mut x = MaybeUninit::<String>::uninit();
536 ///
537 /// x.write("Hello".to_string());
538 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
539 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
540 /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
541 /// // This leaks the contained string:
542 /// x.write("hello".to_string());
543 /// // x is initialized now:
544 /// let s = unsafe { x.assume_init() };
545 /// ```
546 ///
547 /// This method can be used to avoid unsafe in some cases. The example below
548 /// shows a part of an implementation of a fixed sized arena that lends out
549 /// pinned references.
550 /// With `write`, we can avoid the need to write through a raw pointer:
551 ///
552 /// ```rust
553 /// use core::pin::Pin;
554 /// use core::mem::MaybeUninit;
555 ///
556 /// struct PinArena<T> {
557 /// memory: Box<[MaybeUninit<T>]>,
558 /// len: usize,
559 /// }
560 ///
561 /// impl <T> PinArena<T> {
562 /// pub fn capacity(&self) -> usize {
563 /// self.memory.len()
564 /// }
565 /// pub fn push(&mut self, val: T) -> Pin<&mut T> {
566 /// if self.len >= self.capacity() {
567 /// panic!("Attempted to push to a full pin arena!");
568 /// }
569 /// let ref_ = self.memory[self.len].write(val);
570 /// self.len += 1;
571 /// unsafe { Pin::new_unchecked(ref_) }
572 /// }
573 /// }
574 /// ```
575 #[inline(always)]
576 #[stable(feature = "maybe_uninit_write", since = "1.55.0")]
577 #[rustc_const_stable(feature = "const_maybe_uninit_write", since = "1.85.0")]
578 #[ferrocene::prevalidated]
579 pub const fn write(&mut self, val: T) -> &mut T {
580 *self = MaybeUninit::new(val);
581 // SAFETY: We just initialized this value.
582 unsafe { self.assume_init_mut() }
583 }
584
585 /// Gets a pointer to the contained value. Reading from this pointer or turning it
586 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
587 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
588 /// (except inside an `UnsafeCell<T>`).
589 ///
590 /// # Examples
591 ///
592 /// Correct usage of this method:
593 ///
594 /// ```rust
595 /// use std::mem::MaybeUninit;
596 ///
597 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
598 /// x.write(vec![0, 1, 2]);
599 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
600 /// let x_vec = unsafe { &*x.as_ptr() };
601 /// assert_eq!(x_vec.len(), 3);
602 /// # // Prevent leaks for Miri
603 /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
604 /// ```
605 ///
606 /// *Incorrect* usage of this method:
607 ///
608 /// ```rust,no_run
609 /// use std::mem::MaybeUninit;
610 ///
611 /// let x = MaybeUninit::<Vec<u32>>::uninit();
612 /// let x_vec = unsafe { &*x.as_ptr() };
613 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
614 /// ```
615 ///
616 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
617 /// until they are, it is advisable to avoid them.)
618 #[stable(feature = "maybe_uninit", since = "1.36.0")]
619 #[rustc_const_stable(feature = "const_maybe_uninit_as_ptr", since = "1.59.0")]
620 #[rustc_as_ptr]
621 #[inline(always)]
622 #[ferrocene::prevalidated]
623 pub const fn as_ptr(&self) -> *const T {
624 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
625 self as *const _ as *const T
626 }
627
628 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
629 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
630 ///
631 /// # Examples
632 ///
633 /// Correct usage of this method:
634 ///
635 /// ```rust
636 /// use std::mem::MaybeUninit;
637 ///
638 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
639 /// x.write(vec![0, 1, 2]);
640 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
641 /// // This is okay because we initialized it.
642 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
643 /// x_vec.push(3);
644 /// assert_eq!(x_vec.len(), 4);
645 /// # // Prevent leaks for Miri
646 /// # unsafe { MaybeUninit::assume_init_drop(&mut x); }
647 /// ```
648 ///
649 /// *Incorrect* usage of this method:
650 ///
651 /// ```rust,no_run
652 /// use std::mem::MaybeUninit;
653 ///
654 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
655 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
656 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
657 /// ```
658 ///
659 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
660 /// until they are, it is advisable to avoid them.)
661 #[stable(feature = "maybe_uninit", since = "1.36.0")]
662 #[rustc_const_stable(feature = "const_maybe_uninit_as_mut_ptr", since = "1.83.0")]
663 #[rustc_as_ptr]
664 #[inline(always)]
665 #[ferrocene::prevalidated]
666 pub const fn as_mut_ptr(&mut self) -> *mut T {
667 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
668 self as *mut _ as *mut T
669 }
670
671 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
672 /// to ensure that the data will get dropped, because the resulting `T` is
673 /// subject to the usual drop handling.
674 ///
675 /// # Safety
676 ///
677 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
678 /// state, i.e., a state that is considered ["valid" for type `T`][validity]. Calling this when
679 /// the content is not yet fully initialized causes immediate undefined behavior. The
680 /// [type-level documentation][inv] contains more information about this initialization
681 /// invariant.
682 ///
683 /// It is a common mistake to assume that this function is safe to call on integers because they
684 /// can hold all bit patterns. It is also a common mistake to think that calling this function
685 /// is UB if any byte is uninitialized. Both of these assumptions are wrong. If that is
686 /// surprising to you, please read the [type-level documentation][inv].
687 ///
688 /// [inv]: #initialization-invariant
689 /// [validity]: ../../reference/behavior-considered-undefined.html#r-undefined.validity
690 ///
691 /// On top of that, remember that most types have additional invariants beyond merely
692 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
693 /// is considered initialized (under the current implementation; this does not constitute
694 /// a stable guarantee) because the only requirement the compiler knows about it
695 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
696 /// *immediate* undefined behavior, but will cause undefined behavior with most
697 /// safe operations (including dropping it).
698 ///
699 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
700 ///
701 /// # Examples
702 ///
703 /// Correct usage of this method:
704 ///
705 /// ```rust
706 /// use std::mem::MaybeUninit;
707 ///
708 /// let mut x = MaybeUninit::<bool>::uninit();
709 /// x.write(true);
710 /// let x_init = unsafe { x.assume_init() };
711 /// assert_eq!(x_init, true);
712 /// ```
713 ///
714 /// *Incorrect* usage of this method:
715 ///
716 /// ```rust,no_run
717 /// # #![allow(invalid_value)]
718 /// use std::mem::MaybeUninit;
719 ///
720 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
721 /// ```
722 ///
723 /// See the [type-level documentation][#examples] for more examples.
724 #[stable(feature = "maybe_uninit", since = "1.36.0")]
725 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_by_value", since = "1.59.0")]
726 #[inline(always)]
727 #[rustc_diagnostic_item = "assume_init"]
728 #[track_caller]
729 #[ferrocene::prevalidated]
730 pub const unsafe fn assume_init(self) -> T {
731 // SAFETY: the caller must guarantee that `self` is initialized.
732 // This also means that `self` must be a `value` variant.
733 unsafe {
734 intrinsics::assert_inhabited::<T>();
735 // We do this via a raw ptr read instead of `ManuallyDrop::into_inner` so that there's
736 // no trace of `ManuallyDrop` in Miri's error messages here.
737 (&raw const self.value).cast::<T>().read()
738 }
739 }
740
741 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
742 /// to the usual drop handling.
743 ///
744 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
745 /// prevents duplicating the content of the `MaybeUninit<T>`.
746 ///
747 /// # Safety
748 ///
749 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
750 /// state. Calling this when the content is not yet fully initialized causes undefined
751 /// behavior. The [type-level documentation][inv] contains more information about
752 /// this initialization invariant.
753 ///
754 /// Moreover, similar to the [`ptr::read`] function, this function creates a
755 /// bitwise copy of the contents, regardless whether the contained type
756 /// implements the [`Copy`] trait or not. When using multiple copies of the
757 /// data (by calling `assume_init_read` multiple times, or first calling
758 /// `assume_init_read` and then [`assume_init`]), it is your responsibility
759 /// to ensure that data may indeed be duplicated.
760 ///
761 /// [inv]: #initialization-invariant
762 /// [`assume_init`]: MaybeUninit::assume_init
763 ///
764 /// # Examples
765 ///
766 /// Correct usage of this method:
767 ///
768 /// ```rust
769 /// use std::mem::MaybeUninit;
770 ///
771 /// let mut x = MaybeUninit::<u32>::uninit();
772 /// x.write(13);
773 /// let x1 = unsafe { x.assume_init_read() };
774 /// // `u32` is `Copy`, so we may read multiple times.
775 /// let x2 = unsafe { x.assume_init_read() };
776 /// assert_eq!(x1, x2);
777 ///
778 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
779 /// x.write(None);
780 /// let x1 = unsafe { x.assume_init_read() };
781 /// // Duplicating a `None` value is okay, so we may read multiple times.
782 /// let x2 = unsafe { x.assume_init_read() };
783 /// assert_eq!(x1, x2);
784 /// ```
785 ///
786 /// *Incorrect* usage of this method:
787 ///
788 /// ```rust,no_run
789 /// use std::mem::MaybeUninit;
790 ///
791 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
792 /// x.write(Some(vec![0, 1, 2]));
793 /// let x1 = unsafe { x.assume_init_read() };
794 /// let x2 = unsafe { x.assume_init_read() };
795 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
796 /// // they both get dropped!
797 /// ```
798 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
799 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_read", since = "1.75.0")]
800 #[inline(always)]
801 #[track_caller]
802 #[ferrocene::prevalidated]
803 pub const unsafe fn assume_init_read(&self) -> T {
804 // SAFETY: the caller must guarantee that `self` is initialized.
805 // Reading from `self.as_ptr()` is safe since `self` should be initialized.
806 unsafe {
807 intrinsics::assert_inhabited::<T>();
808 self.as_ptr().read()
809 }
810 }
811
812 /// Drops the contained value in place.
813 ///
814 /// If you have ownership of the `MaybeUninit`, you can also use
815 /// [`assume_init`] as an alternative.
816 ///
817 /// # Safety
818 ///
819 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
820 /// in an initialized state. Calling this when the content is not yet fully
821 /// initialized causes undefined behavior.
822 ///
823 /// On top of that, all additional invariants of the type `T` must be
824 /// satisfied, as the `Drop` implementation of `T` (or its members) may
825 /// rely on this. For example, setting a `Vec<T>` to an invalid but
826 /// non-null address makes it initialized (under the current implementation;
827 /// this does not constitute a stable guarantee), because the only
828 /// requirement the compiler knows about it is that the data pointer must be
829 /// non-null. Dropping such a `Vec<T>` however will cause undefined
830 /// behavior.
831 ///
832 /// [`assume_init`]: MaybeUninit::assume_init
833 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
834 #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
835 #[ferrocene::prevalidated]
836 pub const unsafe fn assume_init_drop(&mut self)
837 where
838 T: [const] Destruct,
839 {
840 // SAFETY: the caller must guarantee that `self` is initialized and
841 // satisfies all invariants of `T`.
842 // Dropping the value in place is safe if that is the case.
843 unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
844 }
845
846 /// Gets a shared reference to the contained value.
847 ///
848 /// This can be useful when we want to access a `MaybeUninit` that has been
849 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
850 /// of `.assume_init()`).
851 ///
852 /// # Safety
853 ///
854 /// Calling this when the content is not yet fully initialized causes undefined
855 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
856 /// is in an initialized state.
857 ///
858 /// # Examples
859 ///
860 /// ### Correct usage of this method:
861 ///
862 /// ```rust
863 /// use std::mem::MaybeUninit;
864 ///
865 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
866 /// # let mut x_mu = x;
867 /// # let mut x = &mut x_mu;
868 /// // Initialize `x`:
869 /// x.write(vec![1, 2, 3]);
870 /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
871 /// // create a shared reference to it:
872 /// let x: &Vec<u32> = unsafe {
873 /// // SAFETY: `x` has been initialized.
874 /// x.assume_init_ref()
875 /// };
876 /// assert_eq!(x, &vec![1, 2, 3]);
877 /// # // Prevent leaks for Miri
878 /// # unsafe { MaybeUninit::assume_init_drop(&mut x_mu); }
879 /// ```
880 ///
881 /// ### *Incorrect* usages of this method:
882 ///
883 /// ```rust,no_run
884 /// use std::mem::MaybeUninit;
885 ///
886 /// let x = MaybeUninit::<Vec<u32>>::uninit();
887 /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
888 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
889 /// ```
890 ///
891 /// ```rust,no_run
892 /// use std::{cell::Cell, mem::MaybeUninit};
893 ///
894 /// let b = MaybeUninit::<Cell<bool>>::uninit();
895 /// // Initialize the `MaybeUninit` using `Cell::set`:
896 /// unsafe {
897 /// b.assume_init_ref().set(true);
898 /// //^^^^^^^^^^^^^^^ Reference to an uninitialized `Cell<bool>`: UB!
899 /// }
900 /// ```
901 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
902 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_ref", since = "1.59.0")]
903 #[inline(always)]
904 #[ferrocene::prevalidated]
905 pub const unsafe fn assume_init_ref(&self) -> &T {
906 // SAFETY: the caller must guarantee that `self` is initialized.
907 // This also means that `self` must be a `value` variant.
908 unsafe {
909 intrinsics::assert_inhabited::<T>();
910 &*self.as_ptr()
911 }
912 }
913
914 /// Gets a mutable (unique) reference to the contained value.
915 ///
916 /// This can be useful when we want to access a `MaybeUninit` that has been
917 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
918 /// of `.assume_init()`).
919 ///
920 /// # Safety
921 ///
922 /// Calling this when the content is not yet fully initialized causes undefined
923 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
924 /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
925 /// initialize a `MaybeUninit`.
926 ///
927 /// # Examples
928 ///
929 /// ### Correct usage of this method:
930 ///
931 /// ```rust
932 /// # #![allow(unexpected_cfgs)]
933 /// use std::mem::MaybeUninit;
934 ///
935 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { unsafe { *buf = [0; 1024] } }
936 /// # #[cfg(FALSE)]
937 /// extern "C" {
938 /// /// Initializes *all* the bytes of the input buffer.
939 /// fn initialize_buffer(buf: *mut [u8; 1024]);
940 /// }
941 ///
942 /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
943 ///
944 /// // Initialize `buf`:
945 /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
946 /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
947 /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes.
948 /// // To assert our buffer has been initialized without copying it, we upgrade
949 /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`:
950 /// let buf: &mut [u8; 1024] = unsafe {
951 /// // SAFETY: `buf` has been initialized.
952 /// buf.assume_init_mut()
953 /// };
954 ///
955 /// // Now we can use `buf` as a normal slice:
956 /// buf.sort_unstable();
957 /// assert!(
958 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
959 /// "buffer is sorted",
960 /// );
961 /// ```
962 ///
963 /// ### *Incorrect* usages of this method:
964 ///
965 /// You cannot use `.assume_init_mut()` to initialize a value:
966 ///
967 /// ```rust,no_run
968 /// use std::mem::MaybeUninit;
969 ///
970 /// let mut b = MaybeUninit::<bool>::uninit();
971 /// unsafe {
972 /// *b.assume_init_mut() = true;
973 /// // We have created a (mutable) reference to an uninitialized `bool`!
974 /// // This is undefined behavior. ⚠️
975 /// }
976 /// ```
977 ///
978 /// For instance, you cannot [`Read`] into an uninitialized buffer:
979 ///
980 /// [`Read`]: ../../std/io/trait.Read.html
981 ///
982 /// ```rust,no_run
983 /// use std::{io, mem::MaybeUninit};
984 ///
985 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
986 /// {
987 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
988 /// reader.read_exact(unsafe { buffer.assume_init_mut() })?;
989 /// // ^^^^^^^^^^^^^^^^^^^^^^^^
990 /// // (mutable) reference to uninitialized memory!
991 /// // This is undefined behavior.
992 /// Ok(unsafe { buffer.assume_init() })
993 /// }
994 /// ```
995 ///
996 /// Nor can you use direct field access to do field-by-field gradual initialization:
997 ///
998 /// ```rust,no_run
999 /// use std::{mem::MaybeUninit, ptr};
1000 ///
1001 /// struct Foo {
1002 /// a: u32,
1003 /// b: u8,
1004 /// }
1005 ///
1006 /// let foo: Foo = unsafe {
1007 /// let mut foo = MaybeUninit::<Foo>::uninit();
1008 /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
1009 /// // ^^^^^^^^^^^^^^^^^^^^^
1010 /// // (mutable) reference to uninitialized memory!
1011 /// // This is undefined behavior.
1012 /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
1013 /// // ^^^^^^^^^^^^^^^^^^^^^
1014 /// // (mutable) reference to uninitialized memory!
1015 /// // This is undefined behavior.
1016 /// foo.assume_init()
1017 /// };
1018 /// ```
1019 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
1020 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init", since = "1.84.0")]
1021 #[inline(always)]
1022 #[ferrocene::prevalidated]
1023 pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
1024 // SAFETY: the caller must guarantee that `self` is initialized.
1025 // This also means that `self` must be a `value` variant.
1026 unsafe {
1027 intrinsics::assert_inhabited::<T>();
1028 &mut *self.as_mut_ptr()
1029 }
1030 }
1031
1032 /// Extracts the values from an array of `MaybeUninit` containers.
1033 ///
1034 /// # Safety
1035 ///
1036 /// It is up to the caller to guarantee that all elements of the array are
1037 /// in an initialized state.
1038 ///
1039 /// # Examples
1040 ///
1041 /// ```
1042 /// #![feature(maybe_uninit_array_assume_init)]
1043 /// use std::mem::MaybeUninit;
1044 ///
1045 /// let mut array: [MaybeUninit<i32>; 3] = [MaybeUninit::uninit(); 3];
1046 /// array[0].write(0);
1047 /// array[1].write(1);
1048 /// array[2].write(2);
1049 ///
1050 /// // SAFETY: Now safe as we initialised all elements
1051 /// let array = unsafe {
1052 /// MaybeUninit::array_assume_init(array)
1053 /// };
1054 ///
1055 /// assert_eq!(array, [0, 1, 2]);
1056 /// ```
1057 #[unstable(feature = "maybe_uninit_array_assume_init", issue = "96097")]
1058 #[inline(always)]
1059 #[track_caller]
1060 #[ferrocene::prevalidated]
1061 pub const unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
1062 // SAFETY:
1063 // * The caller guarantees that all elements of the array are initialized
1064 // * `MaybeUninit<T>` and T are guaranteed to have the same layout
1065 // * `MaybeUninit` does not drop, so there are no double-frees
1066 // And thus the conversion is safe
1067 unsafe {
1068 intrinsics::assert_inhabited::<[T; N]>();
1069 intrinsics::transmute_unchecked(array)
1070 }
1071 }
1072
1073 /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1074 ///
1075 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1076 /// contain padding bytes which are left uninitialized.
1077 ///
1078 /// # Examples
1079 ///
1080 /// ```
1081 /// #![feature(maybe_uninit_as_bytes)]
1082 /// use std::mem::MaybeUninit;
1083 ///
1084 /// let val = 0x12345678_i32;
1085 /// let uninit = MaybeUninit::new(val);
1086 /// let uninit_bytes = uninit.as_bytes();
1087 /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1088 /// assert_eq!(bytes, val.to_ne_bytes());
1089 /// ```
1090 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1091 #[ferrocene::prevalidated]
1092 pub const fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1093 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1094 unsafe {
1095 slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of::<T>())
1096 }
1097 }
1098
1099 /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized
1100 /// bytes.
1101 ///
1102 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1103 /// contain padding bytes which are left uninitialized.
1104 ///
1105 /// # Examples
1106 ///
1107 /// ```
1108 /// #![feature(maybe_uninit_as_bytes)]
1109 /// use std::mem::MaybeUninit;
1110 ///
1111 /// let val = 0x12345678_i32;
1112 /// let mut uninit = MaybeUninit::new(val);
1113 /// let uninit_bytes = uninit.as_bytes_mut();
1114 /// if cfg!(target_endian = "little") {
1115 /// uninit_bytes[0].write(0xcd);
1116 /// } else {
1117 /// uninit_bytes[3].write(0xcd);
1118 /// }
1119 /// let val2 = unsafe { uninit.assume_init() };
1120 /// assert_eq!(val2, 0x123456cd);
1121 /// ```
1122 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1123 #[ferrocene::prevalidated]
1124 pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1125 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1126 unsafe {
1127 slice::from_raw_parts_mut(
1128 self.as_mut_ptr().cast::<MaybeUninit<u8>>(),
1129 super::size_of::<T>(),
1130 )
1131 }
1132 }
1133}
1134
1135impl<T> [MaybeUninit<T>] {
1136 /// Copies the elements from `src` to `self`,
1137 /// returning a mutable reference to the now initialized contents of `self`.
1138 ///
1139 /// If `T` does not implement `Copy`, use [`write_clone_of_slice`] instead.
1140 ///
1141 /// This is similar to [`slice::copy_from_slice`].
1142 ///
1143 /// # Panics
1144 ///
1145 /// This function will panic if the two slices have different lengths.
1146 ///
1147 /// # Examples
1148 ///
1149 /// ```
1150 /// use std::mem::MaybeUninit;
1151 ///
1152 /// let mut dst = [MaybeUninit::uninit(); 32];
1153 /// let src = [0; 32];
1154 ///
1155 /// let init = dst.write_copy_of_slice(&src);
1156 ///
1157 /// assert_eq!(init, src);
1158 /// ```
1159 ///
1160 /// ```
1161 /// let mut vec = Vec::with_capacity(32);
1162 /// let src = [0; 16];
1163 ///
1164 /// vec.spare_capacity_mut()[..src.len()].write_copy_of_slice(&src);
1165 ///
1166 /// // SAFETY: we have just copied all the elements of len into the spare capacity
1167 /// // the first src.len() elements of the vec are valid now.
1168 /// unsafe {
1169 /// vec.set_len(src.len());
1170 /// }
1171 ///
1172 /// assert_eq!(vec, src);
1173 /// ```
1174 ///
1175 /// [`write_clone_of_slice`]: slice::write_clone_of_slice
1176 #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1177 #[rustc_const_stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1178 pub const fn write_copy_of_slice(&mut self, src: &[T]) -> &mut [T]
1179 where
1180 T: Copy,
1181 {
1182 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1183 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1184
1185 self.copy_from_slice(uninit_src);
1186
1187 // SAFETY: Valid elements have just been copied into `self` so it is initialized
1188 unsafe { self.assume_init_mut() }
1189 }
1190
1191 /// Clones the elements from `src` to `self`,
1192 /// returning a mutable reference to the now initialized contents of `self`.
1193 /// Any already initialized elements will not be dropped.
1194 ///
1195 /// If `T` implements `Copy`, use [`write_copy_of_slice`] instead.
1196 ///
1197 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1198 ///
1199 /// # Panics
1200 ///
1201 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1202 ///
1203 /// If there is a panic, the already cloned elements will be dropped.
1204 ///
1205 /// # Examples
1206 ///
1207 /// ```
1208 /// use std::mem::MaybeUninit;
1209 ///
1210 /// let mut dst = [const { MaybeUninit::uninit() }; 5];
1211 /// let src = ["wibbly", "wobbly", "timey", "wimey", "stuff"].map(|s| s.to_string());
1212 ///
1213 /// let init = dst.write_clone_of_slice(&src);
1214 ///
1215 /// assert_eq!(init, src);
1216 ///
1217 /// # // Prevent leaks for Miri
1218 /// # unsafe { std::ptr::drop_in_place(init); }
1219 /// ```
1220 ///
1221 /// ```
1222 /// let mut vec = Vec::with_capacity(32);
1223 /// let src = ["rust", "is", "a", "pretty", "cool", "language"].map(|s| s.to_string());
1224 ///
1225 /// vec.spare_capacity_mut()[..src.len()].write_clone_of_slice(&src);
1226 ///
1227 /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1228 /// // the first src.len() elements of the vec are valid now.
1229 /// unsafe {
1230 /// vec.set_len(src.len());
1231 /// }
1232 ///
1233 /// assert_eq!(vec, src);
1234 /// ```
1235 ///
1236 /// [`write_copy_of_slice`]: slice::write_copy_of_slice
1237 #[stable(feature = "maybe_uninit_write_slice", since = "1.93.0")]
1238 pub fn write_clone_of_slice(&mut self, src: &[T]) -> &mut [T]
1239 where
1240 T: Clone,
1241 {
1242 // unlike copy_from_slice this does not call clone_from_slice on the slice
1243 // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1244
1245 assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
1246
1247 // NOTE: We need to explicitly slice them to the same length
1248 // for bounds checking to be elided, and the optimizer will
1249 // generate memcpy for simple cases (for example T = u8).
1250 let len = self.len();
1251 let src = &src[..len];
1252
1253 // guard is needed b/c panic might happen during a clone
1254 let mut guard = Guard { slice: self, initialized: 0 };
1255
1256 for i in 0..len {
1257 guard.slice[i].write(src[i].clone());
1258 guard.initialized += 1;
1259 }
1260
1261 super::forget(guard);
1262
1263 // SAFETY: Valid elements have just been written into `self` so it is initialized
1264 unsafe { self.assume_init_mut() }
1265 }
1266
1267 /// Fills a slice with elements by cloning `value`, returning a mutable reference to the now
1268 /// initialized contents of the slice.
1269 /// Any previously initialized elements will not be dropped.
1270 ///
1271 /// This is similar to [`slice::fill`].
1272 ///
1273 /// # Panics
1274 ///
1275 /// This function will panic if any call to `Clone` panics.
1276 ///
1277 /// If such a panic occurs, any elements previously initialized during this operation will be
1278 /// dropped.
1279 ///
1280 /// # Examples
1281 ///
1282 /// ```
1283 /// #![feature(maybe_uninit_fill)]
1284 /// use std::mem::MaybeUninit;
1285 ///
1286 /// let mut buf = [const { MaybeUninit::uninit() }; 10];
1287 /// let initialized = buf.write_filled(1);
1288 /// assert_eq!(initialized, &mut [1; 10]);
1289 /// ```
1290 #[doc(alias = "memset")]
1291 #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1292 pub fn write_filled(&mut self, value: T) -> &mut [T]
1293 where
1294 T: Clone,
1295 {
1296 SpecFill::spec_fill(self, value);
1297 // SAFETY: Valid elements have just been filled into `self` so it is initialized
1298 unsafe { self.assume_init_mut() }
1299 }
1300
1301 /// Fills a slice with elements returned by calling a closure for each index.
1302 ///
1303 /// This method uses a closure to create new values. If you'd rather `Clone` a given value, use
1304 /// [slice::write_filled]. If you want to use the `Default` trait to generate values, you can
1305 /// pass [`|_| Default::default()`][Default::default] as the argument.
1306 ///
1307 /// # Panics
1308 ///
1309 /// This function will panic if any call to the provided closure panics.
1310 ///
1311 /// If such a panic occurs, any elements previously initialized during this operation will be
1312 /// dropped.
1313 ///
1314 /// # Examples
1315 ///
1316 /// ```
1317 /// #![feature(maybe_uninit_fill)]
1318 /// use std::mem::MaybeUninit;
1319 ///
1320 /// let mut buf = [const { MaybeUninit::<usize>::uninit() }; 5];
1321 /// let initialized = buf.write_with(|idx| idx + 1);
1322 /// assert_eq!(initialized, &mut [1, 2, 3, 4, 5]);
1323 /// ```
1324 #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1325 pub fn write_with<F>(&mut self, mut f: F) -> &mut [T]
1326 where
1327 F: FnMut(usize) -> T,
1328 {
1329 let mut guard = Guard { slice: self, initialized: 0 };
1330
1331 for (idx, element) in guard.slice.iter_mut().enumerate() {
1332 element.write(f(idx));
1333 guard.initialized += 1;
1334 }
1335
1336 super::forget(guard);
1337
1338 // SAFETY: Valid elements have just been written into `this` so it is initialized
1339 unsafe { self.assume_init_mut() }
1340 }
1341
1342 /// Fills a slice with elements yielded by an iterator until either all elements have been
1343 /// initialized or the iterator is empty.
1344 ///
1345 /// Returns two slices. The first slice contains the initialized portion of the original slice.
1346 /// The second slice is the still-uninitialized remainder of the original slice.
1347 ///
1348 /// # Panics
1349 ///
1350 /// This function panics if the iterator's `next` function panics.
1351 ///
1352 /// If such a panic occurs, any elements previously initialized during this operation will be
1353 /// dropped.
1354 ///
1355 /// # Examples
1356 ///
1357 /// Completely filling the slice:
1358 ///
1359 /// ```
1360 /// #![feature(maybe_uninit_fill)]
1361 /// use std::mem::MaybeUninit;
1362 ///
1363 /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1364 ///
1365 /// let iter = [1, 2, 3].into_iter().cycle();
1366 /// let (initialized, remainder) = buf.write_iter(iter);
1367 ///
1368 /// assert_eq!(initialized, &mut [1, 2, 3, 1, 2]);
1369 /// assert_eq!(remainder.len(), 0);
1370 /// ```
1371 ///
1372 /// Partially filling the slice:
1373 ///
1374 /// ```
1375 /// #![feature(maybe_uninit_fill)]
1376 /// use std::mem::MaybeUninit;
1377 ///
1378 /// let mut buf = [const { MaybeUninit::uninit() }; 5];
1379 /// let iter = [1, 2];
1380 /// let (initialized, remainder) = buf.write_iter(iter);
1381 ///
1382 /// assert_eq!(initialized, &mut [1, 2]);
1383 /// assert_eq!(remainder.len(), 3);
1384 /// ```
1385 ///
1386 /// Checking an iterator after filling a slice:
1387 ///
1388 /// ```
1389 /// #![feature(maybe_uninit_fill)]
1390 /// use std::mem::MaybeUninit;
1391 ///
1392 /// let mut buf = [const { MaybeUninit::uninit() }; 3];
1393 /// let mut iter = [1, 2, 3, 4, 5].into_iter();
1394 /// let (initialized, remainder) = buf.write_iter(iter.by_ref());
1395 ///
1396 /// assert_eq!(initialized, &mut [1, 2, 3]);
1397 /// assert_eq!(remainder.len(), 0);
1398 /// assert_eq!(iter.as_slice(), &[4, 5]);
1399 /// ```
1400 #[unstable(feature = "maybe_uninit_fill", issue = "117428")]
1401 pub fn write_iter<I>(&mut self, it: I) -> (&mut [T], &mut [MaybeUninit<T>])
1402 where
1403 I: IntoIterator<Item = T>,
1404 {
1405 let iter = it.into_iter();
1406 let mut guard = Guard { slice: self, initialized: 0 };
1407
1408 for (element, val) in guard.slice.iter_mut().zip(iter) {
1409 element.write(val);
1410 guard.initialized += 1;
1411 }
1412
1413 let initialized_len = guard.initialized;
1414 super::forget(guard);
1415
1416 // SAFETY: guard.initialized <= self.len()
1417 let (initted, remainder) = unsafe { self.split_at_mut_unchecked(initialized_len) };
1418
1419 // SAFETY: Valid elements have just been written into `init`, so that portion
1420 // of `this` is initialized.
1421 (unsafe { initted.assume_init_mut() }, remainder)
1422 }
1423
1424 /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1425 ///
1426 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1427 /// contain padding bytes which are left uninitialized.
1428 ///
1429 /// # Examples
1430 ///
1431 /// ```
1432 /// #![feature(maybe_uninit_as_bytes)]
1433 /// use std::mem::MaybeUninit;
1434 ///
1435 /// let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)];
1436 /// let uninit_bytes = uninit.as_bytes();
1437 /// let bytes = unsafe { uninit_bytes.assume_init_ref() };
1438 /// let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap());
1439 /// let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap());
1440 /// assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]);
1441 /// ```
1442 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1443 pub const fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1444 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1445 unsafe {
1446 slice::from_raw_parts(self.as_ptr().cast::<MaybeUninit<u8>>(), super::size_of_val(self))
1447 }
1448 }
1449
1450 /// Returns the contents of this `MaybeUninit` slice as a mutable slice of potentially
1451 /// uninitialized bytes.
1452 ///
1453 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1454 /// contain padding bytes which are left uninitialized.
1455 ///
1456 /// # Examples
1457 ///
1458 /// ```
1459 /// #![feature(maybe_uninit_as_bytes)]
1460 /// use std::mem::MaybeUninit;
1461 ///
1462 /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()];
1463 /// let uninit_bytes = uninit.as_bytes_mut();
1464 /// uninit_bytes.write_copy_of_slice(&[0x12, 0x34, 0x56, 0x78]);
1465 /// let vals = unsafe { uninit.assume_init_ref() };
1466 /// if cfg!(target_endian = "little") {
1467 /// assert_eq!(vals, &[0x3412u16, 0x7856u16]);
1468 /// } else {
1469 /// assert_eq!(vals, &[0x1234u16, 0x5678u16]);
1470 /// }
1471 /// ```
1472 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1473 pub const fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1474 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1475 unsafe {
1476 slice::from_raw_parts_mut(
1477 self.as_mut_ptr() as *mut MaybeUninit<u8>,
1478 super::size_of_val(self),
1479 )
1480 }
1481 }
1482
1483 /// Drops the contained values in place.
1484 ///
1485 /// # Safety
1486 ///
1487 /// It is up to the caller to guarantee that every `MaybeUninit<T>` in the slice
1488 /// really is in an initialized state. Calling this when the content is not yet
1489 /// fully initialized causes undefined behavior.
1490 ///
1491 /// On top of that, all additional invariants of the type `T` must be
1492 /// satisfied, as the `Drop` implementation of `T` (or its members) may
1493 /// rely on this. For example, setting a `Vec<T>` to an invalid but
1494 /// non-null address makes it initialized (under the current implementation;
1495 /// this does not constitute a stable guarantee), because the only
1496 /// requirement the compiler knows about it is that the data pointer must be
1497 /// non-null. Dropping such a `Vec<T>` however will cause undefined
1498 /// behaviour.
1499 #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1500 #[inline(always)]
1501 #[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
1502 #[ferrocene::prevalidated]
1503 pub const unsafe fn assume_init_drop(&mut self)
1504 where
1505 T: [const] Destruct,
1506 {
1507 if !self.is_empty() {
1508 // SAFETY: the caller must guarantee that every element of `self`
1509 // is initialized and satisfies all invariants of `T`.
1510 // Dropping the value in place is safe if that is the case.
1511 unsafe { ptr::drop_in_place(self as *mut [MaybeUninit<T>] as *mut [T]) }
1512 }
1513 }
1514
1515 /// Gets a shared reference to the contained value.
1516 ///
1517 /// # Safety
1518 ///
1519 /// Calling this when the content is not yet fully initialized causes undefined
1520 /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in
1521 /// the slice really is in an initialized state.
1522 #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1523 #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1524 #[inline(always)]
1525 #[ferrocene::prevalidated]
1526 pub const unsafe fn assume_init_ref(&self) -> &[T] {
1527 // SAFETY: casting `slice` to a `*const [T]` is safe since the caller guarantees that
1528 // `slice` is initialized, and `MaybeUninit` is guaranteed to have the same layout as `T`.
1529 // The pointer obtained is valid since it refers to memory owned by `slice` which is a
1530 // reference and thus guaranteed to be valid for reads.
1531 unsafe { &*(self as *const Self as *const [T]) }
1532 }
1533
1534 /// Gets a mutable (unique) reference to the contained value.
1535 ///
1536 /// # Safety
1537 ///
1538 /// Calling this when the content is not yet fully initialized causes undefined
1539 /// behavior: it is up to the caller to guarantee that every `MaybeUninit<T>` in the
1540 /// slice really is in an initialized state. For instance, `.assume_init_mut()` cannot
1541 /// be used to initialize a `MaybeUninit` slice.
1542 #[stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1543 #[rustc_const_stable(feature = "maybe_uninit_slice", since = "1.93.0")]
1544 #[inline(always)]
1545 #[ferrocene::prevalidated]
1546 pub const unsafe fn assume_init_mut(&mut self) -> &mut [T] {
1547 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
1548 // mutable reference which is also guaranteed to be valid for writes.
1549 unsafe { &mut *(self as *mut Self as *mut [T]) }
1550 }
1551}
1552
1553impl<T, const N: usize> MaybeUninit<[T; N]> {
1554 /// Transposes a `MaybeUninit<[T; N]>` into a `[MaybeUninit<T>; N]`.
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```
1559 /// #![feature(maybe_uninit_uninit_array_transpose)]
1560 /// # use std::mem::MaybeUninit;
1561 ///
1562 /// let data: [MaybeUninit<u8>; 1000] = MaybeUninit::uninit().transpose();
1563 /// ```
1564 #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1565 #[inline]
1566 #[ferrocene::prevalidated]
1567 pub const fn transpose(self) -> [MaybeUninit<T>; N] {
1568 // SAFETY: T and MaybeUninit<T> have the same layout
1569 unsafe { intrinsics::transmute_unchecked(self) }
1570 }
1571}
1572
1573#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1574impl<T, const N: usize> From<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1575 #[inline]
1576 fn from(arr: [MaybeUninit<T>; N]) -> Self {
1577 arr.transpose()
1578 }
1579}
1580
1581#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1582impl<T, const N: usize> AsRef<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1583 #[inline]
1584 fn as_ref(&self) -> &[MaybeUninit<T>; N] {
1585 // SAFETY: T and MaybeUninit<T> have the same layout
1586 unsafe { &*ptr::from_ref(self).cast() }
1587 }
1588}
1589
1590#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1591impl<T, const N: usize> AsRef<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1592 #[inline]
1593 fn as_ref(&self) -> &[MaybeUninit<T>] {
1594 &*AsRef::<[MaybeUninit<T>; N]>::as_ref(self)
1595 }
1596}
1597
1598#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1599impl<T, const N: usize> AsMut<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
1600 #[inline]
1601 fn as_mut(&mut self) -> &mut [MaybeUninit<T>; N] {
1602 // SAFETY: T and MaybeUninit<T> have the same layout
1603 unsafe { &mut *ptr::from_mut(self).cast() }
1604 }
1605}
1606
1607#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1608impl<T, const N: usize> AsMut<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
1609 #[inline]
1610 fn as_mut(&mut self) -> &mut [MaybeUninit<T>] {
1611 &mut *AsMut::<[MaybeUninit<T>; N]>::as_mut(self)
1612 }
1613}
1614
1615#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
1616impl<T, const N: usize> From<MaybeUninit<[T; N]>> for [MaybeUninit<T>; N] {
1617 #[inline]
1618 fn from(arr: MaybeUninit<[T; N]>) -> Self {
1619 arr.transpose()
1620 }
1621}
1622
1623impl<T, const N: usize> [MaybeUninit<T>; N] {
1624 /// Transposes a `[MaybeUninit<T>; N]` into a `MaybeUninit<[T; N]>`.
1625 ///
1626 /// # Examples
1627 ///
1628 /// ```
1629 /// #![feature(maybe_uninit_uninit_array_transpose)]
1630 /// # use std::mem::MaybeUninit;
1631 ///
1632 /// let data = [MaybeUninit::<u8>::uninit(); 1000];
1633 /// let data: MaybeUninit<[u8; 1000]> = data.transpose();
1634 /// ```
1635 #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")]
1636 #[inline]
1637 #[ferrocene::prevalidated]
1638 pub const fn transpose(self) -> MaybeUninit<[T; N]> {
1639 // SAFETY: T and MaybeUninit<T> have the same layout
1640 unsafe { intrinsics::transmute_unchecked(self) }
1641 }
1642}
1643
1644struct Guard<'a, T> {
1645 slice: &'a mut [MaybeUninit<T>],
1646 initialized: usize,
1647}
1648
1649impl<'a, T> Drop for Guard<'a, T> {
1650 fn drop(&mut self) {
1651 let initialized_part = &mut self.slice[..self.initialized];
1652 // SAFETY: this raw sub-slice will contain only initialized objects.
1653 unsafe {
1654 initialized_part.assume_init_drop();
1655 }
1656 }
1657}
1658
1659trait SpecFill<T> {
1660 fn spec_fill(&mut self, value: T);
1661}
1662
1663impl<T: Clone> SpecFill<T> for [MaybeUninit<T>] {
1664 default fn spec_fill(&mut self, value: T) {
1665 let mut guard = Guard { slice: self, initialized: 0 };
1666
1667 if let Some((last, elems)) = guard.slice.split_last_mut() {
1668 for el in elems {
1669 el.write(value.clone());
1670 guard.initialized += 1;
1671 }
1672
1673 last.write(value);
1674 }
1675 super::forget(guard);
1676 }
1677}
1678
1679impl<T: TrivialClone> SpecFill<T> for [MaybeUninit<T>] {
1680 fn spec_fill(&mut self, value: T) {
1681 // SAFETY: because `T` is `TrivialClone`, this is equivalent to calling
1682 // `T::clone` for every element. Notably, `TrivialClone` also implies
1683 // that the `clone` implementation will not panic, so we can avoid
1684 // initialization guards and such.
1685 self.fill_with(|| MaybeUninit::new(unsafe { ptr::read(&value) }));
1686 }
1687}