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