1 use crate::any::type_name;
4 use crate::mem::ManuallyDrop;
7 /// A wrapper type to construct uninitialized instances of `T`.
9 /// # Initialization invariant
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:
19 /// # #![allow(invalid_value)]
20 /// use std::mem::{self, MaybeUninit};
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! ⚠️
27 /// This is exploited by the compiler for various optimizations, such as eliding
28 /// run-time checks and optimizing `enum` layout.
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:
34 /// # #![allow(invalid_value)]
35 /// use std::mem::{self, MaybeUninit};
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! ⚠️
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:
48 /// # #![allow(invalid_value)]
49 /// use std::mem::{self, MaybeUninit};
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! ⚠️
55 /// (Notice that the rules around uninitialized integers are not finalized yet, but
56 /// until they are, it is advisable to avoid them.)
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).
66 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
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*
75 /// use std::mem::MaybeUninit;
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() };
87 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
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.
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.
101 /// use std::mem::MaybeUninit;
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]);
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]);
116 /// ## Initializing an array element-by-element
118 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
121 /// use std::mem::{self, MaybeUninit};
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()
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
136 /// for elem in &mut data[..] {
137 /// *elem = MaybeUninit::new(vec![42]);
140 /// // Everything is initialized. Transmute the array to the
141 /// // initialized type.
142 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
145 /// assert_eq!(&data[0], &[42]);
148 /// You can also work with partially initialized arrays, which could
149 /// be found in low-level datastructures.
152 /// use std::mem::MaybeUninit;
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;
162 /// for elem in &mut data[0..500] {
163 /// *elem = MaybeUninit::new(String::from("hello"));
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()); }
173 /// ## Initializing a struct field-by-field
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
180 /// [ub]: ../../reference/behavior-considered-undefined.html
184 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
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>());
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:
199 /// # use std::mem::{MaybeUninit, size_of};
200 /// assert_eq!(size_of::<Option<bool>>(), 1);
201 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
204 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
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"]
221 pub union MaybeUninit<T> {
223 value: ManuallyDrop<T>,
226 #[stable(feature = "maybe_uninit", since = "1.36.0")]
227 impl<T: Copy> Clone for MaybeUninit<T> {
229 fn clone(&self) -> Self {
230 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
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>())
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.
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.
252 /// use std::mem::MaybeUninit;
254 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
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")]
261 pub const fn new(val: T) -> MaybeUninit<T> {
262 MaybeUninit { value: ManuallyDrop::new(val) }
265 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
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.
270 /// See the [type-level documentation][MaybeUninit] for some examples.
275 /// use std::mem::MaybeUninit;
277 /// let v: MaybeUninit<String> = MaybeUninit::uninit();
279 #[stable(feature = "maybe_uninit", since = "1.36.0")]
280 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
282 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
283 pub const fn uninit() -> MaybeUninit<T> {
284 MaybeUninit { uninit: () }
287 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
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];`.
297 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
299 /// use std::mem::MaybeUninit;
302 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
305 /// /// Returns a (possibly smaller) slice of data that was actually read
306 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
308 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
309 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
313 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
314 /// let data = read(&mut buf);
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)]
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() }
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
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.
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.
340 /// use std::mem::MaybeUninit;
342 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
343 /// let x = unsafe { x.assume_init() };
344 /// assert_eq!(x, (0, false));
347 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
348 /// when `0` is not a valid bit-pattern for the type:
351 /// use std::mem::MaybeUninit;
353 /// enum NotZero { One = 1, Two = 2 }
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. ⚠️
360 #[stable(feature = "maybe_uninit", since = "1.36.0")]
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.
367 u.as_mut_ptr().write_bytes(0u8, 1);
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")]
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() }
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>`).
391 /// Correct usage of this method:
394 /// use std::mem::MaybeUninit;
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);
403 /// *Incorrect* usage of this method:
406 /// use std::mem::MaybeUninit;
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. ⚠️
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")]
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
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.
428 /// Correct usage of this method:
431 /// use std::mem::MaybeUninit;
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() };
439 /// assert_eq!(x_vec.len(), 4);
442 /// *Incorrect* usage of this method:
445 /// use std::mem::MaybeUninit;
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. ⚠️
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")]
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
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.
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.
473 /// [inv]: #initialization-invariant
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).
483 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
487 /// Correct usage of this method:
490 /// use std::mem::MaybeUninit;
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);
498 /// *Incorrect* usage of this method:
501 /// use std::mem::MaybeUninit;
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. ⚠️
507 #[stable(feature = "maybe_uninit", since = "1.36.0")]
508 #[rustc_const_unstable(feature = "const_maybe_assume_init", issue = "none")]
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.
515 intrinsics::assert_inhabited::<T>();
516 ManuallyDrop::into_inner(self.value)
520 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
521 /// to the usual drop handling.
523 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
524 /// prevents duplicating the content of the `MaybeUninit<T>`.
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.
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.
538 /// [inv]: #initialization-invariant
539 /// [`assume_init`]: MaybeUninit::assume_init
543 /// Correct usage of this method:
546 /// #![feature(maybe_uninit_extra)]
547 /// use std::mem::MaybeUninit;
549 /// let mut x = MaybeUninit::<u32>::uninit();
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);
556 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
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);
564 /// *Incorrect* usage of this method:
567 /// #![feature(maybe_uninit_extra)]
568 /// use std::mem::MaybeUninit;
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!
577 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
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.
583 intrinsics::assert_inhabited::<T>();
588 /// Drops the contained value in place.
590 /// If you have ownership of the `MaybeUninit`, you can use [`assume_init`] instead.
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.
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.
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()) }
616 /// Gets a shared reference to the contained value.
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()`).
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.
630 /// ### Correct usage of this method:
633 /// #![feature(maybe_uninit_ref)]
634 /// use std::mem::MaybeUninit;
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()
645 /// assert_eq!(x, &vec![1, 2, 3]);
648 /// ### *Incorrect* usages of this method:
651 /// #![feature(maybe_uninit_ref)]
652 /// use std::mem::MaybeUninit;
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. ⚠️
660 /// #![feature(maybe_uninit_ref)]
661 /// use std::{cell::Cell, mem::MaybeUninit};
663 /// let b = MaybeUninit::<Cell<bool>>::uninit();
664 /// // Initialize the `MaybeUninit` using `Cell::set`:
666 /// b.assume_init_ref().set(true);
667 /// // ^^^^^^^^^^^^^^^
668 /// // Reference to an uninitialized `Cell<bool>`: UB!
671 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
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.
677 intrinsics::assert_inhabited::<T>();
682 /// Gets a mutable (unique) reference to the contained value.
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()`).
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`.
697 /// ### Correct usage of this method:
700 /// #![feature(maybe_uninit_ref)]
701 /// use std::mem::MaybeUninit;
703 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 2048]) { *buf = [0; 2048] }
706 /// /// Initializes *all* the bytes of the input buffer.
707 /// fn initialize_buffer(buf: *mut [u8; 2048]);
710 /// let mut buf = MaybeUninit::<[u8; 2048]>::uninit();
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()
723 /// // Now we can use `buf` as a normal slice:
724 /// buf.sort_unstable();
726 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
727 /// "buffer is sorted",
731 /// ### *Incorrect* usages of this method:
733 /// You cannot use `.assume_init_mut()` to initialize a value:
736 /// #![feature(maybe_uninit_ref)]
737 /// use std::mem::MaybeUninit;
739 /// let mut b = MaybeUninit::<bool>::uninit();
741 /// *b.assume_init_mut() = true;
742 /// // We have created a (mutable) reference to an uninitialized `bool`!
743 /// // This is undefined behavior. ⚠️
747 /// For instance, you cannot [`Read`] into an uninitialized buffer:
749 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
752 /// #![feature(maybe_uninit_ref)]
753 /// use std::{io, mem::MaybeUninit};
755 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
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() })
766 /// Nor can you use direct field access to do field-by-field gradual initialization:
769 /// #![feature(maybe_uninit_ref)]
770 /// use std::{mem::MaybeUninit, ptr};
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()
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")]
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.
799 intrinsics::assert_inhabited::<T>();
804 /// Assuming all the elements are initialized, get a slice to them.
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.
812 /// See [`assume_init_ref`] for more details and examples.
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")]
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]) }
826 /// Assuming all the elements are initialized, get a mutable slice to them.
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.
834 /// See [`assume_init_mut`] for more details and examples.
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")]
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]) }
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")]
850 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
851 this.as_ptr() as *const T
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")]
858 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
859 this.as_mut_ptr() as *mut T