]> git.proxmox.com Git - rustc.git/blob - library/core/src/mem/maybe_uninit.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / library / core / src / mem / maybe_uninit.rs
1 use crate::any::type_name;
2 use crate::fmt;
3 use crate::intrinsics;
4 use crate::mem::{self, ManuallyDrop};
5 use crate::ptr;
6 use crate::slice;
7
8 /// A wrapper type to construct uninitialized instances of `T`.
9 ///
10 /// # Initialization invariant
11 ///
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:
18 ///
19 /// ```rust,no_run
20 /// # #![allow(invalid_value)]
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
35 /// # #![allow(invalid_value)]
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 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:
48 ///
49 /// ```rust,no_run
50 /// # #![allow(invalid_value)]
51 /// use std::mem::{self, MaybeUninit};
52 ///
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! ⚠️
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>`]
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).
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.
83 /// x.write(&0);
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};
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 ///
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.
138 /// for elem in &mut data[..] {
139 /// elem.write(vec![42]);
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] {
165 /// elem.write(String::from("hello"));
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 ///
177 /// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field:
178 ///
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
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()); }
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
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.
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"]
254 #[derive(Copy)]
255 #[repr(transparent)]
256 pub union MaybeUninit<T> {
257 uninit: (),
258 value: ManuallyDrop<T>,
259 }
260
261 #[stable(feature = "maybe_uninit", since = "1.36.0")]
262 impl<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
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>())
274 }
275 }
276
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.
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 ///
284 /// # Example
285 ///
286 /// ```
287 /// use std::mem::MaybeUninit;
288 ///
289 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]);
290 /// ```
291 ///
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"]
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 ///
306 /// See the [type-level documentation][MaybeUninit] for some examples.
307 ///
308 /// # Example
309 ///
310 /// ```
311 /// use std::mem::MaybeUninit;
312 ///
313 /// let v: MaybeUninit<String> = MaybeUninit::uninit();
314 /// ```
315 #[stable(feature = "maybe_uninit", since = "1.36.0")]
316 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")]
317 #[must_use]
318 #[inline(always)]
319 #[rustc_diagnostic_item = "maybe_uninit_uninit"]
320 pub const fn uninit() -> MaybeUninit<T> {
321 MaybeUninit { uninit: () }
322 }
323
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
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];`.
330 ///
331 /// # Examples
332 ///
333 /// ```no_run
334 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_slice)]
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());
346 /// MaybeUninit::slice_assume_init_ref(&buf[..len])
347 /// }
348 /// }
349 ///
350 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
351 /// let data = read(&mut buf);
352 /// ```
353 #[unstable(feature = "maybe_uninit_uninit_array", issue = "96097")]
354 #[rustc_const_unstable(feature = "const_maybe_uninit_uninit_array", issue = "96097")]
355 #[must_use]
356 #[inline(always)]
357 pub const fn uninit_array<const N: usize>() -> [Self; N] {
358 // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
359 unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() }
360 }
361
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 ///
384 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()`
385 /// when `0` is not a valid bit-pattern for the type:
386 ///
387 /// ```rust,no_run
388 /// use std::mem::MaybeUninit;
389 ///
390 /// enum NotZero { One = 1, Two = 2 }
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.
395 /// // This is undefined behavior. ⚠️
396 /// ```
397 #[stable(feature = "maybe_uninit", since = "1.36.0")]
398 #[rustc_const_unstable(feature = "const_maybe_uninit_zeroed", issue = "91850")]
399 #[must_use]
400 #[inline]
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.
405 unsafe {
406 u.as_mut_ptr().write_bytes(0u8, 1);
407 }
408 u
409 }
410
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
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")]
494 #[inline(always)]
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() }
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();
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);
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() };
527 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
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")]
533 #[rustc_const_stable(feature = "const_maybe_uninit_as_ptr", since = "1.59.0")]
534 #[inline(always)]
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
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();
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() };
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() };
566 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
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")]
572 #[rustc_const_unstable(feature = "const_maybe_uninit_as_mut_ptr", issue = "75251")]
573 #[inline(always)]
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
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 ///
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 ///
600 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
601 ///
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();
610 /// x.write(true);
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() };
622 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️
623 /// ```
624 #[stable(feature = "maybe_uninit", since = "1.36.0")]
625 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_by_value", since = "1.59.0")]
626 #[inline(always)]
627 #[rustc_diagnostic_item = "assume_init"]
628 #[track_caller]
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.
632 unsafe {
633 intrinsics::assert_inhabited::<T>();
634 ManuallyDrop::into_inner(self.value)
635 }
636 }
637
638 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
639 /// to the usual drop handling.
640 ///
641 /// Whenever possible, it is preferable to use [`assume_init`] instead, which
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 ///
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.
657 ///
658 /// [inv]: #initialization-invariant
659 /// [`assume_init`]: MaybeUninit::assume_init
660 ///
661 /// # Examples
662 ///
663 /// Correct usage of this method:
664 ///
665 /// ```rust
666 /// use std::mem::MaybeUninit;
667 ///
668 /// let mut x = MaybeUninit::<u32>::uninit();
669 /// x.write(13);
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);
674 ///
675 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
676 /// x.write(None);
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);
681 /// ```
682 ///
683 /// *Incorrect* usage of this method:
684 ///
685 /// ```rust,no_run
686 /// use std::mem::MaybeUninit;
687 ///
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!
694 /// ```
695 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")]
696 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init_read", issue = "63567")]
697 #[inline(always)]
698 #[track_caller]
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.
702 unsafe {
703 intrinsics::assert_inhabited::<T>();
704 self.as_ptr().read()
705 }
706 }
707
708 /// Drops the contained value in place.
709 ///
710 /// If you have ownership of the `MaybeUninit`, you can also use
711 /// [`assume_init`] as an alternative.
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
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.
727 ///
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()) }
736 }
737
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()`).
743 ///
744 /// # Safety
745 ///
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
755 /// use std::mem::MaybeUninit;
756 ///
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()
765 /// };
766 /// assert_eq!(x, &vec![1, 2, 3]);
767 /// ```
768 ///
769 /// ### *Incorrect* usages of this method:
770 ///
771 /// ```rust,no_run
772 /// use std::mem::MaybeUninit;
773 ///
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. ⚠️
777 /// ```
778 ///
779 /// ```rust,no_run
780 /// use std::{cell::Cell, mem::MaybeUninit};
781 ///
782 /// let b = MaybeUninit::<Cell<bool>>::uninit();
783 /// // Initialize the `MaybeUninit` using `Cell::set`:
784 /// unsafe {
785 /// b.assume_init_ref().set(true);
786 /// // ^^^^^^^^^^^^^^^
787 /// // Reference to an uninitialized `Cell<bool>`: UB!
788 /// }
789 /// ```
790 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
791 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_ref", since = "1.59.0")]
792 #[inline(always)]
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.
796 unsafe {
797 intrinsics::assert_inhabited::<T>();
798 &*self.as_ptr()
799 }
800 }
801
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()`).
807 ///
808 /// # Safety
809 ///
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`.
814 ///
815 /// # Examples
816 ///
817 /// ### Correct usage of this method:
818 ///
819 /// ```rust
820 /// # #![allow(unexpected_cfgs)]
821 /// use std::mem::MaybeUninit;
822 ///
823 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] }
824 /// # #[cfg(FALSE)]
825 /// extern "C" {
826 /// /// Initializes *all* the bytes of the input buffer.
827 /// fn initialize_buffer(buf: *mut [u8; 1024]);
828 /// }
829 ///
830 /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit();
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.
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()
841 /// };
842 ///
843 /// // Now we can use `buf` as a normal slice:
844 /// buf.sort_unstable();
845 /// assert!(
846 /// buf.windows(2).all(|pair| pair[0] <= pair[1]),
847 /// "buffer is sorted",
848 /// );
849 /// ```
850 ///
851 /// ### *Incorrect* usages of this method:
852 ///
853 /// You cannot use `.assume_init_mut()` to initialize a value:
854 ///
855 /// ```rust,no_run
856 /// use std::mem::MaybeUninit;
857 ///
858 /// let mut b = MaybeUninit::<bool>::uninit();
859 /// unsafe {
860 /// *b.assume_init_mut() = true;
861 /// // We have created a (mutable) reference to an uninitialized `bool`!
862 /// // This is undefined behavior. ⚠️
863 /// }
864 /// ```
865 ///
866 /// For instance, you cannot [`Read`] into an uninitialized buffer:
867 ///
868 /// [`Read`]: ../../std/io/trait.Read.html
869 ///
870 /// ```rust,no_run
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();
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() })
881 /// }
882 /// ```
883 ///
884 /// Nor can you use direct field access to do field-by-field gradual initialization:
885 ///
886 /// ```rust,no_run
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();
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()
905 /// };
906 /// ```
907 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")]
908 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
909 #[inline(always)]
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.
913 unsafe {
914 intrinsics::assert_inhabited::<T>();
915 &mut *self.as_mut_ptr()
916 }
917 }
918
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();
934 /// array[0].write(0);
935 /// array[1].write(1);
936 /// array[2].write(2);
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 = "96097")]
946 #[rustc_const_unstable(feature = "const_maybe_uninit_array_assume_init", issue = "96097")]
947 #[inline(always)]
948 #[track_caller]
949 pub const unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] {
950 // SAFETY:
951 // * The caller guarantees that all elements of the array are initialized
952 // * `MaybeUninit<T>` and T are guaranteed to have the same layout
953 // * `MaybeUninit` does not drop, so there are no double-frees
954 // And thus the conversion is safe
955 let ret = unsafe {
956 intrinsics::assert_inhabited::<[T; N]>();
957 (&array as *const _ as *const [T; N]).read()
958 };
959
960 // FIXME: required to avoid `~const Destruct` bound
961 super::forget(array);
962 ret
963 }
964
965 /// Assuming all the elements are initialized, get a slice to them.
966 ///
967 /// # Safety
968 ///
969 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
970 /// really are in an initialized state.
971 /// Calling this when the content is not yet fully initialized causes undefined behavior.
972 ///
973 /// See [`assume_init_ref`] for more details and examples.
974 ///
975 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref
976 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
977 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
978 #[inline(always)]
979 pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] {
980 // SAFETY: casting `slice` to a `*const [T]` is safe since the caller guarantees that
981 // `slice` is initialized, and `MaybeUninit` is guaranteed to have the same layout as `T`.
982 // The pointer obtained is valid since it refers to memory owned by `slice` which is a
983 // reference and thus guaranteed to be valid for reads.
984 unsafe { &*(slice as *const [Self] as *const [T]) }
985 }
986
987 /// Assuming all the elements are initialized, get a mutable slice to them.
988 ///
989 /// # Safety
990 ///
991 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
992 /// really are in an initialized state.
993 /// Calling this when the content is not yet fully initialized causes undefined behavior.
994 ///
995 /// See [`assume_init_mut`] for more details and examples.
996 ///
997 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut
998 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
999 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
1000 #[inline(always)]
1001 pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] {
1002 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a
1003 // mutable reference which is also guaranteed to be valid for writes.
1004 unsafe { &mut *(slice as *mut [Self] as *mut [T]) }
1005 }
1006
1007 /// Gets a pointer to the first element of the array.
1008 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
1009 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
1010 #[inline(always)]
1011 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T {
1012 this.as_ptr() as *const T
1013 }
1014
1015 /// Gets a mutable pointer to the first element of the array.
1016 #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
1017 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")]
1018 #[inline(always)]
1019 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T {
1020 this.as_mut_ptr() as *mut T
1021 }
1022
1023 /// Copies the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
1024 ///
1025 /// If `T` does not implement `Copy`, use [`write_slice_cloned`]
1026 ///
1027 /// This is similar to [`slice::copy_from_slice`].
1028 ///
1029 /// # Panics
1030 ///
1031 /// This function will panic if the two slices have different lengths.
1032 ///
1033 /// # Examples
1034 ///
1035 /// ```
1036 /// #![feature(maybe_uninit_write_slice)]
1037 /// use std::mem::MaybeUninit;
1038 ///
1039 /// let mut dst = [MaybeUninit::uninit(); 32];
1040 /// let src = [0; 32];
1041 ///
1042 /// let init = MaybeUninit::write_slice(&mut dst, &src);
1043 ///
1044 /// assert_eq!(init, src);
1045 /// ```
1046 ///
1047 /// ```
1048 /// #![feature(maybe_uninit_write_slice)]
1049 /// use std::mem::MaybeUninit;
1050 ///
1051 /// let mut vec = Vec::with_capacity(32);
1052 /// let src = [0; 16];
1053 ///
1054 /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);
1055 ///
1056 /// // SAFETY: we have just copied all the elements of len into the spare capacity
1057 /// // the first src.len() elements of the vec are valid now.
1058 /// unsafe {
1059 /// vec.set_len(src.len());
1060 /// }
1061 ///
1062 /// assert_eq!(vec, src);
1063 /// ```
1064 ///
1065 /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned
1066 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1067 pub fn write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1068 where
1069 T: Copy,
1070 {
1071 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout
1072 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) };
1073
1074 this.copy_from_slice(uninit_src);
1075
1076 // SAFETY: Valid elements have just been copied into `this` so it is initialized
1077 unsafe { MaybeUninit::slice_assume_init_mut(this) }
1078 }
1079
1080 /// Clones the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`.
1081 /// Any already initialized elements will not be dropped.
1082 ///
1083 /// If `T` implements `Copy`, use [`write_slice`]
1084 ///
1085 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements.
1086 ///
1087 /// # Panics
1088 ///
1089 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics.
1090 ///
1091 /// If there is a panic, the already cloned elements will be dropped.
1092 ///
1093 /// # Examples
1094 ///
1095 /// ```
1096 /// #![feature(maybe_uninit_write_slice)]
1097 /// use std::mem::MaybeUninit;
1098 ///
1099 /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()];
1100 /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()];
1101 ///
1102 /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src);
1103 ///
1104 /// assert_eq!(init, src);
1105 /// ```
1106 ///
1107 /// ```
1108 /// #![feature(maybe_uninit_write_slice)]
1109 /// use std::mem::MaybeUninit;
1110 ///
1111 /// let mut vec = Vec::with_capacity(32);
1112 /// let src = ["rust", "is", "a", "pretty", "cool", "language"];
1113 ///
1114 /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src);
1115 ///
1116 /// // SAFETY: we have just cloned all the elements of len into the spare capacity
1117 /// // the first src.len() elements of the vec are valid now.
1118 /// unsafe {
1119 /// vec.set_len(src.len());
1120 /// }
1121 ///
1122 /// assert_eq!(vec, src);
1123 /// ```
1124 ///
1125 /// [`write_slice`]: MaybeUninit::write_slice
1126 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")]
1127 pub fn write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]
1128 where
1129 T: Clone,
1130 {
1131 // unlike copy_from_slice this does not call clone_from_slice on the slice
1132 // this is because `MaybeUninit<T: Clone>` does not implement Clone.
1133
1134 struct Guard<'a, T> {
1135 slice: &'a mut [MaybeUninit<T>],
1136 initialized: usize,
1137 }
1138
1139 impl<'a, T> Drop for Guard<'a, T> {
1140 fn drop(&mut self) {
1141 let initialized_part = &mut self.slice[..self.initialized];
1142 // SAFETY: this raw slice will contain only initialized objects
1143 // that's why, it is allowed to drop it.
1144 unsafe {
1145 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part));
1146 }
1147 }
1148 }
1149
1150 assert_eq!(this.len(), src.len(), "destination and source slices have different lengths");
1151 // NOTE: We need to explicitly slice them to the same length
1152 // for bounds checking to be elided, and the optimizer will
1153 // generate memcpy for simple cases (for example T = u8).
1154 let len = this.len();
1155 let src = &src[..len];
1156
1157 // guard is needed b/c panic might happen during a clone
1158 let mut guard = Guard { slice: this, initialized: 0 };
1159
1160 for i in 0..len {
1161 guard.slice[i].write(src[i].clone());
1162 guard.initialized += 1;
1163 }
1164
1165 super::forget(guard);
1166
1167 // SAFETY: Valid elements have just been written into `this` so it is initialized
1168 unsafe { MaybeUninit::slice_assume_init_mut(this) }
1169 }
1170
1171 /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes.
1172 ///
1173 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1174 /// contain padding bytes which are left uninitialized.
1175 ///
1176 /// # Examples
1177 ///
1178 /// ```
1179 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_slice)]
1180 /// use std::mem::MaybeUninit;
1181 ///
1182 /// let val = 0x12345678i32;
1183 /// let uninit = MaybeUninit::new(val);
1184 /// let uninit_bytes = uninit.as_bytes();
1185 /// let bytes = unsafe { MaybeUninit::slice_assume_init_ref(uninit_bytes) };
1186 /// assert_eq!(bytes, val.to_ne_bytes());
1187 /// ```
1188 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1189 pub fn as_bytes(&self) -> &[MaybeUninit<u8>] {
1190 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1191 unsafe {
1192 slice::from_raw_parts(self.as_ptr() as *const MaybeUninit<u8>, mem::size_of::<T>())
1193 }
1194 }
1195
1196 /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized
1197 /// bytes.
1198 ///
1199 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1200 /// contain padding bytes which are left uninitialized.
1201 ///
1202 /// # Examples
1203 ///
1204 /// ```
1205 /// #![feature(maybe_uninit_as_bytes)]
1206 /// use std::mem::MaybeUninit;
1207 ///
1208 /// let val = 0x12345678i32;
1209 /// let mut uninit = MaybeUninit::new(val);
1210 /// let uninit_bytes = uninit.as_bytes_mut();
1211 /// if cfg!(target_endian = "little") {
1212 /// uninit_bytes[0].write(0xcd);
1213 /// } else {
1214 /// uninit_bytes[3].write(0xcd);
1215 /// }
1216 /// let val2 = unsafe { uninit.assume_init() };
1217 /// assert_eq!(val2, 0x123456cd);
1218 /// ```
1219 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1220 pub fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1221 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1222 unsafe {
1223 slice::from_raw_parts_mut(
1224 self.as_mut_ptr() as *mut MaybeUninit<u8>,
1225 mem::size_of::<T>(),
1226 )
1227 }
1228 }
1229
1230 /// Returns the contents of this slice of `MaybeUninit` as a slice of potentially uninitialized
1231 /// bytes.
1232 ///
1233 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1234 /// contain padding bytes which are left uninitialized.
1235 ///
1236 /// # Examples
1237 ///
1238 /// ```
1239 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)]
1240 /// use std::mem::MaybeUninit;
1241 ///
1242 /// let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)];
1243 /// let uninit_bytes = MaybeUninit::slice_as_bytes(&uninit);
1244 /// let bytes = unsafe { MaybeUninit::slice_assume_init_ref(&uninit_bytes) };
1245 /// let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap());
1246 /// let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap());
1247 /// assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]);
1248 /// ```
1249 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1250 pub fn slice_as_bytes(this: &[MaybeUninit<T>]) -> &[MaybeUninit<u8>] {
1251 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1252 unsafe {
1253 slice::from_raw_parts(
1254 this.as_ptr() as *const MaybeUninit<u8>,
1255 this.len() * mem::size_of::<T>(),
1256 )
1257 }
1258 }
1259
1260 /// Returns the contents of this mutable slice of `MaybeUninit` as a mutable slice of
1261 /// potentially uninitialized bytes.
1262 ///
1263 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still
1264 /// contain padding bytes which are left uninitialized.
1265 ///
1266 /// # Examples
1267 ///
1268 /// ```
1269 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)]
1270 /// use std::mem::MaybeUninit;
1271 ///
1272 /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()];
1273 /// let uninit_bytes = MaybeUninit::slice_as_bytes_mut(&mut uninit);
1274 /// MaybeUninit::write_slice(uninit_bytes, &[0x12, 0x34, 0x56, 0x78]);
1275 /// let vals = unsafe { MaybeUninit::slice_assume_init_ref(&uninit) };
1276 /// if cfg!(target_endian = "little") {
1277 /// assert_eq!(vals, &[0x3412u16, 0x7856u16]);
1278 /// } else {
1279 /// assert_eq!(vals, &[0x1234u16, 0x5678u16]);
1280 /// }
1281 /// ```
1282 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")]
1283 pub fn slice_as_bytes_mut(this: &mut [MaybeUninit<T>]) -> &mut [MaybeUninit<u8>] {
1284 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes
1285 unsafe {
1286 slice::from_raw_parts_mut(
1287 this.as_mut_ptr() as *mut MaybeUninit<u8>,
1288 this.len() * mem::size_of::<T>(),
1289 )
1290 }
1291 }
1292 }