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