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