1 use crate::any::type_name;
4 use crate::mem::ManuallyDrop;
6 /// A wrapper type to construct uninitialized instances of `T`.
8 /// # Initialization invariant
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:
18 /// # #![allow(invalid_value)]
19 /// use std::mem::{self, MaybeUninit};
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! ⚠️
26 /// This is exploited by the compiler for various optimizations, such as eliding
27 /// run-time checks and optimizing `enum` layout.
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:
33 /// # #![allow(invalid_value)]
34 /// use std::mem::{self, MaybeUninit};
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! ⚠️
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:
47 /// # #![allow(invalid_value)]
48 /// use std::mem::{self, MaybeUninit};
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! ⚠️
54 /// (Notice that the rules around uninitialized integers are not finalized yet, but
55 /// until they are, it is advisable to avoid them.)
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).
65 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
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*
74 /// use std::mem::MaybeUninit;
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() };
86 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
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.
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.
100 /// use std::mem::MaybeUninit;
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]);
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]);
115 /// ## Initializing an array element-by-element
117 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
120 /// use std::mem::{self, MaybeUninit};
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()
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
135 /// for elem in &mut data[..] {
136 /// *elem = MaybeUninit::new(vec![42]);
139 /// // Everything is initialized. Transmute the array to the
140 /// // initialized type.
141 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
144 /// assert_eq!(&data[0], &[42]);
147 /// You can also work with partially initialized arrays, which could
148 /// be found in low-level datastructures.
151 /// use std::mem::MaybeUninit;
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;
161 /// for elem in &mut data[0..500] {
162 /// *elem = MaybeUninit::new(String::from("hello"));
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()); }
172 /// ## Initializing a struct field-by-field
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
179 /// [ub]: ../../reference/behavior-considered-undefined.html
183 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
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>());
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:
198 /// # use std::mem::{MaybeUninit, size_of};
199 /// assert_eq!(size_of::<Option<bool>>(), 1);
200 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
203 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
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"]
220 pub union MaybeUninit<T> {
222 value: ManuallyDrop<T>,
225 #[stable(feature = "maybe_uninit", since = "1.36.0")]
226 impl<T: Copy> Clone for MaybeUninit<T> {
228 fn clone(&self) -> Self {
229 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
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>())
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.
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.
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")]
252 pub const fn new(val: T) -> MaybeUninit<T> {
253 MaybeUninit { value: ManuallyDrop::new(val) }
256 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
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.
261 /// See the [type-level documentation][type] for some examples.
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")]
267 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
268 pub const fn uninit() -> MaybeUninit<T> {
269 MaybeUninit { uninit: () }
272 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
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];`.
282 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
284 /// use std::mem::MaybeUninit;
287 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
290 /// /// Returns a (possibly smaller) slice of data that was actually read
291 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
293 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
294 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
298 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
299 /// let data = read(&mut buf);
301 #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
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() }
308 /// A promotable constant, equivalent to `uninit()`.
310 feature = "internal_uninit_const",
312 reason = "hack to work around promotability"
314 pub const UNINIT: Self = Self::uninit();
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
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.
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.
331 /// use std::mem::MaybeUninit;
333 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
334 /// let x = unsafe { x.assume_init() };
335 /// assert_eq!(x, (0, false));
338 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
339 /// when `0` is not a valid bit-pattern for the type:
342 /// use std::mem::MaybeUninit;
344 /// enum NotZero { One = 1, Two = 2 };
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. ⚠️
351 #[stable(feature = "maybe_uninit", since = "1.36.0")]
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.
358 u.as_mut_ptr().write_bytes(0u8, 1);
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")]
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() }
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>`).
382 /// Correct usage of this method:
385 /// use std::mem::MaybeUninit;
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);
394 /// *Incorrect* usage of this method:
397 /// use std::mem::MaybeUninit;
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. ⚠️
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")]
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
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.
419 /// Correct usage of this method:
422 /// use std::mem::MaybeUninit;
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() };
430 /// assert_eq!(x_vec.len(), 4);
433 /// *Incorrect* usage of this method:
436 /// use std::mem::MaybeUninit;
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. ⚠️
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")]
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
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.
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.
464 /// [inv]: #initialization-invariant
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).
476 /// Correct usage of this method:
479 /// use std::mem::MaybeUninit;
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);
487 /// *Incorrect* usage of this method:
490 /// use std::mem::MaybeUninit;
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. ⚠️
496 #[stable(feature = "maybe_uninit", since = "1.36.0")]
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.
503 intrinsics::assert_inhabited::<T>();
504 ManuallyDrop::into_inner(self.value)
508 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
509 /// to the usual drop handling.
511 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
512 /// prevents duplicating the content of the `MaybeUninit<T>`.
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.
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.
526 /// [inv]: #initialization-invariant
527 /// [`assume_init`]: MaybeUninit::assume_init
531 /// Correct usage of this method:
534 /// #![feature(maybe_uninit_extra)]
535 /// use std::mem::MaybeUninit;
537 /// let mut x = MaybeUninit::<u32>::uninit();
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);
544 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
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);
552 /// *Incorrect* usage of this method:
555 /// #![feature(maybe_uninit_extra)]
556 /// use std::mem::MaybeUninit;
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!
565 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
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.
571 intrinsics::assert_inhabited::<T>();
576 /// Gets a shared reference to the contained value.
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()`).
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.
590 /// ### Correct usage of this method:
593 /// #![feature(maybe_uninit_ref)]
594 /// use std::mem::MaybeUninit;
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()
605 /// assert_eq!(x, &vec![1, 2, 3]);
608 /// ### *Incorrect* usages of this method:
611 /// #![feature(maybe_uninit_ref)]
612 /// use std::mem::MaybeUninit;
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. ⚠️
620 /// #![feature(maybe_uninit_ref)]
621 /// use std::{cell::Cell, mem::MaybeUninit};
623 /// let b = MaybeUninit::<Cell<bool>>::uninit();
624 /// // Initialize the `MaybeUninit` using `Cell::set`:
626 /// b.assume_init_ref().set(true);
627 /// // ^^^^^^^^^^^^^^^
628 /// // Reference to an uninitialized `Cell<bool>`: UB!
631 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
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.
637 intrinsics::assert_inhabited::<T>();
642 /// Gets a mutable (unique) reference to the contained value.
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()`).
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`.
657 /// ### Correct usage of this method:
660 /// #![feature(maybe_uninit_ref)]
661 /// use std::mem::MaybeUninit;
663 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 2048]) { *buf = [0; 2048] }
666 /// /// Initializes *all* the bytes of the input buffer.
667 /// fn initialize_buffer(buf: *mut [u8; 2048]);
670 /// let mut buf = MaybeUninit::<[u8; 2048]>::uninit();
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()
683 /// // Now we can use `buf` as a normal slice:
684 /// buf.sort_unstable();
686 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
687 /// "buffer is sorted",
691 /// ### *Incorrect* usages of this method:
693 /// You cannot use `.assume_init_mut()` to initialize a value:
696 /// #![feature(maybe_uninit_ref)]
697 /// use std::mem::MaybeUninit;
699 /// let mut b = MaybeUninit::<bool>::uninit();
701 /// *b.assume_init_mut() = true;
702 /// // We have created a (mutable) reference to an uninitialized `bool`!
703 /// // This is undefined behavior. ⚠️
707 /// For instance, you cannot [`Read`] into an uninitialized buffer:
709 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
712 /// #![feature(maybe_uninit_ref)]
713 /// use std::{io, mem::MaybeUninit};
715 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
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() })
726 /// Nor can you use direct field access to do field-by-field gradual initialization:
729 /// #![feature(maybe_uninit_ref)]
730 /// use std::{mem::MaybeUninit, ptr};
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()
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")]
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.
759 intrinsics::assert_inhabited::<T>();
764 /// Assuming all the elements are initialized, get a slice to them.
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.
772 /// See [`assume_init_ref`] for more details and examples.
774 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
775 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
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]) }
785 /// Assuming all the elements are initialized, get a mutable slice to them.
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.
793 /// See [`assume_init_mut`] for more details and examples.
795 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
796 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
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]) }
804 /// Gets a pointer to the first element of the array.
805 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
807 pub fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
808 this as *const [MaybeUninit<T>] as *const T
811 /// Gets a mutable pointer to the first element of the array.
812 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
814 pub fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
815 this as *mut [MaybeUninit<T>] as *mut T