1 use crate::any::type_name;
4 use crate::mem::ManuallyDrop;
6 // ignore-tidy-undocumented-unsafe
8 /// A wrapper type to construct uninitialized instances of `T`.
10 /// # Initialization invariant
12 /// The compiler, in general, assumes that a variable is properly initialized
13 /// according to the requirements of the variable's type. For example, a variable of
14 /// reference type must be aligned and non-NULL. This is an invariant that must
15 /// *always* be upheld, even in unsafe code. As a consequence, zero-initializing a
16 /// variable of reference type causes instantaneous [undefined behavior][ub],
17 /// no matter whether that reference ever gets used to access memory:
20 /// # #![allow(invalid_value)]
21 /// use std::mem::{self, MaybeUninit};
23 /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior! ⚠️
24 /// // The equivalent code with `MaybeUninit<&i32>`:
25 /// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! ⚠️
28 /// This is exploited by the compiler for various optimizations, such as eliding
29 /// run-time checks and optimizing `enum` layout.
31 /// Similarly, entirely uninitialized memory may have any content, while a `bool` must
32 /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior:
35 /// # #![allow(invalid_value)]
36 /// use std::mem::{self, MaybeUninit};
38 /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
39 /// // The equivalent code with `MaybeUninit<bool>`:
40 /// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
43 /// Moreover, uninitialized memory is special in that the compiler knows that
44 /// it does not have a fixed value. This makes it undefined behavior to have
45 /// uninitialized data in a variable even if that variable has an integer type,
46 /// which otherwise can hold any *fixed* bit pattern:
49 /// # #![allow(invalid_value)]
50 /// use std::mem::{self, MaybeUninit};
52 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
53 /// // The equivalent code with `MaybeUninit<i32>`:
54 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
56 /// (Notice that the rules around uninitialized integers are not finalized yet, but
57 /// until they are, it is advisable to avoid them.)
59 /// On top of that, remember that most types have additional invariants beyond merely
60 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
61 /// is considered initialized (under the current implementation; this does not constitute
62 /// a stable guarantee) because the only requirement the compiler knows about it
63 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
64 /// *immediate* undefined behavior, but will cause undefined behavior with most
65 /// safe operations (including dropping it).
67 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
71 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
72 /// It is a signal to the compiler indicating that the data here might *not*
76 /// use std::mem::MaybeUninit;
78 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
79 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
80 /// let mut x = MaybeUninit::<&i32>::uninit();
81 /// // Set it to a valid value.
82 /// unsafe { x.as_mut_ptr().write(&0); }
83 /// // Extract the initialized data -- this is only allowed *after* properly
84 /// // initializing `x`!
85 /// let x = unsafe { x.assume_init() };
88 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
90 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without
91 /// any of the run-time tracking and without any of the safety checks.
95 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
96 /// from a function, pass it a pointer to some (uninitialized) memory to put the
97 /// result into. This can be useful when it is important for the caller to control
98 /// how the memory the result is stored in gets allocated, and you want to avoid
99 /// unnecessary moves.
102 /// use std::mem::MaybeUninit;
104 /// unsafe fn make_vec(out: *mut Vec<i32>) {
105 /// // `write` does not drop the old contents, which is important.
106 /// out.write(vec![1, 2, 3]);
109 /// let mut v = MaybeUninit::uninit();
110 /// unsafe { make_vec(v.as_mut_ptr()); }
111 /// // Now we know `v` is initialized! This also makes sure the vector gets
112 /// // properly dropped.
113 /// let v = unsafe { v.assume_init() };
114 /// assert_eq!(&v, &[1, 2, 3]);
117 /// ## Initializing an array element-by-element
119 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
122 /// use std::mem::{self, MaybeUninit};
125 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
126 /// // safe because the type we are claiming to have initialized here is a
127 /// // bunch of `MaybeUninit`s, which do not require initialization.
128 /// let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
129 /// MaybeUninit::uninit().assume_init()
132 /// // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
133 /// // assignment instead of `ptr::write` does not cause the old
134 /// // uninitialized value to be dropped. Also if there is a panic during
135 /// // this loop, we have a memory leak, but there is no memory safety
137 /// for elem in &mut data[..] {
138 /// *elem = MaybeUninit::new(vec![42]);
141 /// // Everything is initialized. Transmute the array to the
142 /// // initialized type.
143 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
146 /// assert_eq!(&data[0], &[42]);
149 /// You can also work with partially initialized arrays, which could
150 /// be found in low-level datastructures.
153 /// use std::mem::MaybeUninit;
156 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
157 /// // safe because the type we are claiming to have initialized here is a
158 /// // bunch of `MaybeUninit`s, which do not require initialization.
159 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
160 /// // Count the number of elements we have assigned.
161 /// let mut data_len: usize = 0;
163 /// for elem in &mut data[0..500] {
164 /// *elem = MaybeUninit::new(String::from("hello"));
168 /// // For each item in the array, drop if we allocated it.
169 /// for elem in &mut data[0..data_len] {
170 /// unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
174 /// ## Initializing a struct field-by-field
176 /// There is currently no supported way to create a raw pointer or reference
177 /// to a field of a struct inside `MaybeUninit<Struct>`. That means it is not possible
178 /// to create a struct by calling `MaybeUninit::uninit::<Struct>()` and then writing
181 /// [ub]: ../../reference/behavior-considered-undefined.html
185 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
188 /// use std::mem::{MaybeUninit, size_of, align_of};
189 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
190 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
193 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
194 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
195 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
196 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
197 /// optimizations, potentially resulting in a larger size:
200 /// # use std::mem::{MaybeUninit, size_of};
201 /// assert_eq!(size_of::<Option<bool>>(), 1);
202 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
205 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
207 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
208 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
209 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
210 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
211 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
212 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
213 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
214 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
215 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
216 /// guarantee may evolve.
217 #[stable(feature = "maybe_uninit", since = "1.36.0")]
218 // Lang item so we can wrap other types in it. This is useful for generators.
219 #[lang = "maybe_uninit"]
222 pub union MaybeUninit<T> {
224 value: ManuallyDrop<T>,
227 #[stable(feature = "maybe_uninit", since = "1.36.0")]
228 impl<T: Copy> Clone for MaybeUninit<T> {
230 fn clone(&self) -> Self {
231 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
236 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
237 impl<T> fmt::Debug for MaybeUninit<T> {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 f.pad(type_name::<Self>())
243 impl<T> MaybeUninit<T> {
244 /// Creates a new `MaybeUninit<T>` initialized with the given value.
245 /// It is safe to call [`assume_init`] on the return value of this function.
247 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
248 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
250 /// [`assume_init`]: #method.assume_init
251 #[stable(feature = "maybe_uninit", since = "1.36.0")]
252 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
254 pub const fn new(val: T) -> MaybeUninit<T> {
255 MaybeUninit { value: ManuallyDrop::new(val) }
258 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
260 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
261 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
263 /// See the [type-level documentation][type] for some examples.
265 /// [type]: union.MaybeUninit.html
266 #[stable(feature = "maybe_uninit", since = "1.36.0")]
267 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
269 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
270 pub const fn uninit() -> MaybeUninit<T> {
271 MaybeUninit { uninit: () }
274 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
276 /// Note: in a future Rust version this method may become unnecessary
277 /// when array literal syntax allows
278 /// [repeating const expressions](https://github.com/rust-lang/rust/issues/49147).
279 /// The example below could then use `let mut buf = [MaybeUninit::<u8>::uninit(); 32];`.
284 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice_assume_init)]
286 /// use std::mem::MaybeUninit;
289 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
292 /// /// Returns a (possibly smaller) slice of data that was actually read
293 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
295 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
296 /// MaybeUninit::slice_get_ref(&buf[..len])
300 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
301 /// let data = read(&mut buf);
303 #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
305 pub fn uninit_array<const LEN: usize>() -> [Self; LEN] {
306 unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
309 /// A promotable constant, equivalent to `uninit()`.
311 feature = "internal_uninit_const",
313 reason = "hack to work around promotability"
315 pub const UNINIT: Self = Self::uninit();
317 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
318 /// filled with `0` bytes. It depends on `T` whether that already makes for
319 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
320 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
323 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
324 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
328 /// Correct usage of this function: initializing a struct with zero, where all
329 /// fields of the struct can hold the bit-pattern 0 as a valid value.
332 /// use std::mem::MaybeUninit;
334 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
335 /// let x = unsafe { x.assume_init() };
336 /// assert_eq!(x, (0, false));
339 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
340 /// when `0` is not a valid bit-pattern for the type:
343 /// use std::mem::MaybeUninit;
345 /// enum NotZero { One = 1, Two = 2 };
347 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
348 /// let x = unsafe { x.assume_init() };
349 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
350 /// // This is undefined behavior. ⚠️
352 #[stable(feature = "maybe_uninit", since = "1.36.0")]
354 #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
355 pub fn zeroed() -> MaybeUninit<T> {
356 let mut u = MaybeUninit::<T>::uninit();
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 {
371 self.value = ManuallyDrop::new(val);
376 /// Gets a pointer to the contained value. Reading from this pointer or turning it
377 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
378 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
379 /// (except inside an `UnsafeCell<T>`).
383 /// Correct usage of this method:
386 /// use std::mem::MaybeUninit;
388 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
389 /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
390 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
391 /// let x_vec = unsafe { &*x.as_ptr() };
392 /// assert_eq!(x_vec.len(), 3);
395 /// *Incorrect* usage of this method:
398 /// use std::mem::MaybeUninit;
400 /// let x = MaybeUninit::<Vec<u32>>::uninit();
401 /// let x_vec = unsafe { &*x.as_ptr() };
402 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
405 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
406 /// until they are, it is advisable to avoid them.)
407 #[stable(feature = "maybe_uninit", since = "1.36.0")]
409 pub fn as_ptr(&self) -> *const T {
410 unsafe { &*self.value as *const T }
413 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
414 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
418 /// Correct usage of this method:
421 /// use std::mem::MaybeUninit;
423 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
424 /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
425 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
426 /// // This is okay because we initialized it.
427 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
429 /// assert_eq!(x_vec.len(), 4);
432 /// *Incorrect* usage of this method:
435 /// use std::mem::MaybeUninit;
437 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
438 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
439 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
442 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
443 /// until they are, it is advisable to avoid them.)
444 #[stable(feature = "maybe_uninit", since = "1.36.0")]
446 pub fn as_mut_ptr(&mut self) -> *mut T {
447 unsafe { &mut *self.value as *mut T }
450 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
451 /// to ensure that the data will get dropped, because the resulting `T` is
452 /// subject to the usual drop handling.
456 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
457 /// state. Calling this when the content is not yet fully initialized causes immediate undefined
458 /// behavior. The [type-level documentation][inv] contains more information about
459 /// this initialization invariant.
461 /// [inv]: #initialization-invariant
463 /// On top of that, remember that most types have additional invariants beyond merely
464 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
465 /// is considered initialized (under the current implementation; this does not constitute
466 /// a stable guarantee) because the only requirement the compiler knows about it
467 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
468 /// *immediate* undefined behavior, but will cause undefined behavior with most
469 /// safe operations (including dropping it).
473 /// Correct usage of this method:
476 /// use std::mem::MaybeUninit;
478 /// let mut x = MaybeUninit::<bool>::uninit();
479 /// unsafe { x.as_mut_ptr().write(true); }
480 /// let x_init = unsafe { x.assume_init() };
481 /// assert_eq!(x_init, true);
484 /// *Incorrect* usage of this method:
487 /// use std::mem::MaybeUninit;
489 /// let x = MaybeUninit::<Vec<u32>>::uninit();
490 /// let x_init = unsafe { x.assume_init() };
491 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
493 #[stable(feature = "maybe_uninit", since = "1.36.0")]
495 #[rustc_diagnostic_item = "assume_init"]
496 pub unsafe fn assume_init(self) -> T {
497 // SAFETY: the caller must guarantee that `self` is initialized.
498 // This also means that `self` must be a `value` variant.
500 intrinsics::assert_inhabited::<T>();
501 ManuallyDrop::into_inner(self.value)
505 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
506 /// to the usual drop handling.
508 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
509 /// prevents duplicating the content of the `MaybeUninit<T>`.
513 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
514 /// state. Calling this when the content is not yet fully initialized causes undefined
515 /// behavior. The [type-level documentation][inv] contains more information about
516 /// this initialization invariant.
518 /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit<T>`. When using
519 /// multiple copies of the data (by calling `read` multiple times, or first
520 /// calling `read` and then [`assume_init`]), it is your responsibility
521 /// to ensure that that data may indeed be duplicated.
523 /// [inv]: #initialization-invariant
524 /// [`assume_init`]: #method.assume_init
528 /// Correct usage of this method:
531 /// #![feature(maybe_uninit_extra)]
532 /// use std::mem::MaybeUninit;
534 /// let mut x = MaybeUninit::<u32>::uninit();
536 /// let x1 = unsafe { x.read() };
537 /// // `u32` is `Copy`, so we may read multiple times.
538 /// let x2 = unsafe { x.read() };
539 /// assert_eq!(x1, x2);
541 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
543 /// let x1 = unsafe { x.read() };
544 /// // Duplicating a `None` value is okay, so we may read multiple times.
545 /// let x2 = unsafe { x.read() };
546 /// assert_eq!(x1, x2);
549 /// *Incorrect* usage of this method:
552 /// #![feature(maybe_uninit_extra)]
553 /// use std::mem::MaybeUninit;
555 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
556 /// x.write(Some(vec![0,1,2]));
557 /// let x1 = unsafe { x.read() };
558 /// let x2 = unsafe { x.read() };
559 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
560 /// // they both get dropped!
562 #[unstable(feature = "maybe_uninit_extra", issue = "63567")]
564 pub unsafe fn read(&self) -> T {
565 // SAFETY: the caller must guarantee that `self` is initialized.
566 // Reading from `self.as_ptr()` is safe since `self` should be initialized.
568 intrinsics::assert_inhabited::<T>();
573 /// Gets a shared reference to the contained value.
575 /// This can be useful when we want to access a `MaybeUninit` that has been
576 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
577 /// of `.assume_init()`).
581 /// Calling this when the content is not yet fully initialized causes undefined
582 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
583 /// is in an initialized state.
587 /// ### Correct usage of this method:
590 /// #![feature(maybe_uninit_ref)]
591 /// use std::mem::MaybeUninit;
593 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
594 /// // Initialize `x`:
595 /// unsafe { x.as_mut_ptr().write(vec![1, 2, 3]); }
596 /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
597 /// // create a shared reference to it:
598 /// let x: &Vec<u32> = unsafe {
599 /// // Safety: `x` has been initialized.
602 /// assert_eq!(x, &vec![1, 2, 3]);
605 /// ### *Incorrect* usages of this method:
608 /// #![feature(maybe_uninit_ref)]
609 /// use std::mem::MaybeUninit;
611 /// let x = MaybeUninit::<Vec<u32>>::uninit();
612 /// let x_vec: &Vec<u32> = unsafe { x.get_ref() };
613 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
617 /// #![feature(maybe_uninit_ref)]
618 /// use std::{cell::Cell, mem::MaybeUninit};
620 /// let b = MaybeUninit::<Cell<bool>>::uninit();
621 /// // Initialize the `MaybeUninit` using `Cell::set`:
623 /// b.get_ref().set(true);
625 /// // Reference to an uninitialized `Cell<bool>`: UB!
628 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
630 pub unsafe fn get_ref(&self) -> &T {
631 // SAFETY: the caller must guarantee that `self` is initialized.
632 // This also means that `self` must be a `value` variant.
634 intrinsics::assert_inhabited::<T>();
639 /// Gets a mutable (unique) reference to the contained value.
641 /// This can be useful when we want to access a `MaybeUninit` that has been
642 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
643 /// of `.assume_init()`).
647 /// Calling this when the content is not yet fully initialized causes undefined
648 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
649 /// is in an initialized state. For instance, `.get_mut()` cannot be used to
650 /// initialize a `MaybeUninit`.
654 /// ### Correct usage of this method:
657 /// #![feature(maybe_uninit_ref)]
658 /// use std::mem::MaybeUninit;
660 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 2048]) { *buf = [0; 2048] }
663 /// /// Initializes *all* the bytes of the input buffer.
664 /// fn initialize_buffer(buf: *mut [u8; 2048]);
667 /// let mut buf = MaybeUninit::<[u8; 2048]>::uninit();
669 /// // Initialize `buf`:
670 /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
671 /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
672 /// // However, using `.assume_init()` may trigger a `memcpy` of the 2048 bytes.
673 /// // To assert our buffer has been initialized without copying it, we upgrade
674 /// // the `&mut MaybeUninit<[u8; 2048]>` to a `&mut [u8; 2048]`:
675 /// let buf: &mut [u8; 2048] = unsafe {
676 /// // Safety: `buf` has been initialized.
680 /// // Now we can use `buf` as a normal slice:
681 /// buf.sort_unstable();
683 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
684 /// "buffer is sorted",
688 /// ### *Incorrect* usages of this method:
690 /// You cannot use `.get_mut()` to initialize a value:
693 /// #![feature(maybe_uninit_ref)]
694 /// use std::mem::MaybeUninit;
696 /// let mut b = MaybeUninit::<bool>::uninit();
698 /// *b.get_mut() = true;
699 /// // We have created a (mutable) reference to an uninitialized `bool`!
700 /// // This is undefined behavior. ⚠️
704 /// For instance, you cannot [`Read`] into an uninitialized buffer:
706 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
709 /// #![feature(maybe_uninit_ref)]
710 /// use std::{io, mem::MaybeUninit};
712 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
714 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
715 /// reader.read_exact(unsafe { buffer.get_mut() })?;
716 /// // ^^^^^^^^^^^^^^^^
717 /// // (mutable) reference to uninitialized memory!
718 /// // This is undefined behavior.
719 /// Ok(unsafe { buffer.assume_init() })
723 /// Nor can you use direct field access to do field-by-field gradual initialization:
726 /// #![feature(maybe_uninit_ref)]
727 /// use std::{mem::MaybeUninit, ptr};
734 /// let foo: Foo = unsafe {
735 /// let mut foo = MaybeUninit::<Foo>::uninit();
736 /// ptr::write(&mut foo.get_mut().a as *mut u32, 1337);
738 /// // (mutable) reference to uninitialized memory!
739 /// // This is undefined behavior.
740 /// ptr::write(&mut foo.get_mut().b as *mut u8, 42);
742 /// // (mutable) reference to uninitialized memory!
743 /// // This is undefined behavior.
744 /// foo.assume_init()
747 // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references
748 // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make
749 // a final decision about the rules before stabilization.
750 #[unstable(feature = "maybe_uninit_ref", issue = "63568")]
752 pub unsafe fn get_mut(&mut self) -> &mut T {
753 // SAFETY: the caller must guarantee that `self` is initialized.
754 // This also means that `self` must be a `value` variant.
756 intrinsics::assert_inhabited::<T>();
761 /// Assuming all the elements are initialized, get a slice to them.
765 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
766 /// really are in an initialized state.
767 /// Calling this when the content is not yet fully initialized causes undefined behavior.
768 #[unstable(feature = "maybe_uninit_slice_assume_init", issue = "none")]
770 pub unsafe fn slice_get_ref(slice: &[Self]) -> &[T] {
771 // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that
772 // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`.
773 // The pointer obtained is valid since it refers to memory owned by `slice` which is a
774 // reference and thus guaranteed to be valid for reads.
775 unsafe { &*(slice as *const [Self] as *const [T]) }
778 /// Assuming all the elements are initialized, get a mutable slice to them.
782 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
783 /// really are in an initialized state.
784 /// Calling this when the content is not yet fully initialized causes undefined behavior.
785 #[unstable(feature = "maybe_uninit_slice_assume_init", issue = "none")]
787 pub unsafe fn slice_get_mut(slice: &mut [Self]) -> &mut [T] {
788 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
789 // mutable reference which is also guaranteed to be valid for writes.
790 unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
793 /// Gets a pointer to the first element of the array.
794 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
796 pub fn first_ptr(this: &[MaybeUninit<T>]) -> *const T {
797 this as *const [MaybeUninit<T>] as *const T
800 /// Gets a mutable pointer to the first element of the array.
801 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
803 pub fn first_ptr_mut(this: &mut [MaybeUninit<T>]) -> *mut T {
804 this as *mut [MaybeUninit<T>] as *mut T