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