1 use crate::any::type_name;
4 use crate::mem::{self, ManuallyDrop};
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 it does not have a fixed value ("fixed"
44 /// meaning "it won't change without being written to"). Reading the same uninitialized byte
45 /// multiple times can give different results. This makes it undefined behavior to have
46 /// uninitialized data in a variable even if that variable has an integer type, which otherwise can
47 /// hold any *fixed* bit pattern:
50 /// # #![allow(invalid_value)]
51 /// use std::mem::{self, MaybeUninit};
53 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
54 /// // The equivalent code with `MaybeUninit<i32>`:
55 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
57 /// (Notice that the rules around uninitialized integers are not finalized yet, but
58 /// until they are, it is advisable to avoid them.)
60 /// On top of that, remember that most types have additional invariants beyond merely
61 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
62 /// is considered initialized (under the current implementation; this does not constitute
63 /// a stable guarantee) because the only requirement the compiler knows about it
64 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
65 /// *immediate* undefined behavior, but will cause undefined behavior with most
66 /// safe operations (including dropping it).
68 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
72 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
73 /// It is a signal to the compiler indicating that the data here might *not*
77 /// use std::mem::MaybeUninit;
79 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
80 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
81 /// let mut x = MaybeUninit::<&i32>::uninit();
82 /// // Set it to a valid value.
84 /// // Extract the initialized data -- this is only allowed *after* properly
85 /// // initializing `x`!
86 /// let x = unsafe { x.assume_init() };
89 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
91 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without
92 /// any of the run-time tracking and without any of the safety checks.
96 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
97 /// from a function, pass it a pointer to some (uninitialized) memory to put the
98 /// result into. This can be useful when it is important for the caller to control
99 /// how the memory the result is stored in gets allocated, and you want to avoid
100 /// unnecessary moves.
103 /// use std::mem::MaybeUninit;
105 /// unsafe fn make_vec(out: *mut Vec<i32>) {
106 /// // `write` does not drop the old contents, which is important.
107 /// out.write(vec![1, 2, 3]);
110 /// let mut v = MaybeUninit::uninit();
111 /// unsafe { make_vec(v.as_mut_ptr()); }
112 /// // Now we know `v` is initialized! This also makes sure the vector gets
113 /// // properly dropped.
114 /// let v = unsafe { v.assume_init() };
115 /// assert_eq!(&v, &[1, 2, 3]);
118 /// ## Initializing an array element-by-element
120 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
123 /// use std::mem::{self, MaybeUninit};
126 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
127 /// // safe because the type we are claiming to have initialized here is a
128 /// // bunch of `MaybeUninit`s, which do not require initialization.
129 /// let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
130 /// MaybeUninit::uninit().assume_init()
133 /// // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
134 /// // assignment instead of `ptr::write` does not cause the old
135 /// // uninitialized value to be dropped. Also if there is a panic during
136 /// // this loop, we have a memory leak, but there is no memory safety
138 /// for elem in &mut data[..] {
139 /// elem.write(vec![42]);
142 /// // Everything is initialized. Transmute the array to the
143 /// // initialized type.
144 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
147 /// assert_eq!(&data[0], &[42]);
150 /// You can also work with partially initialized arrays, which could
151 /// be found in low-level datastructures.
154 /// use std::mem::MaybeUninit;
157 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
158 /// // safe because the type we are claiming to have initialized here is a
159 /// // bunch of `MaybeUninit`s, which do not require initialization.
160 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
161 /// // Count the number of elements we have assigned.
162 /// let mut data_len: usize = 0;
164 /// for elem in &mut data[0..500] {
165 /// elem.write(String::from("hello"));
169 /// // For each item in the array, drop if we allocated it.
170 /// for elem in &mut data[0..data_len] {
171 /// unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
175 /// ## Initializing a struct field-by-field
177 /// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field:
180 /// use std::mem::MaybeUninit;
181 /// use std::ptr::addr_of_mut;
183 /// #[derive(Debug, PartialEq)]
190 /// let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
191 /// let ptr = uninit.as_mut_ptr();
193 /// // Initializing the `name` field
194 /// // Using `write` instead of assignment via `=` to not call `drop` on the
195 /// // old, uninitialized value.
196 /// unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); }
198 /// // Initializing the `list` field
199 /// // If there is a panic here, then the `String` in the `name` field leaks.
200 /// unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); }
202 /// // All the fields are initialized, so we call `assume_init` to get an initialized Foo.
203 /// unsafe { uninit.assume_init() }
209 /// name: "Bob".to_string(),
210 /// list: vec![0, 1, 2]
214 /// [`std::ptr::addr_of_mut`]: crate::ptr::addr_of_mut
215 /// [ub]: ../../reference/behavior-considered-undefined.html
219 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
222 /// use std::mem::{MaybeUninit, size_of, align_of};
223 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
224 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
227 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
228 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
229 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
230 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
231 /// optimizations, potentially resulting in a larger size:
234 /// # use std::mem::{MaybeUninit, size_of};
235 /// assert_eq!(size_of::<Option<bool>>(), 1);
236 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
239 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
241 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size,
242 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and
243 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type
244 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`.
245 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the
246 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact
247 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not
248 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has
249 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that
250 /// guarantee may evolve.
251 #[stable(feature = "maybe_uninit", since = "1.36.0")]
252 // Lang item so we can wrap other types in it. This is useful for generators.
253 #[lang = "maybe_uninit"]
256 pub union MaybeUninit<T> {
258 value: ManuallyDrop<T>,
261 #[stable(feature = "maybe_uninit", since = "1.36.0")]
262 impl<T: Copy> Clone for MaybeUninit<T> {
264 fn clone(&self) -> Self {
265 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
270 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
271 impl<T> fmt::Debug for MaybeUninit<T> {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 f.pad(type_name::<Self>())
277 impl<T> MaybeUninit<T> {
278 /// Creates a new `MaybeUninit<T>` initialized with the given value.
279 /// It is safe to call [`assume_init`] on the return value of this function.
281 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
282 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
287 /// use std::mem::MaybeUninit;
289 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
292 /// [`assume_init`]: MaybeUninit::assume_init
293 #[stable(feature = "maybe_uninit", since = "1.36.0")]
294 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
295 #[must_use = "use `forget` to avoid running Drop code"]
297 pub const fn new(val: T) -> MaybeUninit<T> {
298 MaybeUninit { value: ManuallyDrop::new(val) }
301 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
303 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
304 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
306 /// See the [type-level documentation][MaybeUninit] for some examples.
311 /// use std::mem::MaybeUninit;
313 /// let v: MaybeUninit<String> = MaybeUninit::uninit();
315 #[stable(feature = "maybe_uninit", since = "1.36.0")]
316 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
319 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
320 pub const fn uninit() -> MaybeUninit<T> {
321 MaybeUninit { uninit: () }
324 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
326 /// Note: in a future Rust version this method may become unnecessary
328 /// [inline const expressions](https://github.com/rust-lang/rust/issues/76001).
329 /// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
334 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_slice)]
336 /// use std::mem::MaybeUninit;
339 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
342 /// /// Returns a (possibly smaller) slice of data that was actually read
343 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
345 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
346 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
350 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
351 /// let data = read(&mut buf);
353 #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
354 #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
357 pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
358 // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
359 unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
362 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
363 /// filled with `0` bytes. It depends on `T` whether that already makes for
364 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
365 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
368 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
369 /// It is your responsibility to make sure `T` gets dropped if it got initialized.
373 /// Correct usage of this function: initializing a struct with zero, where all
374 /// fields of the struct can hold the bit-pattern 0 as a valid value.
377 /// use std::mem::MaybeUninit;
379 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
380 /// let x = unsafe { x.assume_init() };
381 /// assert_eq!(x, (0, false));
384 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
385 /// when `0` is not a valid bit-pattern for the type:
388 /// use std::mem::MaybeUninit;
390 /// enum NotZero { One = 1, Two = 2 }
392 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
393 /// let x = unsafe { x.assume_init() };
394 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
395 /// // This is undefined behavior. ⚠️
397 #[stable(feature = "maybe_uninit", since = "1.36.0")]
398 #[rustc_const_unstable(feature = "const_maybe_uninit_zeroed", issue = "91850")]
401 #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
402 pub const fn zeroed() -> MaybeUninit<T> {
403 let mut u = MaybeUninit::<T>::uninit();
404 // SAFETY: `u.as_mut_ptr()` points to allocated memory.
406 u.as_mut_ptr().write_bytes(0u8, 1);
411 /// Sets the value of the `MaybeUninit<T>`.
413 /// This overwrites any previous value without dropping it, so be careful
414 /// not to use this twice unless you want to skip running the destructor.
415 /// For your convenience, this also returns a mutable reference to the
416 /// (now safely initialized) contents of `self`.
418 /// As the content is stored inside a `MaybeUninit`, the destructor is not
419 /// run for the inner data if the MaybeUninit leaves scope without a call to
420 /// [`assume_init`], [`assume_init_drop`], or similar. Code that receives
421 /// the mutable reference returned by this function needs to keep this in
422 /// mind. The safety model of Rust regards leaks as safe, but they are
423 /// usually still undesirable. This being said, the mutable reference
424 /// behaves like any other mutable reference would, so assigning a new value
425 /// to it will drop the old content.
427 /// [`assume_init`]: Self::assume_init
428 /// [`assume_init_drop`]: Self::assume_init_drop
432 /// Correct usage of this method:
435 /// use std::mem::MaybeUninit;
437 /// let mut x = MaybeUninit::<Vec<u8>>::uninit();
440 /// let hello = x.write((&b"Hello, world!").to_vec());
441 /// // Setting hello does not leak prior allocations, but drops them
442 /// *hello = (&b"Hello").to_vec();
443 /// hello[0] = 'h' as u8;
445 /// // x is initialized now:
446 /// let s = unsafe { x.assume_init() };
447 /// assert_eq!(b"hello", s.as_slice());
450 /// This usage of the method causes a leak:
453 /// use std::mem::MaybeUninit;
455 /// let mut x = MaybeUninit::<String>::uninit();
457 /// x.write("Hello".to_string());
458 /// // This leaks the contained string:
459 /// x.write("hello".to_string());
460 /// // x is initialized now:
461 /// let s = unsafe { x.assume_init() };
464 /// This method can be used to avoid unsafe in some cases. The example below
465 /// shows a part of an implementation of a fixed sized arena that lends out
466 /// pinned references.
467 /// With `write`, we can avoid the need to write through a raw pointer:
470 /// use core::pin::Pin;
471 /// use core::mem::MaybeUninit;
473 /// struct PinArena<T> {
474 /// memory: Box<[MaybeUninit<T>]>,
478 /// impl <T> PinArena<T> {
479 /// pub fn capacity(&self) -> usize {
480 /// self.memory.len()
482 /// pub fn push(&mut self, val: T) -> Pin<&mut T> {
483 /// if self.len >= self.capacity() {
484 /// panic!("Attempted to push to a full pin arena!");
486 /// let ref_ = self.memory[self.len].write(val);
488 /// unsafe { Pin::new_unchecked(ref_) }
492 #[stable(feature = "maybe_uninit_write", since = "1.55.0")]
493 #[rustc_const_unstable(feature = "const_maybe_uninit_write", issue = "63567")]
495 pub const fn write(&mut self, val: T) -> &mut T {
496 *self = MaybeUninit::new(val);
497 // SAFETY: We just initialized this value.
498 unsafe { self.assume_init_mut() }
501 /// Gets a pointer to the contained value. Reading from this pointer or turning it
502 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
503 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
504 /// (except inside an `UnsafeCell<T>`).
508 /// Correct usage of this method:
511 /// use std::mem::MaybeUninit;
513 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
514 /// x.write(vec![0, 1, 2]);
515 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
516 /// let x_vec = unsafe { &*x.as_ptr() };
517 /// assert_eq!(x_vec.len(), 3);
520 /// *Incorrect* usage of this method:
523 /// use std::mem::MaybeUninit;
525 /// let x = MaybeUninit::<Vec<u32>>::uninit();
526 /// let x_vec = unsafe { &*x.as_ptr() };
527 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
530 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
531 /// until they are, it is advisable to avoid them.)
532 #[stable(feature = "maybe_uninit", since = "1.36.0")]
533 #[rustc_const_stable(feature = "const_maybe_uninit_as_ptr", since = "1.59.0")]
535 pub const fn as_ptr(&self) -> *const T {
536 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
537 self as *const _ as *const T
540 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
541 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
545 /// Correct usage of this method:
548 /// use std::mem::MaybeUninit;
550 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
551 /// x.write(vec![0, 1, 2]);
552 /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
553 /// // This is okay because we initialized it.
554 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
556 /// assert_eq!(x_vec.len(), 4);
559 /// *Incorrect* usage of this method:
562 /// use std::mem::MaybeUninit;
564 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
565 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
566 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
569 /// (Notice that the rules around references to uninitialized data are not finalized yet, but
570 /// until they are, it is advisable to avoid them.)
571 #[stable(feature = "maybe_uninit", since = "1.36.0")]
572 #[rustc_const_unstable(feature = "const_maybe_uninit_as_mut_ptr", issue = "75251")]
574 pub const fn as_mut_ptr(&mut self) -> *mut T {
575 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer.
576 self as *mut _ as *mut T
579 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
580 /// to ensure that the data will get dropped, because the resulting `T` is
581 /// subject to the usual drop handling.
585 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
586 /// state. Calling this when the content is not yet fully initialized causes immediate undefined
587 /// behavior. The [type-level documentation][inv] contains more information about
588 /// this initialization invariant.
590 /// [inv]: #initialization-invariant
592 /// On top of that, remember that most types have additional invariants beyond merely
593 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
594 /// is considered initialized (under the current implementation; this does not constitute
595 /// a stable guarantee) because the only requirement the compiler knows about it
596 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
597 /// *immediate* undefined behavior, but will cause undefined behavior with most
598 /// safe operations (including dropping it).
600 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
604 /// Correct usage of this method:
607 /// use std::mem::MaybeUninit;
609 /// let mut x = MaybeUninit::<bool>::uninit();
611 /// let x_init = unsafe { x.assume_init() };
612 /// assert_eq!(x_init, true);
615 /// *Incorrect* usage of this method:
618 /// use std::mem::MaybeUninit;
620 /// let x = MaybeUninit::<Vec<u32>>::uninit();
621 /// let x_init = unsafe { x.assume_init() };
622 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
624 #[stable(feature = "maybe_uninit", since = "1.36.0")]
625 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init", since = "1.59.0")]
627 #[rustc_diagnostic_item = "assume_init"]
629 pub const unsafe fn assume_init(self) -> T {
630 // SAFETY: the caller must guarantee that `self` is initialized.
631 // This also means that `self` must be a `value` variant.
633 intrinsics::assert_inhabited::<T>();
634 ManuallyDrop::into_inner(self.value)
638 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
639 /// to the usual drop handling.
641 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
642 /// prevents duplicating the content of the `MaybeUninit<T>`.
646 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
647 /// state. Calling this when the content is not yet fully initialized causes undefined
648 /// behavior. The [type-level documentation][inv] contains more information about
649 /// this initialization invariant.
651 /// Moreover, similar to the [`ptr::read`] function, this function creates a
652 /// bitwise copy of the contents, regardless whether the contained type
653 /// implements the [`Copy`] trait or not. When using multiple copies of the
654 /// data (by calling `assume_init_read` multiple times, or first calling
655 /// `assume_init_read` and then [`assume_init`]), it is your responsibility
656 /// to ensure that that data may indeed be duplicated.
658 /// [inv]: #initialization-invariant
659 /// [`assume_init`]: MaybeUninit::assume_init
663 /// Correct usage of this method:
666 /// use std::mem::MaybeUninit;
668 /// let mut x = MaybeUninit::<u32>::uninit();
670 /// let x1 = unsafe { x.assume_init_read() };
671 /// // `u32` is `Copy`, so we may read multiple times.
672 /// let x2 = unsafe { x.assume_init_read() };
673 /// assert_eq!(x1, x2);
675 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
677 /// let x1 = unsafe { x.assume_init_read() };
678 /// // Duplicating a `None` value is okay, so we may read multiple times.
679 /// let x2 = unsafe { x.assume_init_read() };
680 /// assert_eq!(x1, x2);
683 /// *Incorrect* usage of this method:
686 /// use std::mem::MaybeUninit;
688 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
689 /// x.write(Some(vec![0, 1, 2]));
690 /// let x1 = unsafe { x.assume_init_read() };
691 /// let x2 = unsafe { x.assume_init_read() };
692 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
693 /// // they both get dropped!
695 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
696 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init_read", issue = "63567")]
699 pub const unsafe fn assume_init_read(&self) -> T {
700 // SAFETY: the caller must guarantee that `self` is initialized.
701 // Reading from `self.as_ptr()` is safe since `self` should be initialized.
703 intrinsics::assert_inhabited::<T>();
708 /// Drops the contained value in place.
710 /// If you have ownership of the `MaybeUninit`, you can also use
711 /// [`assume_init`] as an alternative.
715 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is
716 /// in an initialized state. Calling this when the content is not yet fully
717 /// initialized causes undefined behavior.
719 /// On top of that, all additional invariants of the type `T` must be
720 /// satisfied, as the `Drop` implementation of `T` (or its members) may
721 /// rely on this. For example, setting a [`Vec<T>`] to an invalid but
722 /// non-null address makes it initialized (under the current implementation;
723 /// this does not constitute a stable guarantee), because the only
724 /// requirement the compiler knows about it is that the data pointer must be
725 /// non-null. Dropping such a `Vec<T>` however will cause undefined
728 /// [`assume_init`]: MaybeUninit::assume_init
729 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
730 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
731 pub unsafe fn assume_init_drop(&mut self) {
732 // SAFETY: the caller must guarantee that `self` is initialized and
733 // satisfies all invariants of `T`.
734 // Dropping the value in place is safe if that is the case.
735 unsafe { ptr::drop_in_place(self.as_mut_ptr()) }
738 /// Gets a shared reference to the contained value.
740 /// This can be useful when we want to access a `MaybeUninit` that has been
741 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
742 /// of `.assume_init()`).
746 /// Calling this when the content is not yet fully initialized causes undefined
747 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
748 /// is in an initialized state.
752 /// ### Correct usage of this method:
755 /// use std::mem::MaybeUninit;
757 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
758 /// // Initialize `x`:
759 /// x.write(vec![1, 2, 3]);
760 /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
761 /// // create a shared reference to it:
762 /// let x: &Vec<u32> = unsafe {
763 /// // SAFETY: `x` has been initialized.
764 /// x.assume_init_ref()
766 /// assert_eq!(x, &vec![1, 2, 3]);
769 /// ### *Incorrect* usages of this method:
772 /// use std::mem::MaybeUninit;
774 /// let x = MaybeUninit::<Vec<u32>>::uninit();
775 /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
776 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
780 /// use std::{cell::Cell, mem::MaybeUninit};
782 /// let b = MaybeUninit::<Cell<bool>>::uninit();
783 /// // Initialize the `MaybeUninit` using `Cell::set`:
785 /// b.assume_init_ref().set(true);
786 /// // ^^^^^^^^^^^^^^^
787 /// // Reference to an uninitialized `Cell<bool>`: UB!
790 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
791 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init", since = "1.59.0")]
793 pub const unsafe fn assume_init_ref(&self) -> &T {
794 // SAFETY: the caller must guarantee that `self` is initialized.
795 // This also means that `self` must be a `value` variant.
797 intrinsics::assert_inhabited::<T>();
802 /// Gets a mutable (unique) reference to the contained value.
804 /// This can be useful when we want to access a `MaybeUninit` that has been
805 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use
806 /// of `.assume_init()`).
810 /// Calling this when the content is not yet fully initialized causes undefined
811 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really
812 /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
813 /// initialize a `MaybeUninit`.
817 /// ### Correct usage of this method:
820 /// # #![allow(unexpected_cfgs)]
821 /// use std::mem::MaybeUninit;
823 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] }
826 /// /// Initializes *all* the bytes of the input buffer.
827 /// fn initialize_buffer(buf: *mut [u8; 1024]);
830 /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
832 /// // Initialize `buf`:
833 /// unsafe { initialize_buffer(buf.as_mut_ptr()); }
834 /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it.
835 /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes.
836 /// // To assert our buffer has been initialized without copying it, we upgrade
837 /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`:
838 /// let buf: &mut [u8; 1024] = unsafe {
839 /// // SAFETY: `buf` has been initialized.
840 /// buf.assume_init_mut()
843 /// // Now we can use `buf` as a normal slice:
844 /// buf.sort_unstable();
846 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
847 /// "buffer is sorted",
851 /// ### *Incorrect* usages of this method:
853 /// You cannot use `.assume_init_mut()` to initialize a value:
856 /// use std::mem::MaybeUninit;
858 /// let mut b = MaybeUninit::<bool>::uninit();
860 /// *b.assume_init_mut() = true;
861 /// // We have created a (mutable) reference to an uninitialized `bool`!
862 /// // This is undefined behavior. ⚠️
866 /// For instance, you cannot [`Read`] into an uninitialized buffer:
868 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
871 /// use std::{io, mem::MaybeUninit};
873 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
875 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
876 /// reader.read_exact(unsafe { buffer.assume_init_mut() })?;
877 /// // ^^^^^^^^^^^^^^^^^^^^^^^^
878 /// // (mutable) reference to uninitialized memory!
879 /// // This is undefined behavior.
880 /// Ok(unsafe { buffer.assume_init() })
884 /// Nor can you use direct field access to do field-by-field gradual initialization:
887 /// use std::{mem::MaybeUninit, ptr};
894 /// let foo: Foo = unsafe {
895 /// let mut foo = MaybeUninit::<Foo>::uninit();
896 /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
897 /// // ^^^^^^^^^^^^^^^^^^^^^
898 /// // (mutable) reference to uninitialized memory!
899 /// // This is undefined behavior.
900 /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
901 /// // ^^^^^^^^^^^^^^^^^^^^^
902 /// // (mutable) reference to uninitialized memory!
903 /// // This is undefined behavior.
904 /// foo.assume_init()
907 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
908 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
910 pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
911 // SAFETY: the caller must guarantee that `self` is initialized.
912 // This also means that `self` must be a `value` variant.
914 intrinsics::assert_inhabited::<T>();
915 &mut *self.as_mut_ptr()
919 /// Extracts the values from an array of `MaybeUninit` containers.
923 /// It is up to the caller to guarantee that all elements of the array are
924 /// in an initialized state.
929 /// #![feature(maybe_uninit_uninit_array)]
930 /// #![feature(maybe_uninit_array_assume_init)]
931 /// use std::mem::MaybeUninit;
933 /// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
934 /// array[0].write(0);
935 /// array[1].write(1);
936 /// array[2].write(2);
938 /// // SAFETY: Now safe as we initialised all elements
939 /// let array = unsafe {
940 /// MaybeUninit::array_assume_init(array)
943 /// assert_eq!(array, [0, 1, 2]);
945 #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
948 pub unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
950 // * The caller guarantees that all elements of the array are initialized
951 // * `MaybeUninit<T>` and T are guaranteed to have the same layout
952 // * `MaybeUninit` does not drop, so there are no double-frees
953 // And thus the conversion is safe
955 intrinsics::assert_inhabited::<[T; N]>();
956 (&array as *const _ as *const [T; N]).read()
960 /// Assuming all the elements are initialized, get a slice to them.
964 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
965 /// really are in an initialized state.
966 /// Calling this when the content is not yet fully initialized causes undefined behavior.
968 /// See [`assume_init_ref`] for more details and examples.
970 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
971 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
972 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
974 pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
975 // SAFETY: casting `slice` to a `*const [T]` is safe since the caller guarantees that
976 // `slice` is initialized, and `MaybeUninit` is guaranteed to have the same layout as `T`.
977 // The pointer obtained is valid since it refers to memory owned by `slice` which is a
978 // reference and thus guaranteed to be valid for reads.
979 unsafe { &*(slice as *const [Self] as *const [T]) }
982 /// Assuming all the elements are initialized, get a mutable slice to them.
986 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
987 /// really are in an initialized state.
988 /// Calling this when the content is not yet fully initialized causes undefined behavior.
990 /// See [`assume_init_mut`] for more details and examples.
992 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
993 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
994 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
996 pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
997 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
998 // mutable reference which is also guaranteed to be valid for writes.
999 unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
1002 /// Gets a pointer to the first element of the array.
1003 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
1004 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
1006 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
1007 this.as_ptr() as *const T
1010 /// Gets a mutable pointer to the first element of the array.
1011 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
1012 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
1014 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
1015 this.as_mut_ptr() as *mut T
1018 /// Copies the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
1020 /// If `T` does not implement `Copy`, use [`write_slice_cloned`]
1022 /// This is similar to [`slice::copy_from_slice`].
1026 /// This function will panic if the two slices have different lengths.
1031 /// #![feature(maybe_uninit_write_slice)]
1032 /// use std::mem::MaybeUninit;
1034 /// let mut dst = [MaybeUninit::uninit(); 32];
1035 /// let src = [0; 32];
1037 /// let init = MaybeUninit::write_slice(&mut dst, &src);
1039 /// assert_eq!(init, src);
1043 /// #![feature(maybe_uninit_write_slice)]
1044 /// use std::mem::MaybeUninit;
1046 /// let mut vec = Vec::with_capacity(32);
1047 /// let src = [0; 16];
1049 /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);
1051 /// // SAFETY: we have just copied all the elements of len into the spare capacity
1052 /// // the first src.len() elements of the vec are valid now.
1054 /// vec.set_len(src.len());
1057 /// assert_eq!(vec, src);
1060 /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned
1061 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1062 pub fn write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1066 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1067 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1069 this.copy_from_slice(uninit_src);
1071 // SAFETY: Valid elements have just been copied into `this` so it is initialized
1072 unsafe { MaybeUninit::slice_assume_init_mut(this) }
1075 /// Clones the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
1076 /// Any already initialized elements will not be dropped.
1078 /// If `T` implements `Copy`, use [`write_slice`]
1080 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1084 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1086 /// If there is a panic, the already cloned elements will be dropped.
1091 /// #![feature(maybe_uninit_write_slice)]
1092 /// use std::mem::MaybeUninit;
1094 /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()];
1095 /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()];
1097 /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src);
1099 /// assert_eq!(init, src);
1103 /// #![feature(maybe_uninit_write_slice)]
1104 /// use std::mem::MaybeUninit;
1106 /// let mut vec = Vec::with_capacity(32);
1107 /// let src = ["rust", "is", "a", "pretty", "cool", "language"];
1109 /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src);
1111 /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1112 /// // the first src.len() elements of the vec are valid now.
1114 /// vec.set_len(src.len());
1117 /// assert_eq!(vec, src);
1120 /// [`write_slice`]: MaybeUninit::write_slice
1121 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1122 pub fn write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1126 // unlike copy_from_slice this does not call clone_from_slice on the slice
1127 // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1129 struct Guard<'a, T> {
1130 slice: &'a mut [MaybeUninit<T>],
1134 impl<'a, T> Drop for Guard<'a, T> {
1135 fn drop(&mut self) {
1136 let initialized_part = &mut self.slice[..self.initialized];
1137 // SAFETY: this raw slice will contain only initialized objects
1138 // that's why, it is allowed to drop it.
1140 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part));
1145 assert_eq!(this.len(), src.len(), "destination and source slices have different lengths");
1146 // NOTE: We need to explicitly slice them to the same length
1147 // for bounds checking to be elided, and the optimizer will
1148 // generate memcpy for simple cases (for example T = u8).
1149 let len = this.len();
1150 let src = &src[..len];
1152 // guard is needed b/c panic might happen during a clone
1153 let mut guard = Guard { slice: this, initialized: 0 };
1156 guard.slice[i].write(src[i].clone());
1157 guard.initialized += 1;
1160 super::forget(guard);
1162 // SAFETY: Valid elements have just been written into `this` so it is initialized
1163 unsafe { MaybeUninit::slice_assume_init_mut(this) }
1166 /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1168 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1169 /// contain padding bytes which are left uninitialized.
1174 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_slice)]
1175 /// use std::mem::MaybeUninit;
1177 /// let val = 0x12345678i32;
1178 /// let uninit = MaybeUninit::new(val);
1179 /// let uninit_bytes = uninit.as_bytes();
1180 /// let bytes = unsafe { MaybeUninit::slice_assume_init_ref(uninit_bytes) };
1181 /// assert_eq!(bytes, val.to_ne_bytes());
1183 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1184 pub fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1185 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1187 slice::from_raw_parts(self.as_ptr() as *const MaybeUninit<u8>, mem::size_of::<T>())
1191 /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized
1194 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1195 /// contain padding bytes which are left uninitialized.
1200 /// #![feature(maybe_uninit_as_bytes)]
1201 /// use std::mem::MaybeUninit;
1203 /// let val = 0x12345678i32;
1204 /// let mut uninit = MaybeUninit::new(val);
1205 /// let uninit_bytes = uninit.as_bytes_mut();
1206 /// if cfg!(target_endian = "little") {
1207 /// uninit_bytes[0].write(0xcd);
1209 /// uninit_bytes[3].write(0xcd);
1211 /// let val2 = unsafe { uninit.assume_init() };
1212 /// assert_eq!(val2, 0x123456cd);
1214 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1215 pub fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1216 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1218 slice::from_raw_parts_mut(
1219 self.as_mut_ptr() as *mut MaybeUninit<u8>,
1220 mem::size_of::<T>(),
1225 /// Returns the contents of this slice of `MaybeUninit` as a slice of potentially uninitialized
1228 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1229 /// contain padding bytes which are left uninitialized.
1234 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)]
1235 /// use std::mem::MaybeUninit;
1237 /// let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)];
1238 /// let uninit_bytes = MaybeUninit::slice_as_bytes(&uninit);
1239 /// let bytes = unsafe { MaybeUninit::slice_assume_init_ref(&uninit_bytes) };
1240 /// let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap());
1241 /// let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap());
1242 /// assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]);
1244 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1245 pub fn slice_as_bytes(this: &[MaybeUninit<T>]) -> &[MaybeUninit<u8>] {
1246 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1248 slice::from_raw_parts(
1249 this.as_ptr() as *const MaybeUninit<u8>,
1250 this.len() * mem::size_of::<T>(),
1255 /// Returns the contents of this mutable slice of `MaybeUninit` as a mutable slice of
1256 /// potentially uninitialized bytes.
1258 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1259 /// contain padding bytes which are left uninitialized.
1264 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)]
1265 /// use std::mem::MaybeUninit;
1267 /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()];
1268 /// let uninit_bytes = MaybeUninit::slice_as_bytes_mut(&mut uninit);
1269 /// MaybeUninit::write_slice(uninit_bytes, &[0x12, 0x34, 0x56, 0x78]);
1270 /// let vals = unsafe { MaybeUninit::slice_assume_init_ref(&uninit) };
1271 /// if cfg!(target_endian = "little") {
1272 /// assert_eq!(vals, &[0x3412u16, 0x7856u16]);
1274 /// assert_eq!(vals, &[0x1234u16, 0x5678u16]);
1277 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1278 pub fn slice_as_bytes_mut(this: &mut [MaybeUninit<T>]) -> &mut [MaybeUninit<u8>] {
1279 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1281 slice::from_raw_parts_mut(
1282 this.as_mut_ptr() as *mut MaybeUninit<u8>,
1283 this.len() * mem::size_of::<T>(),