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