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