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