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