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