]> git.proxmox.com Git - rustc.git/blame - library/core/src/mem/maybe_uninit.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / library / core / src / mem / maybe_uninit.rs
CommitLineData
60c5eb7d
XL
1use crate::any::type_name;
2use crate::fmt;
dc9dc135 3use crate::intrinsics;
5099ac24 4use crate::mem::{self, ManuallyDrop};
1b1a35ee 5use crate::ptr;
5099ac24 6use crate::slice;
60c5eb7d 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
17df50a5 14/// reference type must be aligned and non-null. This is an invariant that must
e74abb32
XL
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///
f9f354fc 23/// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior! ⚠️
dc9dc135 24/// // The equivalent code with `MaybeUninit<&i32>`:
f9f354fc 25/// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! ⚠️
dc9dc135
XL
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///
f9f354fc 38/// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
dc9dc135 39/// // The equivalent code with `MaybeUninit<bool>`:
f9f354fc 40/// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
dc9dc135
XL
41/// ```
42///
6a06907d
XL
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:
dc9dc135
XL
48///
49/// ```rust,no_run
416331ca 50/// # #![allow(invalid_value)]
dc9dc135
XL
51/// use std::mem::{self, MaybeUninit};
52///
f9f354fc 53/// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️
dc9dc135 54/// // The equivalent code with `MaybeUninit<i32>`:
f9f354fc 55/// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️
dc9dc135
XL
56/// ```
57/// (Notice that the rules around uninitialized integers are not finalized yet, but
58/// until they are, it is advisable to avoid them.)
59///
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>`]
416331ca
XL
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
dc9dc135
XL
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).
67///
68/// [`Vec<T>`]: ../../std/vec/struct.Vec.html
69///
70/// # Examples
71///
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*
74/// be initialized:
75///
76/// ```rust
77/// use std::mem::MaybeUninit;
78///
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.
136023e0 83/// x.write(&0);
dc9dc135
XL
84/// // Extract the initialized data -- this is only allowed *after* properly
85/// // initializing `x`!
86/// let x = unsafe { x.assume_init() };
87/// ```
88///
89/// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
90///
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.
93///
94/// ## out-pointers
95///
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.
101///
102/// ```
103/// use std::mem::MaybeUninit;
104///
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]);
108/// }
109///
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]);
116/// ```
117///
118/// ## Initializing an array element-by-element
119///
120/// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
121///
122/// ```
123/// use std::mem::{self, MaybeUninit};
dc9dc135
XL
124///
125/// let data = {
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()
131/// };
132///
416331ca
XL
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
137/// // issue.
dc9dc135 138/// for elem in &mut data[..] {
136023e0 139/// elem.write(vec![42]);
dc9dc135
XL
140/// }
141///
142/// // Everything is initialized. Transmute the array to the
143/// // initialized type.
144/// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
145/// };
146///
147/// assert_eq!(&data[0], &[42]);
148/// ```
149///
150/// You can also work with partially initialized arrays, which could
151/// be found in low-level datastructures.
152///
153/// ```
154/// use std::mem::MaybeUninit;
155/// use std::ptr;
156///
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;
163///
164/// for elem in &mut data[0..500] {
136023e0 165/// elem.write(String::from("hello"));
dc9dc135
XL
166/// data_len += 1;
167/// }
168///
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()); }
172/// }
173/// ```
174///
175/// ## Initializing a struct field-by-field
176///
5869c6ff 177/// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field:
dc9dc135 178///
5869c6ff
XL
179/// ```rust
180/// use std::mem::MaybeUninit;
181/// use std::ptr::addr_of_mut;
182///
183/// #[derive(Debug, PartialEq)]
184/// pub struct Foo {
185/// name: String,
186/// list: Vec<u8>,
187/// }
188///
189/// let foo = {
190/// let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
191/// let ptr = uninit.as_mut_ptr();
192///
193/// // Initializing the `name` field
cdc7bbd5
XL
194/// // Using `write` instead of assignment via `=` to not call `drop` on the
195/// // old, uninitialized value.
5869c6ff
XL
196/// unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); }
197///
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]); }
201///
202/// // All the fields are initialized, so we call `assume_init` to get an initialized Foo.
203/// unsafe { uninit.assume_init() }
204/// };
205///
206/// assert_eq!(
207/// foo,
208/// Foo {
209/// name: "Bob".to_string(),
210/// list: vec![0, 1, 2]
211/// }
212/// );
213/// ```
214/// [`std::ptr::addr_of_mut`]: crate::ptr::addr_of_mut
dc9dc135
XL
215/// [ub]: ../../reference/behavior-considered-undefined.html
216///
217/// # Layout
218///
219/// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`:
220///
221/// ```rust
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>());
225/// ```
226///
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:
232///
233/// ```rust
234/// # use std::mem::{MaybeUninit, size_of};
235/// assert_eq!(size_of::<Option<bool>>(), 1);
236/// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
237/// ```
238///
239/// If `T` is FFI-safe, then so is `MaybeUninit<T>`.
240///
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.
dc9dc135 251#[stable(feature = "maybe_uninit", since = "1.36.0")]
416331ca 252// Lang item so we can wrap other types in it. This is useful for generators.
e1599b0c 253#[lang = "maybe_uninit"]
dc9dc135 254#[derive(Copy)]
416331ca 255#[repr(transparent)]
dc9dc135
XL
256pub union MaybeUninit<T> {
257 uninit: (),
258 value: ManuallyDrop<T>,
259}
260
261#[stable(feature = "maybe_uninit", since = "1.36.0")]
262impl<T: Copy> Clone for MaybeUninit<T> {
263 #[inline(always)]
264 fn clone(&self) -> Self {
265 // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
266 *self
267 }
268}
269
60c5eb7d
XL
270#[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
271impl<T> fmt::Debug for MaybeUninit<T> {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 f.pad(type_name::<Self>())
274 }
275}
276
dc9dc135
XL
277impl<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.
280 ///
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.
283 ///
29967ef6
XL
284 /// # Example
285 ///
286 /// ```
287 /// use std::mem::MaybeUninit;
288 ///
289 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
290 /// ```
291 ///
3dfed10e 292 /// [`assume_init`]: MaybeUninit::assume_init
dc9dc135 293 #[stable(feature = "maybe_uninit", since = "1.36.0")]
dfeec247 294 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
c295e0f8 295 #[must_use = "use `forget` to avoid running Drop code"]
dc9dc135
XL
296 #[inline(always)]
297 pub const fn new(val: T) -> MaybeUninit<T> {
298 MaybeUninit { value: ManuallyDrop::new(val) }
299 }
300
301 /// Creates a new `MaybeUninit<T>` in an uninitialized state.
302 ///
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.
305 ///
29967ef6 306 /// See the [type-level documentation][MaybeUninit] for some examples.
dc9dc135 307 ///
29967ef6
XL
308 /// # Example
309 ///
310 /// ```
311 /// use std::mem::MaybeUninit;
312 ///
313 /// let v: MaybeUninit<String> = MaybeUninit::uninit();
314 /// ```
dc9dc135 315 #[stable(feature = "maybe_uninit", since = "1.36.0")]
dfeec247 316 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
c295e0f8 317 #[must_use]
dc9dc135 318 #[inline(always)]
dfeec247 319 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
dc9dc135
XL
320 pub const fn uninit() -> MaybeUninit<T> {
321 MaybeUninit { uninit: () }
322 }
323
60c5eb7d
XL
324 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
325 ///
326 /// Note: in a future Rust version this method may become unnecessary
cdc7bbd5
XL
327 /// when Rust allows
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];`.
60c5eb7d
XL
330 ///
331 /// # Examples
332 ///
333 /// ```no_run
5099ac24 334 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_slice)]
60c5eb7d
XL
335 ///
336 /// use std::mem::MaybeUninit;
337 ///
338 /// extern "C" {
339 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
340 /// }
341 ///
342 /// /// Returns a (possibly smaller) slice of data that was actually read
343 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
344 /// unsafe {
345 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
1b1a35ee 346 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
60c5eb7d
XL
347 /// }
348 /// }
349 ///
350 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
351 /// let data = read(&mut buf);
352 /// ```
dfeec247 353 #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
fc512014 354 #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
c295e0f8 355 #[must_use]
60c5eb7d 356 #[inline(always)]
fc512014 357 pub const fn uninit_array<const LEN: usize>() -> [Self; LEN] {
1b1a35ee 358 // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
dfeec247 359 unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
60c5eb7d
XL
360 }
361
dc9dc135
XL
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
366 /// be null.
367 ///
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.
370 ///
371 /// # Example
372 ///
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.
375 ///
376 /// ```rust
377 /// use std::mem::MaybeUninit;
378 ///
379 /// let x = MaybeUninit::<(u8, bool)>::zeroed();
380 /// let x = unsafe { x.assume_init() };
381 /// assert_eq!(x, (0, false));
382 /// ```
383 ///
3dfed10e
XL
384 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
385 /// when `0` is not a valid bit-pattern for the type:
dc9dc135
XL
386 ///
387 /// ```rust,no_run
388 /// use std::mem::MaybeUninit;
389 ///
fc512014 390 /// enum NotZero { One = 1, Two = 2 }
dc9dc135
XL
391 ///
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.
f9f354fc 395 /// // This is undefined behavior. ⚠️
dc9dc135
XL
396 /// ```
397 #[stable(feature = "maybe_uninit", since = "1.36.0")]
a2a8927a 398 #[rustc_const_unstable(feature = "const_maybe_uninit_zeroed", issue = "91850")]
c295e0f8 399 #[must_use]
dc9dc135 400 #[inline]
dfeec247 401 #[rustc_diagnostic_item = "maybe_uninit_zeroed"]
a2a8927a 402 pub const fn zeroed() -> MaybeUninit<T> {
dc9dc135 403 let mut u = MaybeUninit::<T>::uninit();
1b1a35ee 404 // SAFETY: `u.as_mut_ptr()` points to allocated memory.
dc9dc135
XL
405 unsafe {
406 u.as_mut_ptr().write_bytes(0u8, 1);
407 }
408 u
409 }
410
136023e0
XL
411 /// Sets the value of the `MaybeUninit<T>`.
412 ///
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`.
417 ///
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.
426 ///
427 /// [`assume_init`]: Self::assume_init
428 /// [`assume_init_drop`]: Self::assume_init_drop
429 ///
430 /// # Examples
431 ///
432 /// Correct usage of this method:
433 ///
434 /// ```rust
435 /// use std::mem::MaybeUninit;
436 ///
437 /// let mut x = MaybeUninit::<Vec<u8>>::uninit();
438 ///
439 /// {
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;
444 /// }
445 /// // x is initialized now:
446 /// let s = unsafe { x.assume_init() };
447 /// assert_eq!(b"hello", s.as_slice());
448 /// ```
449 ///
450 /// This usage of the method causes a leak:
451 ///
452 /// ```rust
453 /// use std::mem::MaybeUninit;
454 ///
455 /// let mut x = MaybeUninit::<String>::uninit();
456 ///
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() };
462 /// ```
463 ///
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:
468 ///
469 /// ```rust
136023e0
XL
470 /// use core::pin::Pin;
471 /// use core::mem::MaybeUninit;
472 ///
473 /// struct PinArena<T> {
474 /// memory: Box<[MaybeUninit<T>]>,
475 /// len: usize,
476 /// }
477 ///
478 /// impl <T> PinArena<T> {
479 /// pub fn capacity(&self) -> usize {
480 /// self.memory.len()
481 /// }
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!");
485 /// }
486 /// let ref_ = self.memory[self.len].write(val);
487 /// self.len += 1;
488 /// unsafe { Pin::new_unchecked(ref_) }
489 /// }
490 /// }
491 /// ```
492 #[stable(feature = "maybe_uninit_write", since = "1.55.0")]
493 #[rustc_const_unstable(feature = "const_maybe_uninit_write", issue = "63567")]
dc9dc135 494 #[inline(always)]
fc512014 495 pub const fn write(&mut self, val: T) -> &mut T {
1b1a35ee
XL
496 *self = MaybeUninit::new(val);
497 // SAFETY: We just initialized this value.
498 unsafe { self.assume_init_mut() }
dc9dc135
XL
499 }
500
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>`).
505 ///
506 /// # Examples
507 ///
508 /// Correct usage of this method:
509 ///
510 /// ```rust
511 /// use std::mem::MaybeUninit;
512 ///
513 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
136023e0 514 /// x.write(vec![0, 1, 2]);
dc9dc135
XL
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);
518 /// ```
519 ///
520 /// *Incorrect* usage of this method:
521 ///
522 /// ```rust,no_run
523 /// use std::mem::MaybeUninit;
524 ///
525 /// let x = MaybeUninit::<Vec<u32>>::uninit();
526 /// let x_vec = unsafe { &*x.as_ptr() };
f9f354fc 527 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
dc9dc135
XL
528 /// ```
529 ///
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")]
a2a8927a 533 #[rustc_const_stable(feature = "const_maybe_uninit_as_ptr", since = "1.59.0")]
dc9dc135 534 #[inline(always)]
3dfed10e
XL
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
dc9dc135
XL
538 }
539
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.
542 ///
543 /// # Examples
544 ///
545 /// Correct usage of this method:
546 ///
547 /// ```rust
548 /// use std::mem::MaybeUninit;
549 ///
550 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
136023e0 551 /// x.write(vec![0, 1, 2]);
dc9dc135
XL
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() };
555 /// x_vec.push(3);
556 /// assert_eq!(x_vec.len(), 4);
557 /// ```
558 ///
559 /// *Incorrect* usage of this method:
560 ///
561 /// ```rust,no_run
562 /// use std::mem::MaybeUninit;
563 ///
564 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
565 /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
f9f354fc 566 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
dc9dc135
XL
567 /// ```
568 ///
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")]
a2a8927a 572 #[rustc_const_unstable(feature = "const_maybe_uninit_as_mut_ptr", issue = "75251")]
dc9dc135 573 #[inline(always)]
3dfed10e
XL
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
dc9dc135
XL
577 }
578
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.
582 ///
583 /// # Safety
584 ///
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.
589 ///
590 /// [inv]: #initialization-invariant
591 ///
416331ca
XL
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).
599 ///
1b1a35ee
XL
600 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
601 ///
dc9dc135
XL
602 /// # Examples
603 ///
604 /// Correct usage of this method:
605 ///
606 /// ```rust
607 /// use std::mem::MaybeUninit;
608 ///
609 /// let mut x = MaybeUninit::<bool>::uninit();
136023e0 610 /// x.write(true);
dc9dc135
XL
611 /// let x_init = unsafe { x.assume_init() };
612 /// assert_eq!(x_init, true);
613 /// ```
614 ///
615 /// *Incorrect* usage of this method:
616 ///
617 /// ```rust,no_run
618 /// use std::mem::MaybeUninit;
619 ///
620 /// let x = MaybeUninit::<Vec<u32>>::uninit();
621 /// let x_init = unsafe { x.assume_init() };
f9f354fc 622 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
dc9dc135
XL
623 /// ```
624 #[stable(feature = "maybe_uninit", since = "1.36.0")]
ee023bcb 625 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_by_value", since = "1.59.0")]
dc9dc135 626 #[inline(always)]
dfeec247 627 #[rustc_diagnostic_item = "assume_init"]
94222f64 628 #[track_caller]
fc512014 629 pub const unsafe fn assume_init(self) -> T {
f035d41b
XL
630 // SAFETY: the caller must guarantee that `self` is initialized.
631 // This also means that `self` must be a `value` variant.
632 unsafe {
633 intrinsics::assert_inhabited::<T>();
634 ManuallyDrop::into_inner(self.value)
635 }
dc9dc135
XL
636 }
637
638 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
639 /// to the usual drop handling.
640 ///
416331ca 641 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
dc9dc135
XL
642 /// prevents duplicating the content of the `MaybeUninit<T>`.
643 ///
644 /// # Safety
645 ///
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.
650 ///
136023e0
XL
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
dc9dc135
XL
656 /// to ensure that that data may indeed be duplicated.
657 ///
658 /// [inv]: #initialization-invariant
3dfed10e 659 /// [`assume_init`]: MaybeUninit::assume_init
dc9dc135
XL
660 ///
661 /// # Examples
662 ///
663 /// Correct usage of this method:
664 ///
665 /// ```rust
dc9dc135
XL
666 /// use std::mem::MaybeUninit;
667 ///
668 /// let mut x = MaybeUninit::<u32>::uninit();
669 /// x.write(13);
1b1a35ee 670 /// let x1 = unsafe { x.assume_init_read() };
dc9dc135 671 /// // `u32` is `Copy`, so we may read multiple times.
1b1a35ee 672 /// let x2 = unsafe { x.assume_init_read() };
dc9dc135
XL
673 /// assert_eq!(x1, x2);
674 ///
675 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
676 /// x.write(None);
1b1a35ee 677 /// let x1 = unsafe { x.assume_init_read() };
dc9dc135 678 /// // Duplicating a `None` value is okay, so we may read multiple times.
1b1a35ee 679 /// let x2 = unsafe { x.assume_init_read() };
dc9dc135
XL
680 /// assert_eq!(x1, x2);
681 /// ```
682 ///
683 /// *Incorrect* usage of this method:
684 ///
685 /// ```rust,no_run
dc9dc135
XL
686 /// use std::mem::MaybeUninit;
687 ///
688 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
fc512014 689 /// x.write(Some(vec![0, 1, 2]));
1b1a35ee
XL
690 /// let x1 = unsafe { x.assume_init_read() };
691 /// let x2 = unsafe { x.assume_init_read() };
f9f354fc 692 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when
dc9dc135
XL
693 /// // they both get dropped!
694 /// ```
5099ac24
FG
695 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
696 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init_read", issue = "63567")]
dc9dc135 697 #[inline(always)]
94222f64 698 #[track_caller]
5869c6ff 699 pub const unsafe fn assume_init_read(&self) -> T {
f035d41b
XL
700 // SAFETY: the caller must guarantee that `self` is initialized.
701 // Reading from `self.as_ptr()` is safe since `self` should be initialized.
702 unsafe {
703 intrinsics::assert_inhabited::<T>();
704 self.as_ptr().read()
705 }
dc9dc135
XL
706 }
707
1b1a35ee
XL
708 /// Drops the contained value in place.
709 ///
136023e0
XL
710 /// If you have ownership of the `MaybeUninit`, you can also use
711 /// [`assume_init`] as an alternative.
1b1a35ee
XL
712 ///
713 /// # Safety
714 ///
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.
718 ///
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
136023e0
XL
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
726 /// behaviour.
1b1a35ee
XL
727 ///
728 /// [`assume_init`]: MaybeUninit::assume_init
729 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
5099ac24 730 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
1b1a35ee
XL
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()) }
736 }
737
60c5eb7d
XL
738 /// Gets a shared reference to the contained value.
739 ///
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()`).
dc9dc135
XL
743 ///
744 /// # Safety
745 ///
60c5eb7d
XL
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.
749 ///
750 /// # Examples
751 ///
752 /// ### Correct usage of this method:
753 ///
754 /// ```rust
60c5eb7d
XL
755 /// use std::mem::MaybeUninit;
756 ///
757 /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
758 /// // Initialize `x`:
136023e0 759 /// x.write(vec![1, 2, 3]);
60c5eb7d
XL
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 {
1b1a35ee
XL
763 /// // SAFETY: `x` has been initialized.
764 /// x.assume_init_ref()
60c5eb7d
XL
765 /// };
766 /// assert_eq!(x, &vec![1, 2, 3]);
767 /// ```
768 ///
769 /// ### *Incorrect* usages of this method:
770 ///
771 /// ```rust,no_run
60c5eb7d
XL
772 /// use std::mem::MaybeUninit;
773 ///
774 /// let x = MaybeUninit::<Vec<u32>>::uninit();
1b1a35ee 775 /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
f9f354fc 776 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
60c5eb7d
XL
777 /// ```
778 ///
779 /// ```rust,no_run
60c5eb7d
XL
780 /// use std::{cell::Cell, mem::MaybeUninit};
781 ///
782 /// let b = MaybeUninit::<Cell<bool>>::uninit();
783 /// // Initialize the `MaybeUninit` using `Cell::set`:
784 /// unsafe {
1b1a35ee
XL
785 /// b.assume_init_ref().set(true);
786 /// // ^^^^^^^^^^^^^^^
787 /// // Reference to an uninitialized `Cell<bool>`: UB!
60c5eb7d
XL
788 /// }
789 /// ```
136023e0 790 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
ee023bcb 791 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_ref", since = "1.59.0")]
dc9dc135 792 #[inline(always)]
fc512014 793 pub const unsafe fn assume_init_ref(&self) -> &T {
f035d41b
XL
794 // SAFETY: the caller must guarantee that `self` is initialized.
795 // This also means that `self` must be a `value` variant.
796 unsafe {
797 intrinsics::assert_inhabited::<T>();
fc512014 798 &*self.as_ptr()
f035d41b 799 }
dc9dc135
XL
800 }
801
60c5eb7d
XL
802 /// Gets a mutable (unique) reference to the contained value.
803 ///
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()`).
dc9dc135
XL
807 ///
808 /// # Safety
809 ///
60c5eb7d
XL
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
1b1a35ee 812 /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to
60c5eb7d
XL
813 /// initialize a `MaybeUninit`.
814 ///
815 /// # Examples
816 ///
817 /// ### Correct usage of this method:
818 ///
819 /// ```rust
ee023bcb 820 /// # #![allow(unexpected_cfgs)]
60c5eb7d
XL
821 /// use std::mem::MaybeUninit;
822 ///
cdc7bbd5 823 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] }
60c5eb7d
XL
824 /// # #[cfg(FALSE)]
825 /// extern "C" {
826 /// /// Initializes *all* the bytes of the input buffer.
cdc7bbd5 827 /// fn initialize_buffer(buf: *mut [u8; 1024]);
60c5eb7d
XL
828 /// }
829 ///
cdc7bbd5 830 /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
60c5eb7d
XL
831 ///
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.
cdc7bbd5 835 /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes.
60c5eb7d 836 /// // To assert our buffer has been initialized without copying it, we upgrade
cdc7bbd5
XL
837 /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`:
838 /// let buf: &mut [u8; 1024] = unsafe {
1b1a35ee
XL
839 /// // SAFETY: `buf` has been initialized.
840 /// buf.assume_init_mut()
60c5eb7d
XL
841 /// };
842 ///
843 /// // Now we can use `buf` as a normal slice:
844 /// buf.sort_unstable();
845 /// assert!(
74b04a01 846 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
60c5eb7d
XL
847 /// "buffer is sorted",
848 /// );
849 /// ```
850 ///
851 /// ### *Incorrect* usages of this method:
852 ///
1b1a35ee 853 /// You cannot use `.assume_init_mut()` to initialize a value:
60c5eb7d
XL
854 ///
855 /// ```rust,no_run
60c5eb7d
XL
856 /// use std::mem::MaybeUninit;
857 ///
858 /// let mut b = MaybeUninit::<bool>::uninit();
859 /// unsafe {
1b1a35ee 860 /// *b.assume_init_mut() = true;
60c5eb7d 861 /// // We have created a (mutable) reference to an uninitialized `bool`!
f9f354fc 862 /// // This is undefined behavior. ⚠️
60c5eb7d
XL
863 /// }
864 /// ```
865 ///
866 /// For instance, you cannot [`Read`] into an uninitialized buffer:
867 ///
868 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
869 ///
870 /// ```rust,no_run
60c5eb7d
XL
871 /// use std::{io, mem::MaybeUninit};
872 ///
873 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]>
874 /// {
875 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit();
1b1a35ee
XL
876 /// reader.read_exact(unsafe { buffer.assume_init_mut() })?;
877 /// // ^^^^^^^^^^^^^^^^^^^^^^^^
60c5eb7d
XL
878 /// // (mutable) reference to uninitialized memory!
879 /// // This is undefined behavior.
880 /// Ok(unsafe { buffer.assume_init() })
881 /// }
882 /// ```
883 ///
884 /// Nor can you use direct field access to do field-by-field gradual initialization:
885 ///
886 /// ```rust,no_run
60c5eb7d
XL
887 /// use std::{mem::MaybeUninit, ptr};
888 ///
889 /// struct Foo {
890 /// a: u32,
891 /// b: u8,
892 /// }
893 ///
894 /// let foo: Foo = unsafe {
895 /// let mut foo = MaybeUninit::<Foo>::uninit();
1b1a35ee
XL
896 /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337);
897 /// // ^^^^^^^^^^^^^^^^^^^^^
60c5eb7d
XL
898 /// // (mutable) reference to uninitialized memory!
899 /// // This is undefined behavior.
1b1a35ee
XL
900 /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42);
901 /// // ^^^^^^^^^^^^^^^^^^^^^
60c5eb7d
XL
902 /// // (mutable) reference to uninitialized memory!
903 /// // This is undefined behavior.
904 /// foo.assume_init()
905 /// };
906 /// ```
136023e0 907 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
fc512014 908 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
dc9dc135 909 #[inline(always)]
fc512014 910 pub const unsafe fn assume_init_mut(&mut self) -> &mut T {
f035d41b
XL
911 // SAFETY: the caller must guarantee that `self` is initialized.
912 // This also means that `self` must be a `value` variant.
913 unsafe {
914 intrinsics::assert_inhabited::<T>();
fc512014 915 &mut *self.as_mut_ptr()
f035d41b 916 }
dc9dc135
XL
917 }
918
5869c6ff
XL
919 /// Extracts the values from an array of `MaybeUninit` containers.
920 ///
921 /// # Safety
922 ///
923 /// It is up to the caller to guarantee that all elements of the array are
924 /// in an initialized state.
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// #![feature(maybe_uninit_uninit_array)]
930 /// #![feature(maybe_uninit_array_assume_init)]
931 /// use std::mem::MaybeUninit;
932 ///
933 /// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
136023e0
XL
934 /// array[0].write(0);
935 /// array[1].write(1);
936 /// array[2].write(2);
5869c6ff
XL
937 ///
938 /// // SAFETY: Now safe as we initialised all elements
939 /// let array = unsafe {
940 /// MaybeUninit::array_assume_init(array)
941 /// };
942 ///
943 /// assert_eq!(array, [0, 1, 2]);
944 /// ```
945 #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
946 #[inline(always)]
94222f64 947 #[track_caller]
5869c6ff
XL
948 pub unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
949 // SAFETY:
950 // * The caller guarantees that all elements of the array are initialized
951 // * `MaybeUninit<T>` and T are guaranteed to have the same layout
17df50a5 952 // * `MaybeUninit` does not drop, so there are no double-frees
5869c6ff
XL
953 // And thus the conversion is safe
954 unsafe {
955 intrinsics::assert_inhabited::<[T; N]>();
956 (&array as *const _ as *const [T; N]).read()
957 }
958 }
959
60c5eb7d
XL
960 /// Assuming all the elements are initialized, get a slice to them.
961 ///
962 /// # Safety
963 ///
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.
1b1a35ee
XL
967 ///
968 /// See [`assume_init_ref`] for more details and examples.
969 ///
970 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
971 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
a2a8927a 972 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
60c5eb7d 973 #[inline(always)]
fc512014 974 pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
a2a8927a
XL
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`.
f035d41b
XL
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]) }
60c5eb7d
XL
980 }
981
982 /// Assuming all the elements are initialized, get a mutable slice to them.
983 ///
984 /// # Safety
985 ///
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.
1b1a35ee
XL
989 ///
990 /// See [`assume_init_mut`] for more details and examples.
991 ///
992 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
993 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
fc512014 994 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
60c5eb7d 995 #[inline(always)]
fc512014 996 pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
f035d41b
XL
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]) }
60c5eb7d
XL
1000 }
1001
dc9dc135 1002 /// Gets a pointer to the first element of the array.
e1599b0c 1003 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
fc512014 1004 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
dc9dc135 1005 #[inline(always)]
fc512014 1006 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
29967ef6 1007 this.as_ptr() as *const T
dc9dc135
XL
1008 }
1009
1010 /// Gets a mutable pointer to the first element of the array.
e1599b0c 1011 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
fc512014 1012 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
dc9dc135 1013 #[inline(always)]
fc512014 1014 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
29967ef6 1015 this.as_mut_ptr() as *mut T
dc9dc135 1016 }
fc512014 1017
136023e0 1018 /// Copies the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
fc512014
XL
1019 ///
1020 /// If `T` does not implement `Copy`, use [`write_slice_cloned`]
1021 ///
1022 /// This is similar to [`slice::copy_from_slice`].
1023 ///
1024 /// # Panics
1025 ///
1026 /// This function will panic if the two slices have different lengths.
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// #![feature(maybe_uninit_write_slice)]
1032 /// use std::mem::MaybeUninit;
1033 ///
1034 /// let mut dst = [MaybeUninit::uninit(); 32];
1035 /// let src = [0; 32];
1036 ///
1037 /// let init = MaybeUninit::write_slice(&mut dst, &src);
1038 ///
1039 /// assert_eq!(init, src);
1040 /// ```
1041 ///
1042 /// ```
5099ac24 1043 /// #![feature(maybe_uninit_write_slice)]
fc512014
XL
1044 /// use std::mem::MaybeUninit;
1045 ///
1046 /// let mut vec = Vec::with_capacity(32);
1047 /// let src = [0; 16];
1048 ///
1049 /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);
1050 ///
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.
1053 /// unsafe {
1054 /// vec.set_len(src.len());
1055 /// }
1056 ///
1057 /// assert_eq!(vec, src);
1058 /// ```
1059 ///
1060 /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned
fc512014
XL
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]
1063 where
1064 T: Copy,
1065 {
1066 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1067 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1068
1069 this.copy_from_slice(uninit_src);
1070
136023e0 1071 // SAFETY: Valid elements have just been copied into `this` so it is initialized
fc512014
XL
1072 unsafe { MaybeUninit::slice_assume_init_mut(this) }
1073 }
1074
136023e0
XL
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.
fc512014
XL
1077 ///
1078 /// If `T` implements `Copy`, use [`write_slice`]
1079 ///
1080 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1081 ///
1082 /// # Panics
1083 ///
1084 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1085 ///
1086 /// If there is a panic, the already cloned elements will be dropped.
1087 ///
1088 /// # Examples
1089 ///
1090 /// ```
1091 /// #![feature(maybe_uninit_write_slice)]
1092 /// use std::mem::MaybeUninit;
1093 ///
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()];
1096 ///
1097 /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src);
1098 ///
1099 /// assert_eq!(init, src);
1100 /// ```
1101 ///
1102 /// ```
5099ac24 1103 /// #![feature(maybe_uninit_write_slice)]
fc512014
XL
1104 /// use std::mem::MaybeUninit;
1105 ///
1106 /// let mut vec = Vec::with_capacity(32);
1107 /// let src = ["rust", "is", "a", "pretty", "cool", "language"];
1108 ///
1109 /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src);
1110 ///
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.
1113 /// unsafe {
1114 /// vec.set_len(src.len());
1115 /// }
1116 ///
1117 /// assert_eq!(vec, src);
1118 /// ```
1119 ///
1120 /// [`write_slice`]: MaybeUninit::write_slice
fc512014
XL
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]
1123 where
1124 T: Clone,
1125 {
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.
1128
1129 struct Guard<'a, T> {
1130 slice: &'a mut [MaybeUninit<T>],
1131 initialized: usize,
1132 }
1133
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.
1139 unsafe {
1140 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part));
1141 }
1142 }
1143 }
1144
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];
1151
1152 // guard is needed b/c panic might happen during a clone
1153 let mut guard = Guard { slice: this, initialized: 0 };
1154
1155 for i in 0..len {
1156 guard.slice[i].write(src[i].clone());
1157 guard.initialized += 1;
1158 }
1159
1160 super::forget(guard);
1161
136023e0 1162 // SAFETY: Valid elements have just been written into `this` so it is initialized
fc512014
XL
1163 unsafe { MaybeUninit::slice_assume_init_mut(this) }
1164 }
5099ac24
FG
1165
1166 /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1167 ///
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.
1170 ///
1171 /// # Examples
1172 ///
1173 /// ```
1174 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_slice)]
1175 /// use std::mem::MaybeUninit;
1176 ///
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());
1182 /// ```
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
1186 unsafe {
1187 slice::from_raw_parts(self.as_ptr() as *const MaybeUninit<u8>, mem::size_of::<T>())
1188 }
1189 }
1190
1191 /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized
1192 /// bytes.
1193 ///
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.
1196 ///
1197 /// # Examples
1198 ///
1199 /// ```
1200 /// #![feature(maybe_uninit_as_bytes)]
1201 /// use std::mem::MaybeUninit;
1202 ///
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);
1208 /// } else {
1209 /// uninit_bytes[3].write(0xcd);
1210 /// }
1211 /// let val2 = unsafe { uninit.assume_init() };
1212 /// assert_eq!(val2, 0x123456cd);
1213 /// ```
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
1217 unsafe {
1218 slice::from_raw_parts_mut(
1219 self.as_mut_ptr() as *mut MaybeUninit<u8>,
1220 mem::size_of::<T>(),
1221 )
1222 }
1223 }
1224
1225 /// Returns the contents of this slice of `MaybeUninit` as a slice of potentially uninitialized
1226 /// bytes.
1227 ///
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.
1230 ///
1231 /// # Examples
1232 ///
1233 /// ```
1234 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)]
1235 /// use std::mem::MaybeUninit;
1236 ///
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]);
1243 /// ```
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
1247 unsafe {
1248 slice::from_raw_parts(
1249 this.as_ptr() as *const MaybeUninit<u8>,
1250 this.len() * mem::size_of::<T>(),
1251 )
1252 }
1253 }
1254
1255 /// Returns the contents of this mutable slice of `MaybeUninit` as a mutable slice of
1256 /// potentially uninitialized bytes.
1257 ///
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.
1260 ///
1261 /// # Examples
1262 ///
1263 /// ```
1264 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)]
1265 /// use std::mem::MaybeUninit;
1266 ///
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]);
1273 /// } else {
1274 /// assert_eq!(vals, &[0x1234u16, 0x5678u16]);
1275 /// }
1276 /// ```
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
1280 unsafe {
1281 slice::from_raw_parts_mut(
1282 this.as_mut_ptr() as *mut MaybeUninit<u8>,
1283 this.len() * mem::size_of::<T>(),
1284 )
1285 }
1286 }
dc9dc135 1287}