]> git.lizzy.rs Git - rust.git/blob - library/core/src/mem/maybe_uninit.rs
6251355b90999bc933a14675d1b257f045e08860
[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 = "const_maybe_assume_init", issue = "none")]
318     #[rustc_allow_const_fn_unstable(const_maybe_assume_init)]
319     #[inline(always)]
320     pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
321         // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
322         unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
323     }
324
325     /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
326     /// filled with `0` bytes. It depends on `T` whether that already makes for
327     /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
328     /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
329     /// be null.
330     ///
331     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
332     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
333     ///
334     /// # Example
335     ///
336     /// Correct usage of this function: initializing a struct with zero, where all
337     /// fields of the struct can hold the bit-pattern 0 as a valid value.
338     ///
339     /// ```rust
340     /// use std::mem::MaybeUninit;
341     ///
342     /// let x = MaybeUninit::<(u8, bool)>::zeroed();
343     /// let x = unsafe { x.assume_init() };
344     /// assert_eq!(x, (0, false));
345     /// ```
346     ///
347     /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
348     /// when `0` is not a valid bit-pattern for the type:
349     ///
350     /// ```rust,no_run
351     /// use std::mem::MaybeUninit;
352     ///
353     /// enum NotZero { One = 1, Two = 2 }
354     ///
355     /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
356     /// let x = unsafe { x.assume_init() };
357     /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
358     /// // This is undefined behavior. ⚠️
359     /// ```
360     #[stable(feature = "maybe_uninit", since = "1.36.0")]
361     #[inline]
362     #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
363     pub fn zeroed() -> MaybeUninit<T> {
364         let mut u = MaybeUninit::<T>::uninit();
365         // SAFETY: `u.as_mut_ptr()` points to allocated memory.
366         unsafe {
367             u.as_mut_ptr().write_bytes(0u8, 1);
368         }
369         u
370     }
371
372     /// Sets the value of the `MaybeUninit<T>`. This overwrites any previous value
373     /// without dropping it, so be careful not to use this twice unless you want to
374     /// skip running the destructor. For your convenience, this also returns a mutable
375     /// reference to the (now safely initialized) contents of `self`.
376     #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
377     #[inline(always)]
378     pub 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_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     #[inline(always)]
579     pub unsafe fn assume_init_read(&self) -> T {
580         // SAFETY: the caller must guarantee that `self` is initialized.
581         // Reading from `self.as_ptr()` is safe since `self` should be initialized.
582         unsafe {
583             intrinsics::assert_inhabited::<T>();
584             self.as_ptr().read()
585         }
586     }
587
588     /// Drops the contained value in place.
589     ///
590     /// If you have ownership of the `MaybeUninit`, you can use [`assume_init`] instead.
591     ///
592     /// # Safety
593     ///
594     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
595     /// in an initialized state. Calling this when the content is not yet fully
596     /// initialized causes undefined behavior.
597     ///
598     /// On top of that, all additional invariants of the type `T` must be
599     /// satisfied, as the `Drop` implementation of `T` (or its members) may
600     /// rely on this. For example, a `1`-initialized [`Vec<T>`] is considered
601     /// initialized (under the current implementation; this does not constitute
602     /// a stable guarantee) because the only requirement the compiler knows
603     /// about it is that the data pointer must be non-null. Dropping such a
604     /// `Vec<T>` however will cause undefined behaviour.
605     ///
606     /// [`assume_init`]: MaybeUninit::assume_init
607     /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
608     #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
609     pub unsafe fn assume_init_drop(&mut self) {
610         // SAFETY: the caller must guarantee that `self` is initialized and
611         // satisfies all invariants of `T`.
612         // Dropping the value in place is safe if that is the case.
613         unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
614     }
615
616     /// Gets a shared reference to the contained value.
617     ///
618     /// This can be useful when we want to access a `MaybeUninit` that has been
619     /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
620     /// of `.assume_init()`).
621     ///
622     /// # Safety
623     ///
624     /// Calling this when the content is not yet fully initialized causes undefined
625     /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
626     /// is in an initialized state.
627     ///
628     /// # Examples
629     ///
630     /// ### Correct usage of this method:
631     ///
632     /// ```rust
633     /// #![feature(maybe_uninit_ref)]
634     /// use std::mem::MaybeUninit;
635     ///
636     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
637     /// // Initialize `x`:
638     /// unsafe { x.as_mut_ptr().write(vec![1, 2, 3]); }
639     /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
640     /// // create a shared reference to it:
641     /// let x: &Vec<u32> = unsafe {
642     ///     // SAFETY: `x` has been initialized.
643     ///     x.assume_init_ref()
644     /// };
645     /// assert_eq!(x, &vec![1, 2, 3]);
646     /// ```
647     ///
648     /// ### *Incorrect* usages of this method:
649     ///
650     /// ```rust,no_run
651     /// #![feature(maybe_uninit_ref)]
652     /// use std::mem::MaybeUninit;
653     ///
654     /// let x = MaybeUninit::<Vec<u32>>::uninit();
655     /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
656     /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
657     /// ```
658     ///
659     /// ```rust,no_run
660     /// #![feature(maybe_uninit_ref)]
661     /// use std::{cell::Cell, mem::MaybeUninit};
662     ///
663     /// let b = MaybeUninit::<Cell<bool>>::uninit();
664     /// // Initialize the `MaybeUninit` using `Cell::set`:
665     /// unsafe {
666     ///     b.assume_init_ref().set(true);
667     ///    // ^^^^^^^^^^^^^^^
668     ///    // Reference to an uninitialized `Cell<bool>`: UB!
669     /// }
670     /// ```
671     #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
672     #[inline(always)]
673     pub unsafe fn assume_init_ref(&self) -> &T {
674         // SAFETY: the caller must guarantee that `self` is initialized.
675         // This also means that `self` must be a `value` variant.
676         unsafe {
677             intrinsics::assert_inhabited::<T>();
678             &*self.value
679         }
680     }
681
682     /// Gets a mutable (unique) reference to the contained value.
683     ///
684     /// This can be useful when we want to access a `MaybeUninit` that has been
685     /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
686     /// of `.assume_init()`).
687     ///
688     /// # Safety
689     ///
690     /// Calling this when the content is not yet fully initialized causes undefined
691     /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
692     /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
693     /// initialize a `MaybeUninit`.
694     ///
695     /// # Examples
696     ///
697     /// ### Correct usage of this method:
698     ///
699     /// ```rust
700     /// #![feature(maybe_uninit_ref)]
701     /// use std::mem::MaybeUninit;
702     ///
703     /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 2048]) { *buf = [0; 2048] }
704     /// # #[cfg(FALSE)]
705     /// extern "C" {
706     ///     /// Initializes *all* the bytes of the input buffer.
707     ///     fn initialize_buffer(buf: *mut [u8; 2048]);
708     /// }
709     ///
710     /// let mut buf = MaybeUninit::<[u8; 2048]>::uninit();
711     ///
712     /// // Initialize `buf`:
713     /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
714     /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
715     /// // However, using `.assume_init()` may trigger a `memcpy` of the 2048 bytes.
716     /// // To assert our buffer has been initialized without copying it, we upgrade
717     /// // the `&mut MaybeUninit<[u8; 2048]>` to a `&mut [u8; 2048]`:
718     /// let buf: &mut [u8; 2048] = unsafe {
719     ///     // SAFETY: `buf` has been initialized.
720     ///     buf.assume_init_mut()
721     /// };
722     ///
723     /// // Now we can use `buf` as a normal slice:
724     /// buf.sort_unstable();
725     /// assert!(
726     ///     buf.windows(2).all(|pair| pair[0] <= pair[1]),
727     ///     "buffer is sorted",
728     /// );
729     /// ```
730     ///
731     /// ### *Incorrect* usages of this method:
732     ///
733     /// You cannot use `.assume_init_mut()` to initialize a value:
734     ///
735     /// ```rust,no_run
736     /// #![feature(maybe_uninit_ref)]
737     /// use std::mem::MaybeUninit;
738     ///
739     /// let mut b = MaybeUninit::<bool>::uninit();
740     /// unsafe {
741     ///     *b.assume_init_mut() = true;
742     ///     // We have created a (mutable) reference to an uninitialized `bool`!
743     ///     // This is undefined behavior. ⚠️
744     /// }
745     /// ```
746     ///
747     /// For instance, you cannot [`Read`] into an uninitialized buffer:
748     ///
749     /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
750     ///
751     /// ```rust,no_run
752     /// #![feature(maybe_uninit_ref)]
753     /// use std::{io, mem::MaybeUninit};
754     ///
755     /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
756     /// {
757     ///     let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
758     ///     reader.read_exact(unsafe { buffer.assume_init_mut() })?;
759     ///                             // ^^^^^^^^^^^^^^^^^^^^^^^^
760     ///                             // (mutable) reference to uninitialized memory!
761     ///                             // This is undefined behavior.
762     ///     Ok(unsafe { buffer.assume_init() })
763     /// }
764     /// ```
765     ///
766     /// Nor can you use direct field access to do field-by-field gradual initialization:
767     ///
768     /// ```rust,no_run
769     /// #![feature(maybe_uninit_ref)]
770     /// use std::{mem::MaybeUninit, ptr};
771     ///
772     /// struct Foo {
773     ///     a: u32,
774     ///     b: u8,
775     /// }
776     ///
777     /// let foo: Foo = unsafe {
778     ///     let mut foo = MaybeUninit::<Foo>::uninit();
779     ///     ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
780     ///                  // ^^^^^^^^^^^^^^^^^^^^^
781     ///                  // (mutable) reference to uninitialized memory!
782     ///                  // This is undefined behavior.
783     ///     ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
784     ///                  // ^^^^^^^^^^^^^^^^^^^^^
785     ///                  // (mutable) reference to uninitialized memory!
786     ///                  // This is undefined behavior.
787     ///     foo.assume_init()
788     /// };
789     /// ```
790     // FIXME(#76092): We currently rely on the above being incorrect, i.e., we have references
791     // to uninitialized data (e.g., in `libcore/fmt/float.rs`).  We should make
792     // a final decision about the rules before stabilization.
793     #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
794     #[inline(always)]
795     pub unsafe fn assume_init_mut(&mut self) -> &mut T {
796         // SAFETY: the caller must guarantee that `self` is initialized.
797         // This also means that `self` must be a `value` variant.
798         unsafe {
799             intrinsics::assert_inhabited::<T>();
800             &mut *self.value
801         }
802     }
803
804     /// Assuming all the elements are initialized, get a slice to them.
805     ///
806     /// # Safety
807     ///
808     /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
809     /// really are in an initialized state.
810     /// Calling this when the content is not yet fully initialized causes undefined behavior.
811     ///
812     /// See [`assume_init_ref`] for more details and examples.
813     ///
814     /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
815     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
816     #[rustc_const_unstable(feature = "const_maybe_assume_init", issue = "none")]
817     #[inline(always)]
818     pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
819         // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
820         // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
821         // The pointer obtained is valid since it refers to memory owned by `slice` which is a
822         // reference and thus guaranteed to be valid for reads.
823         unsafe { &*(slice as *const [Self] as *const [T]) }
824     }
825
826     /// Assuming all the elements are initialized, get a mutable slice to them.
827     ///
828     /// # Safety
829     ///
830     /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
831     /// really are in an initialized state.
832     /// Calling this when the content is not yet fully initialized causes undefined behavior.
833     ///
834     /// See [`assume_init_mut`] for more details and examples.
835     ///
836     /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
837     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
838     #[rustc_const_unstable(feature = "const_maybe_assume_init", issue = "none")]
839     #[inline(always)]
840     pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
841         // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
842         // mutable reference which is also guaranteed to be valid for writes.
843         unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
844     }
845
846     /// Gets a pointer to the first element of the array.
847     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
848     #[rustc_const_unstable(feature = "const_maybe_assume_init", issue = "none")]
849     #[inline(always)]
850     pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
851         this.as_ptr() as *const T
852     }
853
854     /// Gets a mutable pointer to the first element of the array.
855     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
856     #[rustc_const_unstable(feature = "const_maybe_assume_init", issue = "none")]
857     #[inline(always)]
858     pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
859         this.as_mut_ptr() as *mut T
860     }
861 }