]> git.lizzy.rs Git - rust.git/blob - library/core/src/mem/maybe_uninit.rs
rustdoc: Remove unused Clean impls
[rust.git] / library / core / src / mem / maybe_uninit.rs
1 use crate::any::type_name;
2 use crate::fmt;
3 use crate::intrinsics;
4 use crate::mem::ManuallyDrop;
5 use crate::ptr;
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
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][ub],
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 /// (Notice that the rules around uninitialized integers are not finalized yet, but
57 /// until they are, it is advisable to avoid them.)
58 ///
59 /// On top of that, remember that most types have additional invariants beyond merely
60 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
61 /// is considered initialized (under the current implementation; this does not constitute
62 /// a stable guarantee) because the only requirement the compiler knows about it
63 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
64 /// *immediate* undefined behavior, but will cause undefined behavior with most
65 /// safe operations (including dropping it).
66 ///
67 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
68 ///
69 /// # Examples
70 ///
71 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
72 /// It is a signal to the compiler indicating that the data here might *not*
73 /// be initialized:
74 ///
75 /// ```rust
76 /// use std::mem::MaybeUninit;
77 ///
78 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
79 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
80 /// let mut x = MaybeUninit::<&i32>::uninit();
81 /// // Set it to a valid value.
82 /// unsafe { x.as_mut_ptr().write(&0); }
83 /// // Extract the initialized data -- this is only allowed *after* properly
84 /// // initializing `x`!
85 /// let x = unsafe { x.assume_init() };
86 /// ```
87 ///
88 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
89 ///
90 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without
91 /// any of the run-time tracking and without any of the safety checks.
92 ///
93 /// ## out-pointers
94 ///
95 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
96 /// from a function, pass it a pointer to some (uninitialized) memory to put the
97 /// result into. This can be useful when it is important for the caller to control
98 /// how the memory the result is stored in gets allocated, and you want to avoid
99 /// unnecessary moves.
100 ///
101 /// ```
102 /// use std::mem::MaybeUninit;
103 ///
104 /// unsafe fn make_vec(out: *mut Vec<i32>) {
105 ///     // `write` does not drop the old contents, which is important.
106 ///     out.write(vec![1, 2, 3]);
107 /// }
108 ///
109 /// let mut v = MaybeUninit::uninit();
110 /// unsafe { make_vec(v.as_mut_ptr()); }
111 /// // Now we know `v` is initialized! This also makes sure the vector gets
112 /// // properly dropped.
113 /// let v = unsafe { v.assume_init() };
114 /// assert_eq!(&v, &[1, 2, 3]);
115 /// ```
116 ///
117 /// ## Initializing an array element-by-element
118 ///
119 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
120 ///
121 /// ```
122 /// use std::mem::{self, MaybeUninit};
123 ///
124 /// let data = {
125 ///     // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
126 ///     // safe because the type we are claiming to have initialized here is a
127 ///     // bunch of `MaybeUninit`s, which do not require initialization.
128 ///     let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
129 ///         MaybeUninit::uninit().assume_init()
130 ///     };
131 ///
132 ///     // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
133 ///     // assignment instead of `ptr::write` does not cause the old
134 ///     // uninitialized value to be dropped. Also if there is a panic during
135 ///     // this loop, we have a memory leak, but there is no memory safety
136 ///     // issue.
137 ///     for elem in &mut data[..] {
138 ///         *elem = MaybeUninit::new(vec![42]);
139 ///     }
140 ///
141 ///     // Everything is initialized. Transmute the array to the
142 ///     // initialized type.
143 ///     unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
144 /// };
145 ///
146 /// assert_eq!(&data[0], &[42]);
147 /// ```
148 ///
149 /// You can also work with partially initialized arrays, which could
150 /// be found in low-level datastructures.
151 ///
152 /// ```
153 /// use std::mem::MaybeUninit;
154 /// use std::ptr;
155 ///
156 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
157 /// // safe because the type we are claiming to have initialized here is a
158 /// // bunch of `MaybeUninit`s, which do not require initialization.
159 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
160 /// // Count the number of elements we have assigned.
161 /// let mut data_len: usize = 0;
162 ///
163 /// for elem in &mut data[0..500] {
164 ///     *elem = MaybeUninit::new(String::from("hello"));
165 ///     data_len += 1;
166 /// }
167 ///
168 /// // For each item in the array, drop if we allocated it.
169 /// for elem in &mut data[0..data_len] {
170 ///     unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
171 /// }
172 /// ```
173 ///
174 /// ## Initializing a struct field-by-field
175 ///
176 /// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field:
177 ///
178 /// ```rust
179 /// use std::mem::MaybeUninit;
180 /// use std::ptr::addr_of_mut;
181 ///
182 /// #[derive(Debug, PartialEq)]
183 /// pub struct Foo {
184 ///     name: String,
185 ///     list: Vec<u8>,
186 /// }
187 ///
188 /// let foo = {
189 ///     let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
190 ///     let ptr = uninit.as_mut_ptr();
191 ///
192 ///     // Initializing the `name` field
193 ///     // Using `write` instead of assignment via `=` to not call `drop` on the
194 ///     // old, uninitialized value.
195 ///     unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); }
196 ///
197 ///     // Initializing the `list` field
198 ///     // If there is a panic here, then the `String` in the `name` field leaks.
199 ///     unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); }
200 ///
201 ///     // All the fields are initialized, so we call `assume_init` to get an initialized Foo.
202 ///     unsafe { uninit.assume_init() }
203 /// };
204 ///
205 /// assert_eq!(
206 ///     foo,
207 ///     Foo {
208 ///         name: "Bob".to_string(),
209 ///         list: vec![0, 1, 2]
210 ///     }
211 /// );
212 /// ```
213 /// [`std::ptr::addr_of_mut`]: crate::ptr::addr_of_mut
214 /// [ub]: ../../reference/behavior-considered-undefined.html
215 ///
216 /// # Layout
217 ///
218 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
219 ///
220 /// ```rust
221 /// use std::mem::{MaybeUninit, size_of, align_of};
222 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
223 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
224 /// ```
225 ///
226 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
227 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
228 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
229 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
230 /// optimizations, potentially resulting in a larger size:
231 ///
232 /// ```rust
233 /// # use std::mem::{MaybeUninit, size_of};
234 /// assert_eq!(size_of::<Option<bool>>(), 1);
235 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
236 /// ```
237 ///
238 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
239 ///
240 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
241 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
242 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
243 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
244 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
245 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
246 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
247 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
248 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
249 /// guarantee may evolve.
250 #[stable(feature = "maybe_uninit", since = "1.36.0")]
251 // Lang item so we can wrap other types in it. This is useful for generators.
252 #[lang = "maybe_uninit"]
253 #[derive(Copy)]
254 #[repr(transparent)]
255 pub union MaybeUninit<T> {
256     uninit: (),
257     value: ManuallyDrop<T>,
258 }
259
260 #[stable(feature = "maybe_uninit", since = "1.36.0")]
261 impl<T: Copy> Clone for MaybeUninit<T> {
262     #[inline(always)]
263     fn clone(&self) -> Self {
264         // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
265         *self
266     }
267 }
268
269 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
270 impl<T> fmt::Debug for MaybeUninit<T> {
271     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272         f.pad(type_name::<Self>())
273     }
274 }
275
276 impl<T> MaybeUninit<T> {
277     /// Creates a new `MaybeUninit<T>` initialized with the given value.
278     /// It is safe to call [`assume_init`] on the return value of this function.
279     ///
280     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
281     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
282     ///
283     /// # Example
284     ///
285     /// ```
286     /// use std::mem::MaybeUninit;
287     ///
288     /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
289     /// ```
290     ///
291     /// [`assume_init`]: MaybeUninit::assume_init
292     #[stable(feature = "maybe_uninit", since = "1.36.0")]
293     #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
294     #[inline(always)]
295     pub const fn new(val: T) -> MaybeUninit<T> {
296         MaybeUninit { value: ManuallyDrop::new(val) }
297     }
298
299     /// Creates a new `MaybeUninit<T>` in an uninitialized state.
300     ///
301     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
302     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
303     ///
304     /// See the [type-level documentation][MaybeUninit] for some examples.
305     ///
306     /// # Example
307     ///
308     /// ```
309     /// use std::mem::MaybeUninit;
310     ///
311     /// let v: MaybeUninit<String> = MaybeUninit::uninit();
312     /// ```
313     #[stable(feature = "maybe_uninit", since = "1.36.0")]
314     #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
315     #[inline(always)]
316     #[rustc_diagnostic_item = "maybe_uninit_uninit"]
317     pub const fn uninit() -> MaybeUninit<T> {
318         MaybeUninit { uninit: () }
319     }
320
321     /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
322     ///
323     /// Note: in a future Rust version this method may become unnecessary
324     /// when Rust allows
325     /// [inline const expressions](https://github.com/rust-lang/rust/issues/76001).
326     /// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
327     ///
328     /// # Examples
329     ///
330     /// ```no_run
331     /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
332     ///
333     /// use std::mem::MaybeUninit;
334     ///
335     /// extern "C" {
336     ///     fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
337     /// }
338     ///
339     /// /// Returns a (possibly smaller) slice of data that was actually read
340     /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
341     ///     unsafe {
342     ///         let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
343     ///         MaybeUninit::slice_assume_init_ref(&buf[..len])
344     ///     }
345     /// }
346     ///
347     /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
348     /// let data = read(&mut buf);
349     /// ```
350     #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
351     #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
352     #[inline(always)]
353     pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
354         // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
355         unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
356     }
357
358     /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
359     /// filled with `0` bytes. It depends on `T` whether that already makes for
360     /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
361     /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
362     /// be null.
363     ///
364     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
365     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
366     ///
367     /// # Example
368     ///
369     /// Correct usage of this function: initializing a struct with zero, where all
370     /// fields of the struct can hold the bit-pattern 0 as a valid value.
371     ///
372     /// ```rust
373     /// use std::mem::MaybeUninit;
374     ///
375     /// let x = MaybeUninit::<(u8, bool)>::zeroed();
376     /// let x = unsafe { x.assume_init() };
377     /// assert_eq!(x, (0, false));
378     /// ```
379     ///
380     /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
381     /// when `0` is not a valid bit-pattern for the type:
382     ///
383     /// ```rust,no_run
384     /// use std::mem::MaybeUninit;
385     ///
386     /// enum NotZero { One = 1, Two = 2 }
387     ///
388     /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
389     /// let x = unsafe { x.assume_init() };
390     /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
391     /// // This is undefined behavior. ⚠️
392     /// ```
393     #[stable(feature = "maybe_uninit", since = "1.36.0")]
394     #[inline]
395     #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
396     pub fn zeroed() -> MaybeUninit<T> {
397         let mut u = MaybeUninit::<T>::uninit();
398         // SAFETY: `u.as_mut_ptr()` points to allocated memory.
399         unsafe {
400             u.as_mut_ptr().write_bytes(0u8, 1);
401         }
402         u
403     }
404
405     /// Sets the value of the `MaybeUninit<T>`.
406     ///
407     /// This overwrites any previous value without dropping it, so be careful
408     /// not to use this twice unless you want to skip running the destructor.
409     /// For your convenience, this also returns a mutable reference to the
410     /// (now safely initialized) contents of `self`.
411     ///
412     /// As the content is stored inside a `MaybeUninit`, the destructor is not
413     /// ran for the inner data if the MaybeUninit leaves scope without a call to
414     /// [`assume_init`], [`assume_init_drop`], or similar. Code that receives
415     /// the mutable reference returned by this function needs to keep this in
416     /// mind. The safety model of Rust regards leaks as safe, but they are
417     /// usually still undesirable. This being said, the mutable reference
418     /// behaves like any other mutable reference would, so assigning a new value
419     /// to it will drop the old content.
420     ///
421     /// [`assume_init`]: Self::assume_init
422     /// [`assume_init_drop`]: Self::assume_init_drop
423     ///
424     /// # Examples
425     ///
426     /// Correct usage of this method:
427     ///
428     /// ```rust
429     /// #![feature(maybe_uninit_extra)]
430     /// use std::mem::MaybeUninit;
431     ///
432     /// let mut x = MaybeUninit::<Vec<u8>>::uninit();
433     ///
434     /// {
435     ///     let hello = x.write((&b"Hello, world!").to_vec());
436     ///     // Setting hello does not leak prior allocations, but drops them
437     ///     *hello = (&b"Hello").to_vec();
438     ///     hello[0] = 'h' as u8;
439     /// }
440     /// // x is initialized now:
441     /// let s = unsafe { x.assume_init() };
442     /// assert_eq!(b"hello", s.as_slice());
443     /// ```
444     ///
445     /// This usage of the method causes a leak:
446     ///
447     /// ```rust
448     /// #![feature(maybe_uninit_extra)]
449     /// use std::mem::MaybeUninit;
450     ///
451     /// let mut x = MaybeUninit::<String>::uninit();
452     ///
453     /// x.write("Hello".to_string());
454     /// // This leaks the contained string:
455     /// x.write("hello".to_string());
456     /// // x is initialized now:
457     /// let s = unsafe { x.assume_init() };
458     /// ```
459     #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
460     #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
461     #[inline(always)]
462     pub const fn write(&mut self, val: T) -> &mut T {
463         *self = MaybeUninit::new(val);
464         // SAFETY: We just initialized this value.
465         unsafe { self.assume_init_mut() }
466     }
467
468     /// Gets a pointer to the contained value. Reading from this pointer or turning it
469     /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
470     /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
471     /// (except inside an `UnsafeCell<T>`).
472     ///
473     /// # Examples
474     ///
475     /// Correct usage of this method:
476     ///
477     /// ```rust
478     /// use std::mem::MaybeUninit;
479     ///
480     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
481     /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
482     /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
483     /// let x_vec = unsafe { &*x.as_ptr() };
484     /// assert_eq!(x_vec.len(), 3);
485     /// ```
486     ///
487     /// *Incorrect* usage of this method:
488     ///
489     /// ```rust,no_run
490     /// use std::mem::MaybeUninit;
491     ///
492     /// let x = MaybeUninit::<Vec<u32>>::uninit();
493     /// let x_vec = unsafe { &*x.as_ptr() };
494     /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
495     /// ```
496     ///
497     /// (Notice that the rules around references to uninitialized data are not finalized yet, but
498     /// until they are, it is advisable to avoid them.)
499     #[stable(feature = "maybe_uninit", since = "1.36.0")]
500     #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
501     #[inline(always)]
502     pub const fn as_ptr(&self) -> *const T {
503         // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
504         self as *const _ as *const T
505     }
506
507     /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
508     /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
509     ///
510     /// # Examples
511     ///
512     /// Correct usage of this method:
513     ///
514     /// ```rust
515     /// use std::mem::MaybeUninit;
516     ///
517     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
518     /// unsafe { x.as_mut_ptr().write(vec![0, 1, 2]); }
519     /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
520     /// // This is okay because we initialized it.
521     /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
522     /// x_vec.push(3);
523     /// assert_eq!(x_vec.len(), 4);
524     /// ```
525     ///
526     /// *Incorrect* usage of this method:
527     ///
528     /// ```rust,no_run
529     /// use std::mem::MaybeUninit;
530     ///
531     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
532     /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
533     /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
534     /// ```
535     ///
536     /// (Notice that the rules around references to uninitialized data are not finalized yet, but
537     /// until they are, it is advisable to avoid them.)
538     #[stable(feature = "maybe_uninit", since = "1.36.0")]
539     #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
540     #[inline(always)]
541     pub const fn as_mut_ptr(&mut self) -> *mut T {
542         // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
543         self as *mut _ as *mut T
544     }
545
546     /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
547     /// to ensure that the data will get dropped, because the resulting `T` is
548     /// subject to the usual drop handling.
549     ///
550     /// # Safety
551     ///
552     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
553     /// state. Calling this when the content is not yet fully initialized causes immediate undefined
554     /// behavior. The [type-level documentation][inv] contains more information about
555     /// this initialization invariant.
556     ///
557     /// [inv]: #initialization-invariant
558     ///
559     /// On top of that, remember that most types have additional invariants beyond merely
560     /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
561     /// is considered initialized (under the current implementation; this does not constitute
562     /// a stable guarantee) because the only requirement the compiler knows about it
563     /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
564     /// *immediate* undefined behavior, but will cause undefined behavior with most
565     /// safe operations (including dropping it).
566     ///
567     /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
568     ///
569     /// # Examples
570     ///
571     /// Correct usage of this method:
572     ///
573     /// ```rust
574     /// use std::mem::MaybeUninit;
575     ///
576     /// let mut x = MaybeUninit::<bool>::uninit();
577     /// unsafe { x.as_mut_ptr().write(true); }
578     /// let x_init = unsafe { x.assume_init() };
579     /// assert_eq!(x_init, true);
580     /// ```
581     ///
582     /// *Incorrect* usage of this method:
583     ///
584     /// ```rust,no_run
585     /// use std::mem::MaybeUninit;
586     ///
587     /// let x = MaybeUninit::<Vec<u32>>::uninit();
588     /// let x_init = unsafe { x.assume_init() };
589     /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
590     /// ```
591     #[stable(feature = "maybe_uninit", since = "1.36.0")]
592     #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
593     #[inline(always)]
594     #[rustc_diagnostic_item = "assume_init"]
595     pub const unsafe fn assume_init(self) -> T {
596         // SAFETY: the caller must guarantee that `self` is initialized.
597         // This also means that `self` must be a `value` variant.
598         unsafe {
599             intrinsics::assert_inhabited::<T>();
600             ManuallyDrop::into_inner(self.value)
601         }
602     }
603
604     /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
605     /// to the usual drop handling.
606     ///
607     /// Whenever possible, it is preferable to use [`assume_init`] instead, which
608     /// prevents duplicating the content of the `MaybeUninit<T>`.
609     ///
610     /// # Safety
611     ///
612     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
613     /// state. Calling this when the content is not yet fully initialized causes undefined
614     /// behavior. The [type-level documentation][inv] contains more information about
615     /// this initialization invariant.
616     ///
617     /// Moreover, similar to the [`ptr::read`] function, this function creates a
618     /// bitwise copy of the contents, regardless whether the contained type
619     /// implements the [`Copy`] trait or not. When using multiple copies of the
620     /// data (by calling `assume_init_read` multiple times, or first calling
621     /// `assume_init_read` and then [`assume_init`]), it is your responsibility
622     /// to ensure that that data may indeed be duplicated.
623     ///
624     /// [inv]: #initialization-invariant
625     /// [`assume_init`]: MaybeUninit::assume_init
626     ///
627     /// # Examples
628     ///
629     /// Correct usage of this method:
630     ///
631     /// ```rust
632     /// #![feature(maybe_uninit_extra)]
633     /// use std::mem::MaybeUninit;
634     ///
635     /// let mut x = MaybeUninit::<u32>::uninit();
636     /// x.write(13);
637     /// let x1 = unsafe { x.assume_init_read() };
638     /// // `u32` is `Copy`, so we may read multiple times.
639     /// let x2 = unsafe { x.assume_init_read() };
640     /// assert_eq!(x1, x2);
641     ///
642     /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
643     /// x.write(None);
644     /// let x1 = unsafe { x.assume_init_read() };
645     /// // Duplicating a `None` value is okay, so we may read multiple times.
646     /// let x2 = unsafe { x.assume_init_read() };
647     /// assert_eq!(x1, x2);
648     /// ```
649     ///
650     /// *Incorrect* usage of this method:
651     ///
652     /// ```rust,no_run
653     /// #![feature(maybe_uninit_extra)]
654     /// use std::mem::MaybeUninit;
655     ///
656     /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
657     /// x.write(Some(vec![0, 1, 2]));
658     /// let x1 = unsafe { x.assume_init_read() };
659     /// let x2 = unsafe { x.assume_init_read() };
660     /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
661     /// // they both get dropped!
662     /// ```
663     #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
664     #[rustc_const_unstable(feature = "maybe_uninit_extra", issue = "63567")]
665     #[inline(always)]
666     pub const unsafe fn assume_init_read(&self) -> T {
667         // SAFETY: the caller must guarantee that `self` is initialized.
668         // Reading from `self.as_ptr()` is safe since `self` should be initialized.
669         unsafe {
670             intrinsics::assert_inhabited::<T>();
671             self.as_ptr().read()
672         }
673     }
674
675     /// Drops the contained value in place.
676     ///
677     /// If you have ownership of the `MaybeUninit`, you can also use
678     /// [`assume_init`] as an alternative.
679     ///
680     /// # Safety
681     ///
682     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
683     /// in an initialized state. Calling this when the content is not yet fully
684     /// initialized causes undefined behavior.
685     ///
686     /// On top of that, all additional invariants of the type `T` must be
687     /// satisfied, as the `Drop` implementation of `T` (or its members) may
688     /// rely on this. For example, setting a [`Vec<T>`] to an invalid but
689     /// non-null address makes it initialized (under the current implementation;
690     /// this does not constitute a stable guarantee), because the only
691     /// requirement the compiler knows about it is that the data pointer must be
692     /// non-null. Dropping such a `Vec<T>` however will cause undefined
693     /// behaviour.
694     ///
695     /// [`assume_init`]: MaybeUninit::assume_init
696     /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
697     #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
698     pub unsafe fn assume_init_drop(&mut self) {
699         // SAFETY: the caller must guarantee that `self` is initialized and
700         // satisfies all invariants of `T`.
701         // Dropping the value in place is safe if that is the case.
702         unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
703     }
704
705     /// Gets a shared reference to the contained value.
706     ///
707     /// This can be useful when we want to access a `MaybeUninit` that has been
708     /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
709     /// of `.assume_init()`).
710     ///
711     /// # Safety
712     ///
713     /// Calling this when the content is not yet fully initialized causes undefined
714     /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
715     /// is in an initialized state.
716     ///
717     /// # Examples
718     ///
719     /// ### Correct usage of this method:
720     ///
721     /// ```rust
722     /// use std::mem::MaybeUninit;
723     ///
724     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
725     /// // Initialize `x`:
726     /// unsafe { x.as_mut_ptr().write(vec![1, 2, 3]); }
727     /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
728     /// // create a shared reference to it:
729     /// let x: &Vec<u32> = unsafe {
730     ///     // SAFETY: `x` has been initialized.
731     ///     x.assume_init_ref()
732     /// };
733     /// assert_eq!(x, &vec![1, 2, 3]);
734     /// ```
735     ///
736     /// ### *Incorrect* usages of this method:
737     ///
738     /// ```rust,no_run
739     /// use std::mem::MaybeUninit;
740     ///
741     /// let x = MaybeUninit::<Vec<u32>>::uninit();
742     /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
743     /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
744     /// ```
745     ///
746     /// ```rust,no_run
747     /// use std::{cell::Cell, mem::MaybeUninit};
748     ///
749     /// let b = MaybeUninit::<Cell<bool>>::uninit();
750     /// // Initialize the `MaybeUninit` using `Cell::set`:
751     /// unsafe {
752     ///     b.assume_init_ref().set(true);
753     ///    // ^^^^^^^^^^^^^^^
754     ///    // Reference to an uninitialized `Cell<bool>`: UB!
755     /// }
756     /// ```
757     #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
758     #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
759     #[inline(always)]
760     pub const unsafe fn assume_init_ref(&self) -> &T {
761         // SAFETY: the caller must guarantee that `self` is initialized.
762         // This also means that `self` must be a `value` variant.
763         unsafe {
764             intrinsics::assert_inhabited::<T>();
765             &*self.as_ptr()
766         }
767     }
768
769     /// Gets a mutable (unique) reference to the contained value.
770     ///
771     /// This can be useful when we want to access a `MaybeUninit` that has been
772     /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
773     /// of `.assume_init()`).
774     ///
775     /// # Safety
776     ///
777     /// Calling this when the content is not yet fully initialized causes undefined
778     /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
779     /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
780     /// initialize a `MaybeUninit`.
781     ///
782     /// # Examples
783     ///
784     /// ### Correct usage of this method:
785     ///
786     /// ```rust
787     /// use std::mem::MaybeUninit;
788     ///
789     /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] }
790     /// # #[cfg(FALSE)]
791     /// extern "C" {
792     ///     /// Initializes *all* the bytes of the input buffer.
793     ///     fn initialize_buffer(buf: *mut [u8; 1024]);
794     /// }
795     ///
796     /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
797     ///
798     /// // Initialize `buf`:
799     /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
800     /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
801     /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes.
802     /// // To assert our buffer has been initialized without copying it, we upgrade
803     /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`:
804     /// let buf: &mut [u8; 1024] = unsafe {
805     ///     // SAFETY: `buf` has been initialized.
806     ///     buf.assume_init_mut()
807     /// };
808     ///
809     /// // Now we can use `buf` as a normal slice:
810     /// buf.sort_unstable();
811     /// assert!(
812     ///     buf.windows(2).all(|pair| pair[0] <= pair[1]),
813     ///     "buffer is sorted",
814     /// );
815     /// ```
816     ///
817     /// ### *Incorrect* usages of this method:
818     ///
819     /// You cannot use `.assume_init_mut()` to initialize a value:
820     ///
821     /// ```rust,no_run
822     /// use std::mem::MaybeUninit;
823     ///
824     /// let mut b = MaybeUninit::<bool>::uninit();
825     /// unsafe {
826     ///     *b.assume_init_mut() = true;
827     ///     // We have created a (mutable) reference to an uninitialized `bool`!
828     ///     // This is undefined behavior. ⚠️
829     /// }
830     /// ```
831     ///
832     /// For instance, you cannot [`Read`] into an uninitialized buffer:
833     ///
834     /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
835     ///
836     /// ```rust,no_run
837     /// use std::{io, mem::MaybeUninit};
838     ///
839     /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
840     /// {
841     ///     let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
842     ///     reader.read_exact(unsafe { buffer.assume_init_mut() })?;
843     ///                             // ^^^^^^^^^^^^^^^^^^^^^^^^
844     ///                             // (mutable) reference to uninitialized memory!
845     ///                             // This is undefined behavior.
846     ///     Ok(unsafe { buffer.assume_init() })
847     /// }
848     /// ```
849     ///
850     /// Nor can you use direct field access to do field-by-field gradual initialization:
851     ///
852     /// ```rust,no_run
853     /// use std::{mem::MaybeUninit, ptr};
854     ///
855     /// struct Foo {
856     ///     a: u32,
857     ///     b: u8,
858     /// }
859     ///
860     /// let foo: Foo = unsafe {
861     ///     let mut foo = MaybeUninit::<Foo>::uninit();
862     ///     ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
863     ///                  // ^^^^^^^^^^^^^^^^^^^^^
864     ///                  // (mutable) reference to uninitialized memory!
865     ///                  // This is undefined behavior.
866     ///     ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
867     ///                  // ^^^^^^^^^^^^^^^^^^^^^
868     ///                  // (mutable) reference to uninitialized memory!
869     ///                  // This is undefined behavior.
870     ///     foo.assume_init()
871     /// };
872     /// ```
873     #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
874     #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
875     #[inline(always)]
876     pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
877         // SAFETY: the caller must guarantee that `self` is initialized.
878         // This also means that `self` must be a `value` variant.
879         unsafe {
880             intrinsics::assert_inhabited::<T>();
881             &mut *self.as_mut_ptr()
882         }
883     }
884
885     /// Extracts the values from an array of `MaybeUninit` containers.
886     ///
887     /// # Safety
888     ///
889     /// It is up to the caller to guarantee that all elements of the array are
890     /// in an initialized state.
891     ///
892     /// # Examples
893     ///
894     /// ```
895     /// #![feature(maybe_uninit_uninit_array)]
896     /// #![feature(maybe_uninit_array_assume_init)]
897     /// use std::mem::MaybeUninit;
898     ///
899     /// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
900     /// array[0] = MaybeUninit::new(0);
901     /// array[1] = MaybeUninit::new(1);
902     /// array[2] = MaybeUninit::new(2);
903     ///
904     /// // SAFETY: Now safe as we initialised all elements
905     /// let array = unsafe {
906     ///     MaybeUninit::array_assume_init(array)
907     /// };
908     ///
909     /// assert_eq!(array, [0, 1, 2]);
910     /// ```
911     #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
912     #[inline(always)]
913     pub unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
914         // SAFETY:
915         // * The caller guarantees that all elements of the array are initialized
916         // * `MaybeUninit<T>` and T are guaranteed to have the same layout
917         // * `MaybeUninit` does not drop, so there are no double-frees
918         // And thus the conversion is safe
919         unsafe {
920             intrinsics::assert_inhabited::<[T; N]>();
921             (&array as *const _ as *const [T; N]).read()
922         }
923     }
924
925     /// Assuming all the elements are initialized, get a slice to them.
926     ///
927     /// # Safety
928     ///
929     /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
930     /// really are in an initialized state.
931     /// Calling this when the content is not yet fully initialized causes undefined behavior.
932     ///
933     /// See [`assume_init_ref`] for more details and examples.
934     ///
935     /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
936     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
937     #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
938     #[inline(always)]
939     pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
940         // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
941         // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
942         // The pointer obtained is valid since it refers to memory owned by `slice` which is a
943         // reference and thus guaranteed to be valid for reads.
944         unsafe { &*(slice as *const [Self] as *const [T]) }
945     }
946
947     /// Assuming all the elements are initialized, get a mutable slice to them.
948     ///
949     /// # Safety
950     ///
951     /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
952     /// really are in an initialized state.
953     /// Calling this when the content is not yet fully initialized causes undefined behavior.
954     ///
955     /// See [`assume_init_mut`] for more details and examples.
956     ///
957     /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
958     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
959     #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
960     #[inline(always)]
961     pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
962         // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
963         // mutable reference which is also guaranteed to be valid for writes.
964         unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
965     }
966
967     /// Gets a pointer to the first element of the array.
968     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
969     #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
970     #[inline(always)]
971     pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
972         this.as_ptr() as *const T
973     }
974
975     /// Gets a mutable pointer to the first element of the array.
976     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
977     #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
978     #[inline(always)]
979     pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
980         this.as_mut_ptr() as *mut T
981     }
982
983     /// Copies the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
984     ///
985     /// If `T` does not implement `Copy`, use [`write_slice_cloned`]
986     ///
987     /// This is similar to [`slice::copy_from_slice`].
988     ///
989     /// # Panics
990     ///
991     /// This function will panic if the two slices have different lengths.
992     ///
993     /// # Examples
994     ///
995     /// ```
996     /// #![feature(maybe_uninit_write_slice)]
997     /// use std::mem::MaybeUninit;
998     ///
999     /// let mut dst = [MaybeUninit::uninit(); 32];
1000     /// let src = [0; 32];
1001     ///
1002     /// let init = MaybeUninit::write_slice(&mut dst, &src);
1003     ///
1004     /// assert_eq!(init, src);
1005     /// ```
1006     ///
1007     /// ```
1008     /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
1009     /// use std::mem::MaybeUninit;
1010     ///
1011     /// let mut vec = Vec::with_capacity(32);
1012     /// let src = [0; 16];
1013     ///
1014     /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);
1015     ///
1016     /// // SAFETY: we have just copied all the elements of len into the spare capacity
1017     /// // the first src.len() elements of the vec are valid now.
1018     /// unsafe {
1019     ///     vec.set_len(src.len());
1020     /// }
1021     ///
1022     /// assert_eq!(vec, src);
1023     /// ```
1024     ///
1025     /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned
1026     #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1027     pub fn write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1028     where
1029         T: Copy,
1030     {
1031         // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1032         let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1033
1034         this.copy_from_slice(uninit_src);
1035
1036         // SAFETY: Valid elements have just been copied into `this` so it is initialized
1037         unsafe { MaybeUninit::slice_assume_init_mut(this) }
1038     }
1039
1040     /// Clones the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
1041     /// Any already initialized elements will not be dropped.
1042     ///
1043     /// If `T` implements `Copy`, use [`write_slice`]
1044     ///
1045     /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1046     ///
1047     /// # Panics
1048     ///
1049     /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1050     ///
1051     /// If there is a panic, the already cloned elements will be dropped.
1052     ///
1053     /// # Examples
1054     ///
1055     /// ```
1056     /// #![feature(maybe_uninit_write_slice)]
1057     /// use std::mem::MaybeUninit;
1058     ///
1059     /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()];
1060     /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()];
1061     ///
1062     /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src);
1063     ///
1064     /// assert_eq!(init, src);
1065     /// ```
1066     ///
1067     /// ```
1068     /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)]
1069     /// use std::mem::MaybeUninit;
1070     ///
1071     /// let mut vec = Vec::with_capacity(32);
1072     /// let src = ["rust", "is", "a", "pretty", "cool", "language"];
1073     ///
1074     /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src);
1075     ///
1076     /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1077     /// // the first src.len() elements of the vec are valid now.
1078     /// unsafe {
1079     ///     vec.set_len(src.len());
1080     /// }
1081     ///
1082     /// assert_eq!(vec, src);
1083     /// ```
1084     ///
1085     /// [`write_slice`]: MaybeUninit::write_slice
1086     #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1087     pub fn write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1088     where
1089         T: Clone,
1090     {
1091         // unlike copy_from_slice this does not call clone_from_slice on the slice
1092         // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1093
1094         struct Guard<'a, T> {
1095             slice: &'a mut [MaybeUninit<T>],
1096             initialized: usize,
1097         }
1098
1099         impl<'a, T> Drop for Guard<'a, T> {
1100             fn drop(&mut self) {
1101                 let initialized_part = &mut self.slice[..self.initialized];
1102                 // SAFETY: this raw slice will contain only initialized objects
1103                 // that's why, it is allowed to drop it.
1104                 unsafe {
1105                     crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part));
1106                 }
1107             }
1108         }
1109
1110         assert_eq!(this.len(), src.len(), "destination and source slices have different lengths");
1111         // NOTE: We need to explicitly slice them to the same length
1112         // for bounds checking to be elided, and the optimizer will
1113         // generate memcpy for simple cases (for example T = u8).
1114         let len = this.len();
1115         let src = &src[..len];
1116
1117         // guard is needed b/c panic might happen during a clone
1118         let mut guard = Guard { slice: this, initialized: 0 };
1119
1120         for i in 0..len {
1121             guard.slice[i].write(src[i].clone());
1122             guard.initialized += 1;
1123         }
1124
1125         super::forget(guard);
1126
1127         // SAFETY: Valid elements have just been written into `this` so it is initialized
1128         unsafe { MaybeUninit::slice_assume_init_mut(this) }
1129     }
1130 }