]> git.lizzy.rs Git - rust.git/blob - library/core/src/mem/maybe_uninit.rs
b64abf68c5e4a6184d0af45d889e7f1cba0891f2
[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
6 /// A wrapper type to construct uninitialized instances of `T`.
7 ///
8 /// # Initialization invariant
9 ///
10 /// The compiler, in general, assumes that a variable is properly initialized
11 /// according to the requirements of the variable's type. For example, a variable of
12 /// reference type must be aligned and non-NULL. This is an invariant that must
13 /// *always* be upheld, even in unsafe code. As a consequence, zero-initializing a
14 /// variable of reference type causes instantaneous [undefined behavior][ub],
15 /// no matter whether that reference ever gets used to access memory:
16 ///
17 /// ```rust,no_run
18 /// # #![allow(invalid_value)]
19 /// use std::mem::{self, MaybeUninit};
20 ///
21 /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior! ⚠️
22 /// // The equivalent code with `MaybeUninit<&i32>`:
23 /// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! ⚠️
24 /// ```
25 ///
26 /// This is exploited by the compiler for various optimizations, such as eliding
27 /// run-time checks and optimizing `enum` layout.
28 ///
29 /// Similarly, entirely uninitialized memory may have any content, while a `bool` must
30 /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior:
31 ///
32 /// ```rust,no_run
33 /// # #![allow(invalid_value)]
34 /// use std::mem::{self, MaybeUninit};
35 ///
36 /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
37 /// // The equivalent code with `MaybeUninit<bool>`:
38 /// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
39 /// ```
40 ///
41 /// Moreover, uninitialized memory is special in that the compiler knows that
42 /// it does not have a fixed value. This makes it undefined behavior to have
43 /// uninitialized data in a variable even if that variable has an integer type,
44 /// which otherwise can hold any *fixed* bit pattern:
45 ///
46 /// ```rust,no_run
47 /// # #![allow(invalid_value)]
48 /// use std::mem::{self, MaybeUninit};
49 ///
50 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
51 /// // The equivalent code with `MaybeUninit<i32>`:
52 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
53 /// ```
54 /// (Notice that the rules around uninitialized integers are not finalized yet, but
55 /// until they are, it is advisable to avoid them.)
56 ///
57 /// On top of that, remember that most types have additional invariants beyond merely
58 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
59 /// is considered initialized (under the current implementation; this does not constitute
60 /// a stable guarantee) because the only requirement the compiler knows about it
61 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
62 /// *immediate* undefined behavior, but will cause undefined behavior with most
63 /// safe operations (including dropping it).
64 ///
65 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
66 ///
67 /// # Examples
68 ///
69 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
70 /// It is a signal to the compiler indicating that the data here might *not*
71 /// be initialized:
72 ///
73 /// ```rust
74 /// use std::mem::MaybeUninit;
75 ///
76 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
77 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
78 /// let mut x = MaybeUninit::<&i32>::uninit();
79 /// // Set it to a valid value.
80 /// unsafe { x.as_mut_ptr().write(&0); }
81 /// // Extract the initialized data -- this is only allowed *after* properly
82 /// // initializing `x`!
83 /// let x = unsafe { x.assume_init() };
84 /// ```
85 ///
86 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
87 ///
88 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without
89 /// any of the run-time tracking and without any of the safety checks.
90 ///
91 /// ## out-pointers
92 ///
93 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
94 /// from a function, pass it a pointer to some (uninitialized) memory to put the
95 /// result into. This can be useful when it is important for the caller to control
96 /// how the memory the result is stored in gets allocated, and you want to avoid
97 /// unnecessary moves.
98 ///
99 /// ```
100 /// use std::mem::MaybeUninit;
101 ///
102 /// unsafe fn make_vec(out: *mut Vec<i32>) {
103 ///     // `write` does not drop the old contents, which is important.
104 ///     out.write(vec![1, 2, 3]);
105 /// }
106 ///
107 /// let mut v = MaybeUninit::uninit();
108 /// unsafe { make_vec(v.as_mut_ptr()); }
109 /// // Now we know `v` is initialized! This also makes sure the vector gets
110 /// // properly dropped.
111 /// let v = unsafe { v.assume_init() };
112 /// assert_eq!(&v, &[1, 2, 3]);
113 /// ```
114 ///
115 /// ## Initializing an array element-by-element
116 ///
117 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
118 ///
119 /// ```
120 /// use std::mem::{self, MaybeUninit};
121 ///
122 /// let data = {
123 ///     // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
124 ///     // safe because the type we are claiming to have initialized here is a
125 ///     // bunch of `MaybeUninit`s, which do not require initialization.
126 ///     let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
127 ///         MaybeUninit::uninit().assume_init()
128 ///     };
129 ///
130 ///     // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
131 ///     // assignment instead of `ptr::write` does not cause the old
132 ///     // uninitialized value to be dropped. Also if there is a panic during
133 ///     // this loop, we have a memory leak, but there is no memory safety
134 ///     // issue.
135 ///     for elem in &mut data[..] {
136 ///         *elem = MaybeUninit::new(vec![42]);
137 ///     }
138 ///
139 ///     // Everything is initialized. Transmute the array to the
140 ///     // initialized type.
141 ///     unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
142 /// };
143 ///
144 /// assert_eq!(&data[0], &[42]);
145 /// ```
146 ///
147 /// You can also work with partially initialized arrays, which could
148 /// be found in low-level datastructures.
149 ///
150 /// ```
151 /// use std::mem::MaybeUninit;
152 /// use std::ptr;
153 ///
154 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
155 /// // safe because the type we are claiming to have initialized here is a
156 /// // bunch of `MaybeUninit`s, which do not require initialization.
157 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
158 /// // Count the number of elements we have assigned.
159 /// let mut data_len: usize = 0;
160 ///
161 /// for elem in &mut data[0..500] {
162 ///     *elem = MaybeUninit::new(String::from("hello"));
163 ///     data_len += 1;
164 /// }
165 ///
166 /// // For each item in the array, drop if we allocated it.
167 /// for elem in &mut data[0..data_len] {
168 ///     unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
169 /// }
170 /// ```
171 ///
172 /// ## Initializing a struct field-by-field
173 ///
174 /// There is currently no supported way to create a raw pointer or reference
175 /// to a field of a struct inside `MaybeUninit<Struct>`. That means it is not possible
176 /// to create a struct by calling `MaybeUninit::uninit::<Struct>()` and then writing
177 /// to its fields.
178 ///
179 /// [ub]: ../../reference/behavior-considered-undefined.html
180 ///
181 /// # Layout
182 ///
183 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
184 ///
185 /// ```rust
186 /// use std::mem::{MaybeUninit, size_of, align_of};
187 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
188 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
189 /// ```
190 ///
191 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
192 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
193 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
194 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
195 /// optimizations, potentially resulting in a larger size:
196 ///
197 /// ```rust
198 /// # use std::mem::{MaybeUninit, size_of};
199 /// assert_eq!(size_of::<Option<bool>>(), 1);
200 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
201 /// ```
202 ///
203 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
204 ///
205 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
206 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
207 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
208 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
209 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
210 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
211 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
212 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
213 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
214 /// guarantee may evolve.
215 #[stable(feature = "maybe_uninit", since = "1.36.0")]
216 // Lang item so we can wrap other types in it. This is useful for generators.
217 #[lang = "maybe_uninit"]
218 #[derive(Copy)]
219 #[repr(transparent)]
220 pub union MaybeUninit<T> {
221     uninit: (),
222     value: ManuallyDrop<T>,
223 }
224
225 #[stable(feature = "maybe_uninit", since = "1.36.0")]
226 impl<T: Copy> Clone for MaybeUninit<T> {
227     #[inline(always)]
228     fn clone(&self) -> Self {
229         // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
230         *self
231     }
232 }
233
234 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
235 impl<T> fmt::Debug for MaybeUninit<T> {
236     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237         f.pad(type_name::<Self>())
238     }
239 }
240
241 impl<T> MaybeUninit<T> {
242     /// Creates a new `MaybeUninit<T>` initialized with the given value.
243     /// It is safe to call [`assume_init`] on the return value of this function.
244     ///
245     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
246     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
247     ///
248     /// [`assume_init`]: MaybeUninit::assume_init
249     #[stable(feature = "maybe_uninit", since = "1.36.0")]
250     #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
251     #[inline(always)]
252     pub const fn new(val: T) -> MaybeUninit<T> {
253         MaybeUninit { value: ManuallyDrop::new(val) }
254     }
255
256     /// Creates a new `MaybeUninit<T>` in an uninitialized state.
257     ///
258     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
259     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
260     ///
261     /// See the [type-level documentation][type] for some examples.
262     ///
263     /// [type]: union.MaybeUninit.html
264     #[stable(feature = "maybe_uninit", since = "1.36.0")]
265     #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
266     #[inline(always)]
267     #[rustc_diagnostic_item = "maybe_uninit_uninit"]
268     pub const fn uninit() -> MaybeUninit<T> {
269         MaybeUninit { uninit: () }
270     }
271
272     /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
273     ///
274     /// Note: in a future Rust version this method may become unnecessary
275     /// when array literal syntax allows
276     /// [repeating const expressions](https://github.com/rust-lang/rust/issues/49147).
277     /// The example below could then use `let mut buf = [MaybeUninit::<u8>::uninit(); 32];`.
278     ///
279     /// # Examples
280     ///
281     /// ```no_run
282     /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
283     ///
284     /// use std::mem::MaybeUninit;
285     ///
286     /// extern "C" {
287     ///     fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
288     /// }
289     ///
290     /// /// Returns a (possibly smaller) slice of data that was actually read
291     /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
292     ///     unsafe {
293     ///         let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
294     ///         MaybeUninit::slice_assume_init_ref(&buf[..len])
295     ///     }
296     /// }
297     ///
298     /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
299     /// let data = read(&mut buf);
300     /// ```
301     #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
302     #[inline(always)]
303     pub fn uninit_array<const LEN: usize>() -> [Self; LEN] {
304         // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
305         unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
306     }
307
308     /// A promotable constant, equivalent to `uninit()`.
309     #[unstable(
310         feature = "internal_uninit_const",
311         issue = "none",
312         reason = "hack to work around promotability"
313     )]
314     pub const UNINIT: Self = Self::uninit();
315
316     /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
317     /// filled with `0` bytes. It depends on `T` whether that already makes for
318     /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
319     /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
320     /// be null.
321     ///
322     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
323     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
324     ///
325     /// # Example
326     ///
327     /// Correct usage of this function: initializing a struct with zero, where all
328     /// fields of the struct can hold the bit-pattern 0 as a valid value.
329     ///
330     /// ```rust
331     /// use std::mem::MaybeUninit;
332     ///
333     /// let x = MaybeUninit::<(u8, bool)>::zeroed();
334     /// let x = unsafe { x.assume_init() };
335     /// assert_eq!(x, (0, false));
336     /// ```
337     ///
338     /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
339     /// when `0` is not a valid bit-pattern for the type:
340     ///
341     /// ```rust,no_run
342     /// use std::mem::MaybeUninit;
343     ///
344     /// enum NotZero { One = 1, Two = 2 };
345     ///
346     /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
347     /// let x = unsafe { x.assume_init() };
348     /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
349     /// // This is undefined behavior. ⚠️
350     /// ```
351     #[stable(feature = "maybe_uninit", since = "1.36.0")]
352     #[inline]
353     #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
354     pub fn zeroed() -> MaybeUninit<T> {
355         let mut u = MaybeUninit::<T>::uninit();
356         // SAFETY: `u.as_mut_ptr()` points to allocated memory.
357         unsafe {
358             u.as_mut_ptr().write_bytes(0u8, 1);
359         }
360         u
361     }
362
363     /// Sets the value of the `MaybeUninit<T>`. This overwrites any previous value
364     /// without dropping it, so be careful not to use this twice unless you want to
365     /// skip running the destructor. For your convenience, this also returns a mutable
366     /// reference to the (now safely initialized) contents of `self`.
367     #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
368     #[inline(always)]
369     pub fn write(&mut self, val: T) -> &mut T {
370         *self = MaybeUninit::new(val);
371         // SAFETY: We just initialized this value.
372         unsafe { self.assume_init_mut() }
373     }
374
375     /// Gets a pointer to the contained value. Reading from this pointer or turning it
376     /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
377     /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
378     /// (except inside an `UnsafeCell<T>`).
379     ///
380     /// # Examples
381     ///
382     /// Correct usage of this method:
383     ///
384     /// ```rust
385     /// use std::mem::MaybeUninit;
386     ///
387     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
388     /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
389     /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
390     /// let x_vec = unsafe { &*x.as_ptr() };
391     /// assert_eq!(x_vec.len(), 3);
392     /// ```
393     ///
394     /// *Incorrect* usage of this method:
395     ///
396     /// ```rust,no_run
397     /// use std::mem::MaybeUninit;
398     ///
399     /// let x = MaybeUninit::<Vec<u32>>::uninit();
400     /// let x_vec = unsafe { &*x.as_ptr() };
401     /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
402     /// ```
403     ///
404     /// (Notice that the rules around references to uninitialized data are not finalized yet, but
405     /// until they are, it is advisable to avoid them.)
406     #[stable(feature = "maybe_uninit", since = "1.36.0")]
407     #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
408     #[inline(always)]
409     pub const fn as_ptr(&self) -> *const T {
410         // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
411         self as *const _ as *const T
412     }
413
414     /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
415     /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
416     ///
417     /// # Examples
418     ///
419     /// Correct usage of this method:
420     ///
421     /// ```rust
422     /// use std::mem::MaybeUninit;
423     ///
424     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
425     /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
426     /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
427     /// // This is okay because we initialized it.
428     /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
429     /// x_vec.push(3);
430     /// assert_eq!(x_vec.len(), 4);
431     /// ```
432     ///
433     /// *Incorrect* usage of this method:
434     ///
435     /// ```rust,no_run
436     /// use std::mem::MaybeUninit;
437     ///
438     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
439     /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
440     /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
441     /// ```
442     ///
443     /// (Notice that the rules around references to uninitialized data are not finalized yet, but
444     /// until they are, it is advisable to avoid them.)
445     #[stable(feature = "maybe_uninit", since = "1.36.0")]
446     #[rustc_const_unstable(feature = "const_maybe_uninit_as_ptr", issue = "75251")]
447     #[inline(always)]
448     pub const fn as_mut_ptr(&mut self) -> *mut T {
449         // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
450         self as *mut _ as *mut T
451     }
452
453     /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
454     /// to ensure that the data will get dropped, because the resulting `T` is
455     /// subject to the usual drop handling.
456     ///
457     /// # Safety
458     ///
459     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
460     /// state. Calling this when the content is not yet fully initialized causes immediate undefined
461     /// behavior. The [type-level documentation][inv] contains more information about
462     /// this initialization invariant.
463     ///
464     /// [inv]: #initialization-invariant
465     ///
466     /// On top of that, remember that most types have additional invariants beyond merely
467     /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
468     /// is considered initialized (under the current implementation; this does not constitute
469     /// a stable guarantee) because the only requirement the compiler knows about it
470     /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
471     /// *immediate* undefined behavior, but will cause undefined behavior with most
472     /// safe operations (including dropping it).
473     ///
474     /// # Examples
475     ///
476     /// Correct usage of this method:
477     ///
478     /// ```rust
479     /// use std::mem::MaybeUninit;
480     ///
481     /// let mut x = MaybeUninit::<bool>::uninit();
482     /// unsafe { x.as_mut_ptr().write(true); }
483     /// let x_init = unsafe { x.assume_init() };
484     /// assert_eq!(x_init, true);
485     /// ```
486     ///
487     /// *Incorrect* usage of this method:
488     ///
489     /// ```rust,no_run
490     /// use std::mem::MaybeUninit;
491     ///
492     /// let x = MaybeUninit::<Vec<u32>>::uninit();
493     /// let x_init = unsafe { x.assume_init() };
494     /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
495     /// ```
496     #[stable(feature = "maybe_uninit", since = "1.36.0")]
497     #[inline(always)]
498     #[rustc_diagnostic_item = "assume_init"]
499     pub unsafe fn assume_init(self) -> T {
500         // SAFETY: the caller must guarantee that `self` is initialized.
501         // This also means that `self` must be a `value` variant.
502         unsafe {
503             intrinsics::assert_inhabited::<T>();
504             ManuallyDrop::into_inner(self.value)
505         }
506     }
507
508     /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
509     /// to the usual drop handling.
510     ///
511     /// Whenever possible, it is preferable to use [`assume_init`] instead, which
512     /// prevents duplicating the content of the `MaybeUninit<T>`.
513     ///
514     /// # Safety
515     ///
516     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
517     /// state. Calling this when the content is not yet fully initialized causes undefined
518     /// behavior. The [type-level documentation][inv] contains more information about
519     /// this initialization invariant.
520     ///
521     /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit<T>`. When using
522     /// multiple copies of the data (by calling `read` multiple times, or first
523     /// calling `read` and then [`assume_init`]), it is your responsibility
524     /// to ensure that that data may indeed be duplicated.
525     ///
526     /// [inv]: #initialization-invariant
527     /// [`assume_init`]: MaybeUninit::assume_init
528     ///
529     /// # Examples
530     ///
531     /// Correct usage of this method:
532     ///
533     /// ```rust
534     /// #![feature(maybe_uninit_extra)]
535     /// use std::mem::MaybeUninit;
536     ///
537     /// let mut x = MaybeUninit::<u32>::uninit();
538     /// x.write(13);
539     /// let x1 = unsafe { x.read() };
540     /// // `u32` is `Copy`, so we may read multiple times.
541     /// let x2 = unsafe { x.read() };
542     /// assert_eq!(x1, x2);
543     ///
544     /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
545     /// x.write(None);
546     /// let x1 = unsafe { x.read() };
547     /// // Duplicating a `None` value is okay, so we may read multiple times.
548     /// let x2 = unsafe { x.read() };
549     /// assert_eq!(x1, x2);
550     /// ```
551     ///
552     /// *Incorrect* usage of this method:
553     ///
554     /// ```rust,no_run
555     /// #![feature(maybe_uninit_extra)]
556     /// use std::mem::MaybeUninit;
557     ///
558     /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
559     /// x.write(Some(vec![0,1,2]));
560     /// let x1 = unsafe { x.read() };
561     /// let x2 = unsafe { x.read() };
562     /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
563     /// // they both get dropped!
564     /// ```
565     #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
566     #[inline(always)]
567     pub unsafe fn read(&self) -> T {
568         // SAFETY: the caller must guarantee that `self` is initialized.
569         // Reading from `self.as_ptr()` is safe since `self` should be initialized.
570         unsafe {
571             intrinsics::assert_inhabited::<T>();
572             self.as_ptr().read()
573         }
574     }
575
576     /// Gets a shared reference to the contained value.
577     ///
578     /// This can be useful when we want to access a `MaybeUninit` that has been
579     /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
580     /// of `.assume_init()`).
581     ///
582     /// # Safety
583     ///
584     /// Calling this when the content is not yet fully initialized causes undefined
585     /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
586     /// is in an initialized state.
587     ///
588     /// # Examples
589     ///
590     /// ### Correct usage of this method:
591     ///
592     /// ```rust
593     /// #![feature(maybe_uninit_ref)]
594     /// use std::mem::MaybeUninit;
595     ///
596     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
597     /// // Initialize `x`:
598     /// unsafe { x.as_mut_ptr().write(vec![1, 2, 3]); }
599     /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
600     /// // create a shared reference to it:
601     /// let x: &Vec<u32> = unsafe {
602     ///     // Safety: `x` has been initialized.
603     ///     x.assume_init_ref()
604     /// };
605     /// assert_eq!(x, &vec![1, 2, 3]);
606     /// ```
607     ///
608     /// ### *Incorrect* usages of this method:
609     ///
610     /// ```rust,no_run
611     /// #![feature(maybe_uninit_ref)]
612     /// use std::mem::MaybeUninit;
613     ///
614     /// let x = MaybeUninit::<Vec<u32>>::uninit();
615     /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
616     /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
617     /// ```
618     ///
619     /// ```rust,no_run
620     /// #![feature(maybe_uninit_ref)]
621     /// use std::{cell::Cell, mem::MaybeUninit};
622     ///
623     /// let b = MaybeUninit::<Cell<bool>>::uninit();
624     /// // Initialize the `MaybeUninit` using `Cell::set`:
625     /// unsafe {
626     ///     b.assume_init_ref().set(true);
627     ///    // ^^^^^^^^^^^^^^^
628     ///    // Reference to an uninitialized `Cell<bool>`: UB!
629     /// }
630     /// ```
631     #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
632     #[inline(always)]
633     pub unsafe fn assume_init_ref(&self) -> &T {
634         // SAFETY: the caller must guarantee that `self` is initialized.
635         // This also means that `self` must be a `value` variant.
636         unsafe {
637             intrinsics::assert_inhabited::<T>();
638             &*self.value
639         }
640     }
641
642     /// Gets a mutable (unique) reference to the contained value.
643     ///
644     /// This can be useful when we want to access a `MaybeUninit` that has been
645     /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
646     /// of `.assume_init()`).
647     ///
648     /// # Safety
649     ///
650     /// Calling this when the content is not yet fully initialized causes undefined
651     /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
652     /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
653     /// initialize a `MaybeUninit`.
654     ///
655     /// # Examples
656     ///
657     /// ### Correct usage of this method:
658     ///
659     /// ```rust
660     /// #![feature(maybe_uninit_ref)]
661     /// use std::mem::MaybeUninit;
662     ///
663     /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 2048]) { *buf = [0; 2048] }
664     /// # #[cfg(FALSE)]
665     /// extern "C" {
666     ///     /// Initializes *all* the bytes of the input buffer.
667     ///     fn initialize_buffer(buf: *mut [u8; 2048]);
668     /// }
669     ///
670     /// let mut buf = MaybeUninit::<[u8; 2048]>::uninit();
671     ///
672     /// // Initialize `buf`:
673     /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
674     /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
675     /// // However, using `.assume_init()` may trigger a `memcpy` of the 2048 bytes.
676     /// // To assert our buffer has been initialized without copying it, we upgrade
677     /// // the `&mut MaybeUninit<[u8; 2048]>` to a `&mut [u8; 2048]`:
678     /// let buf: &mut [u8; 2048] = unsafe {
679     ///     // Safety: `buf` has been initialized.
680     ///     buf.assume_init_mut()
681     /// };
682     ///
683     /// // Now we can use `buf` as a normal slice:
684     /// buf.sort_unstable();
685     /// assert!(
686     ///     buf.windows(2).all(|pair| pair[0] <= pair[1]),
687     ///     "buffer is sorted",
688     /// );
689     /// ```
690     ///
691     /// ### *Incorrect* usages of this method:
692     ///
693     /// You cannot use `.assume_init_mut()` to initialize a value:
694     ///
695     /// ```rust,no_run
696     /// #![feature(maybe_uninit_ref)]
697     /// use std::mem::MaybeUninit;
698     ///
699     /// let mut b = MaybeUninit::<bool>::uninit();
700     /// unsafe {
701     ///     *b.assume_init_mut() = true;
702     ///     // We have created a (mutable) reference to an uninitialized `bool`!
703     ///     // This is undefined behavior. ⚠️
704     /// }
705     /// ```
706     ///
707     /// For instance, you cannot [`Read`] into an uninitialized buffer:
708     ///
709     /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
710     ///
711     /// ```rust,no_run
712     /// #![feature(maybe_uninit_ref)]
713     /// use std::{io, mem::MaybeUninit};
714     ///
715     /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
716     /// {
717     ///     let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
718     ///     reader.read_exact(unsafe { buffer.assume_init_mut() })?;
719     ///                             // ^^^^^^^^^^^^^^^^^^^^^^^^
720     ///                             // (mutable) reference to uninitialized memory!
721     ///                             // This is undefined behavior.
722     ///     Ok(unsafe { buffer.assume_init() })
723     /// }
724     /// ```
725     ///
726     /// Nor can you use direct field access to do field-by-field gradual initialization:
727     ///
728     /// ```rust,no_run
729     /// #![feature(maybe_uninit_ref)]
730     /// use std::{mem::MaybeUninit, ptr};
731     ///
732     /// struct Foo {
733     ///     a: u32,
734     ///     b: u8,
735     /// }
736     ///
737     /// let foo: Foo = unsafe {
738     ///     let mut foo = MaybeUninit::<Foo>::uninit();
739     ///     ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
740     ///                  // ^^^^^^^^^^^^^^^^^^^^^
741     ///                  // (mutable) reference to uninitialized memory!
742     ///                  // This is undefined behavior.
743     ///     ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
744     ///                  // ^^^^^^^^^^^^^^^^^^^^^
745     ///                  // (mutable) reference to uninitialized memory!
746     ///                  // This is undefined behavior.
747     ///     foo.assume_init()
748     /// };
749     /// ```
750     // FIXME(#76092): We currently rely on the above being incorrect, i.e., we have references
751     // to uninitialized data (e.g., in `libcore/fmt/float.rs`).  We should make
752     // a final decision about the rules before stabilization.
753     #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
754     #[inline(always)]
755     pub unsafe fn assume_init_mut(&mut self) -> &mut T {
756         // SAFETY: the caller must guarantee that `self` is initialized.
757         // This also means that `self` must be a `value` variant.
758         unsafe {
759             intrinsics::assert_inhabited::<T>();
760             &mut *self.value
761         }
762     }
763
764     /// Assuming all the elements are initialized, get a slice to them.
765     ///
766     /// # Safety
767     ///
768     /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
769     /// really are in an initialized state.
770     /// Calling this when the content is not yet fully initialized causes undefined behavior.
771     ///
772     /// See [`assume_init_ref`] for more details and examples.
773     ///
774     /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
775     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
776     #[inline(always)]
777     pub unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
778         // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
779         // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
780         // The pointer obtained is valid since it refers to memory owned by `slice` which is a
781         // reference and thus guaranteed to be valid for reads.
782         unsafe { &*(slice as *const [Self] as *const [T]) }
783     }
784
785     /// Assuming all the elements are initialized, get a mutable slice to them.
786     ///
787     /// # Safety
788     ///
789     /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
790     /// really are in an initialized state.
791     /// Calling this when the content is not yet fully initialized causes undefined behavior.
792     ///
793     /// See [`assume_init_mut`] for more details and examples.
794     ///
795     /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
796     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
797     #[inline(always)]
798     pub unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
799         // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
800         // mutable reference which is also guaranteed to be valid for writes.
801         unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
802     }
803
804     /// Gets a pointer to the first element of the array.
805     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
806     #[inline(always)]
807     pub fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
808         this as *const [MaybeUninit<T>] as *const T
809     }
810
811     /// Gets a mutable pointer to the first element of the array.
812     #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
813     #[inline(always)]
814     pub fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
815         this as *mut [MaybeUninit<T>] as *mut T
816     }
817 }