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