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 /// On top of that, remember that most types have additional invariants beyond merely 58 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`] 59 /// is considered initialized (under the current implementation; this does not constitute 60 /// a stable guarantee) because the only requirement the compiler knows about it 61 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause 62 /// *immediate* undefined behavior, but will cause undefined behavior with most 63 /// safe operations (including dropping it). 64 /// 65 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html 66 /// 67 /// # Examples 68 /// 69 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data. 70 /// It is a signal to the compiler indicating that the data here might *not* 71 /// be initialized: 72 /// 73 /// ```rust 74 /// use std::mem::MaybeUninit; 75 /// 76 /// // Create an explicitly uninitialized reference. The compiler knows that data inside 77 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB: 78 /// let mut x = MaybeUninit::<&i32>::uninit(); 79 /// // Set it to a valid value. 80 /// x.write(&0); 81 /// // Extract the initialized data -- this is only allowed *after* properly 82 /// // initializing `x`! 83 /// let x = unsafe { x.assume_init() }; 84 /// ``` 85 /// 86 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code. 87 /// 88 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without 89 /// any of the run-time tracking and without any of the safety checks. 90 /// 91 /// ## out-pointers 92 /// 93 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data 94 /// from a function, pass it a pointer to some (uninitialized) memory to put the 95 /// result into. This can be useful when it is important for the caller to control 96 /// how the memory the result is stored in gets allocated, and you want to avoid 97 /// unnecessary moves. 98 /// 99 /// ``` 100 /// use std::mem::MaybeUninit; 101 /// 102 /// unsafe fn make_vec(out: *mut Vec<i32>) { 103 /// // `write` does not drop the old contents, which is important. 104 /// out.write(vec![1, 2, 3]); 105 /// } 106 /// 107 /// let mut v = MaybeUninit::uninit(); 108 /// unsafe { make_vec(v.as_mut_ptr()); } 109 /// // Now we know `v` is initialized! This also makes sure the vector gets 110 /// // properly dropped. 111 /// let v = unsafe { v.assume_init() }; 112 /// assert_eq!(&v, &[1, 2, 3]); 113 /// ``` 114 /// 115 /// ## Initializing an array element-by-element 116 /// 117 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element: 118 /// 119 /// ``` 120 /// use std::mem::{self, MaybeUninit}; 121 /// 122 /// let data = { 123 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is 124 /// // safe because the type we are claiming to have initialized here is a 125 /// // bunch of `MaybeUninit`s, which do not require initialization. 126 /// let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe { 127 /// MaybeUninit::uninit().assume_init() 128 /// }; 129 /// 130 /// // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop, 131 /// // we have a memory leak, but there is no memory safety issue. 132 /// for elem in &mut data[..] { 133 /// elem.write(vec![42]); 134 /// } 135 /// 136 /// // Everything is initialized. Transmute the array to the 137 /// // initialized type. 138 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) } 139 /// }; 140 /// 141 /// assert_eq!(&data[0], &[42]); 142 /// ``` 143 /// 144 /// You can also work with partially initialized arrays, which could 145 /// be found in low-level datastructures. 146 /// 147 /// ``` 148 /// use std::mem::MaybeUninit; 149 /// 150 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is 151 /// // safe because the type we are claiming to have initialized here is a 152 /// // bunch of `MaybeUninit`s, which do not require initialization. 153 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() }; 154 /// // Count the number of elements we have assigned. 155 /// let mut data_len: usize = 0; 156 /// 157 /// for elem in &mut data[0..500] { 158 /// elem.write(String::from("hello")); 159 /// data_len += 1; 160 /// } 161 /// 162 /// // For each item in the array, drop if we allocated it. 163 /// for elem in &mut data[0..data_len] { 164 /// unsafe { elem.assume_init_drop(); } 165 /// } 166 /// ``` 167 /// 168 /// ## Initializing a struct field-by-field 169 /// 170 /// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field: 171 /// 172 /// ```rust 173 /// use std::mem::MaybeUninit; 174 /// use std::ptr::addr_of_mut; 175 /// 176 /// #[derive(Debug, PartialEq)] 177 /// pub struct Foo { 178 /// name: String, 179 /// list: Vec<u8>, 180 /// } 181 /// 182 /// let foo = { 183 /// let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit(); 184 /// let ptr = uninit.as_mut_ptr(); 185 /// 186 /// // Initializing the `name` field 187 /// // Using `write` instead of assignment via `=` to not call `drop` on the 188 /// // old, uninitialized value. 189 /// unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); } 190 /// 191 /// // Initializing the `list` field 192 /// // If there is a panic here, then the `String` in the `name` field leaks. 193 /// unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); } 194 /// 195 /// // All the fields are initialized, so we call `assume_init` to get an initialized Foo. 196 /// unsafe { uninit.assume_init() } 197 /// }; 198 /// 199 /// assert_eq!( 200 /// foo, 201 /// Foo { 202 /// name: "Bob".to_string(), 203 /// list: vec![0, 1, 2] 204 /// } 205 /// ); 206 /// ``` 207 /// [`std::ptr::addr_of_mut`]: crate::ptr::addr_of_mut 208 /// [ub]: ../../reference/behavior-considered-undefined.html 209 /// 210 /// # Layout 211 /// 212 /// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`: 213 /// 214 /// ```rust 215 /// use std::mem::{MaybeUninit, size_of, align_of}; 216 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>()); 217 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>()); 218 /// ``` 219 /// 220 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same 221 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as 222 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit 223 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling 224 /// optimizations, potentially resulting in a larger size: 225 /// 226 /// ```rust 227 /// # use std::mem::{MaybeUninit, size_of}; 228 /// assert_eq!(size_of::<Option<bool>>(), 1); 229 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2); 230 /// ``` 231 /// 232 /// If `T` is FFI-safe, then so is `MaybeUninit<T>`. 233 /// 234 /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size, 235 /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and 236 /// `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type 237 /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`. 238 /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the 239 /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact 240 /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not 241 /// remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has 242 /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that 243 /// guarantee may evolve. 244 #[stable(feature = "maybe_uninit", since = "1.36.0")] 245 // Lang item so we can wrap other types in it. This is useful for generators. 246 #[lang = "maybe_uninit"] 247 #[derive(Copy)] 248 #[repr(transparent)] 249 pub union MaybeUninit<T> { 250 uninit: (), 251 value: ManuallyDrop<T>, 252 } 253 254 #[stable(feature = "maybe_uninit", since = "1.36.0")] 255 impl<T: Copy> Clone for MaybeUninit<T> { 256 #[inline(always)] clone(&self) -> Self257 fn clone(&self) -> Self { 258 // Not calling `T::clone()`, we cannot know if we are initialized enough for that. 259 *self 260 } 261 } 262 263 #[stable(feature = "maybe_uninit_debug", since = "1.41.0")] 264 impl<T> fmt::Debug for MaybeUninit<T> { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 266 f.pad(type_name::<Self>()) 267 } 268 } 269 270 impl<T> MaybeUninit<T> { 271 /// Creates a new `MaybeUninit<T>` initialized with the given value. 272 /// It is safe to call [`assume_init`] on the return value of this function. 273 /// 274 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code. 275 /// It is your responsibility to make sure `T` gets dropped if it got initialized. 276 /// 277 /// # Example 278 /// 279 /// ``` 280 /// use std::mem::MaybeUninit; 281 /// 282 /// let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]); 283 /// ``` 284 /// 285 /// [`assume_init`]: MaybeUninit::assume_init 286 #[stable(feature = "maybe_uninit", since = "1.36.0")] 287 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")] 288 #[must_use = "use `forget` to avoid running Drop code"] 289 #[inline(always)] new(val: T) -> MaybeUninit<T>290 pub const fn new(val: T) -> MaybeUninit<T> { 291 MaybeUninit { value: ManuallyDrop::new(val) } 292 } 293 294 /// Creates a new `MaybeUninit<T>` in an uninitialized state. 295 /// 296 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code. 297 /// It is your responsibility to make sure `T` gets dropped if it got initialized. 298 /// 299 /// See the [type-level documentation][MaybeUninit] for some examples. 300 /// 301 /// # Example 302 /// 303 /// ``` 304 /// use std::mem::MaybeUninit; 305 /// 306 /// let v: MaybeUninit<String> = MaybeUninit::uninit(); 307 /// ``` 308 #[stable(feature = "maybe_uninit", since = "1.36.0")] 309 #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")] 310 #[must_use] 311 #[inline(always)] 312 #[rustc_diagnostic_item = "maybe_uninit_uninit"] uninit() -> MaybeUninit<T>313 pub const fn uninit() -> MaybeUninit<T> { 314 MaybeUninit { uninit: () } 315 } 316 317 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state. 318 /// 319 /// Note: in a future Rust version this method may become unnecessary 320 /// when Rust allows 321 /// [inline const expressions](https://github.com/rust-lang/rust/issues/76001). 322 /// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`. 323 /// 324 /// # Examples 325 /// 326 /// ```no_run 327 /// #![feature(maybe_uninit_uninit_array, maybe_uninit_slice)] 328 /// 329 /// use std::mem::MaybeUninit; 330 /// 331 /// extern "C" { 332 /// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize; 333 /// } 334 /// 335 /// /// Returns a (possibly smaller) slice of data that was actually read 336 /// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] { 337 /// unsafe { 338 /// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len()); 339 /// MaybeUninit::slice_assume_init_ref(&buf[..len]) 340 /// } 341 /// } 342 /// 343 /// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array(); 344 /// let data = read(&mut buf); 345 /// ``` 346 #[unstable(feature = "maybe_uninit_uninit_array", issue = "96097")] 347 #[rustc_const_unstable(feature = "const_maybe_uninit_uninit_array", issue = "96097")] 348 #[must_use] 349 #[inline(always)] uninit_array<const N: usize>() -> [Self; N]350 pub const fn uninit_array<const N: usize>() -> [Self; N] { 351 // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid. 352 unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() } 353 } 354 355 /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being 356 /// filled with `0` bytes. It depends on `T` whether that already makes for 357 /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized, 358 /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not 359 /// be null. 360 /// 361 /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code. 362 /// It is your responsibility to make sure `T` gets dropped if it got initialized. 363 /// 364 /// # Example 365 /// 366 /// Correct usage of this function: initializing a struct with zero, where all 367 /// fields of the struct can hold the bit-pattern 0 as a valid value. 368 /// 369 /// ```rust 370 /// use std::mem::MaybeUninit; 371 /// 372 /// let x = MaybeUninit::<(u8, bool)>::zeroed(); 373 /// let x = unsafe { x.assume_init() }; 374 /// assert_eq!(x, (0, false)); 375 /// ``` 376 /// 377 /// *Incorrect* usage of this function: calling `x.zeroed().assume_init()` 378 /// when `0` is not a valid bit-pattern for the type: 379 /// 380 /// ```rust,no_run 381 /// use std::mem::MaybeUninit; 382 /// 383 /// enum NotZero { One = 1, Two = 2 } 384 /// 385 /// let x = MaybeUninit::<(u8, NotZero)>::zeroed(); 386 /// let x = unsafe { x.assume_init() }; 387 /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant. 388 /// // This is undefined behavior. ⚠️ 389 /// ``` 390 #[stable(feature = "maybe_uninit", since = "1.36.0")] 391 #[rustc_const_unstable(feature = "const_maybe_uninit_zeroed", issue = "91850")] 392 #[must_use] 393 #[inline] 394 #[rustc_diagnostic_item = "maybe_uninit_zeroed"] zeroed() -> MaybeUninit<T>395 pub const fn zeroed() -> MaybeUninit<T> { 396 let mut u = MaybeUninit::<T>::uninit(); 397 // SAFETY: `u.as_mut_ptr()` points to allocated memory. 398 unsafe { 399 u.as_mut_ptr().write_bytes(0u8, 1); 400 } 401 u 402 } 403 404 /// Sets the value of the `MaybeUninit<T>`. 405 /// 406 /// This overwrites any previous value without dropping it, so be careful 407 /// not to use this twice unless you want to skip running the destructor. 408 /// For your convenience, this also returns a mutable reference to the 409 /// (now safely initialized) contents of `self`. 410 /// 411 /// As the content is stored inside a `MaybeUninit`, the destructor is not 412 /// run for the inner data if the MaybeUninit leaves scope without a call to 413 /// [`assume_init`], [`assume_init_drop`], or similar. Code that receives 414 /// the mutable reference returned by this function needs to keep this in 415 /// mind. The safety model of Rust regards leaks as safe, but they are 416 /// usually still undesirable. This being said, the mutable reference 417 /// behaves like any other mutable reference would, so assigning a new value 418 /// to it will drop the old content. 419 /// 420 /// [`assume_init`]: Self::assume_init 421 /// [`assume_init_drop`]: Self::assume_init_drop 422 /// 423 /// # Examples 424 /// 425 /// Correct usage of this method: 426 /// 427 /// ```rust 428 /// use std::mem::MaybeUninit; 429 /// 430 /// let mut x = MaybeUninit::<Vec<u8>>::uninit(); 431 /// 432 /// { 433 /// let hello = x.write((&b"Hello, world!").to_vec()); 434 /// // Setting hello does not leak prior allocations, but drops them 435 /// *hello = (&b"Hello").to_vec(); 436 /// hello[0] = 'h' as u8; 437 /// } 438 /// // x is initialized now: 439 /// let s = unsafe { x.assume_init() }; 440 /// assert_eq!(b"hello", s.as_slice()); 441 /// ``` 442 /// 443 /// This usage of the method causes a leak: 444 /// 445 /// ```rust 446 /// use std::mem::MaybeUninit; 447 /// 448 /// let mut x = MaybeUninit::<String>::uninit(); 449 /// 450 /// x.write("Hello".to_string()); 451 /// // This leaks the contained string: 452 /// x.write("hello".to_string()); 453 /// // x is initialized now: 454 /// let s = unsafe { x.assume_init() }; 455 /// ``` 456 /// 457 /// This method can be used to avoid unsafe in some cases. The example below 458 /// shows a part of an implementation of a fixed sized arena that lends out 459 /// pinned references. 460 /// With `write`, we can avoid the need to write through a raw pointer: 461 /// 462 /// ```rust 463 /// use core::pin::Pin; 464 /// use core::mem::MaybeUninit; 465 /// 466 /// struct PinArena<T> { 467 /// memory: Box<[MaybeUninit<T>]>, 468 /// len: usize, 469 /// } 470 /// 471 /// impl <T> PinArena<T> { 472 /// pub fn capacity(&self) -> usize { 473 /// self.memory.len() 474 /// } 475 /// pub fn push(&mut self, val: T) -> Pin<&mut T> { 476 /// if self.len >= self.capacity() { 477 /// panic!("Attempted to push to a full pin arena!"); 478 /// } 479 /// let ref_ = self.memory[self.len].write(val); 480 /// self.len += 1; 481 /// unsafe { Pin::new_unchecked(ref_) } 482 /// } 483 /// } 484 /// ``` 485 #[stable(feature = "maybe_uninit_write", since = "1.55.0")] 486 #[rustc_const_unstable(feature = "const_maybe_uninit_write", issue = "63567")] 487 #[inline(always)] write(&mut self, val: T) -> &mut T488 pub const fn write(&mut self, val: T) -> &mut T { 489 *self = MaybeUninit::new(val); 490 // SAFETY: We just initialized this value. 491 unsafe { self.assume_init_mut() } 492 } 493 494 /// Gets a pointer to the contained value. Reading from this pointer or turning it 495 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized. 496 /// Writing to memory that this pointer (non-transitively) points to is undefined behavior 497 /// (except inside an `UnsafeCell<T>`). 498 /// 499 /// # Examples 500 /// 501 /// Correct usage of this method: 502 /// 503 /// ```rust 504 /// use std::mem::MaybeUninit; 505 /// 506 /// let mut x = MaybeUninit::<Vec<u32>>::uninit(); 507 /// x.write(vec![0, 1, 2]); 508 /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it. 509 /// let x_vec = unsafe { &*x.as_ptr() }; 510 /// assert_eq!(x_vec.len(), 3); 511 /// ``` 512 /// 513 /// *Incorrect* usage of this method: 514 /// 515 /// ```rust,no_run 516 /// use std::mem::MaybeUninit; 517 /// 518 /// let x = MaybeUninit::<Vec<u32>>::uninit(); 519 /// let x_vec = unsafe { &*x.as_ptr() }; 520 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️ 521 /// ``` 522 /// 523 /// (Notice that the rules around references to uninitialized data are not finalized yet, but 524 /// until they are, it is advisable to avoid them.) 525 #[stable(feature = "maybe_uninit", since = "1.36.0")] 526 #[rustc_const_stable(feature = "const_maybe_uninit_as_ptr", since = "1.59.0")] 527 #[inline(always)] as_ptr(&self) -> *const T528 pub const fn as_ptr(&self) -> *const T { 529 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer. 530 self as *const _ as *const T 531 } 532 533 /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it 534 /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized. 535 /// 536 /// # Examples 537 /// 538 /// Correct usage of this method: 539 /// 540 /// ```rust 541 /// use std::mem::MaybeUninit; 542 /// 543 /// let mut x = MaybeUninit::<Vec<u32>>::uninit(); 544 /// x.write(vec![0, 1, 2]); 545 /// // Create a reference into the `MaybeUninit<Vec<u32>>`. 546 /// // This is okay because we initialized it. 547 /// let x_vec = unsafe { &mut *x.as_mut_ptr() }; 548 /// x_vec.push(3); 549 /// assert_eq!(x_vec.len(), 4); 550 /// ``` 551 /// 552 /// *Incorrect* usage of this method: 553 /// 554 /// ```rust,no_run 555 /// use std::mem::MaybeUninit; 556 /// 557 /// let mut x = MaybeUninit::<Vec<u32>>::uninit(); 558 /// let x_vec = unsafe { &mut *x.as_mut_ptr() }; 559 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️ 560 /// ``` 561 /// 562 /// (Notice that the rules around references to uninitialized data are not finalized yet, but 563 /// until they are, it is advisable to avoid them.) 564 #[stable(feature = "maybe_uninit", since = "1.36.0")] 565 #[rustc_const_unstable(feature = "const_maybe_uninit_as_mut_ptr", issue = "75251")] 566 #[inline(always)] as_mut_ptr(&mut self) -> *mut T567 pub const fn as_mut_ptr(&mut self) -> *mut T { 568 // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer. 569 self as *mut _ as *mut T 570 } 571 572 /// Extracts the value from the `MaybeUninit<T>` container. This is a great way 573 /// to ensure that the data will get dropped, because the resulting `T` is 574 /// subject to the usual drop handling. 575 /// 576 /// # Safety 577 /// 578 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized 579 /// state. Calling this when the content is not yet fully initialized causes immediate undefined 580 /// behavior. The [type-level documentation][inv] contains more information about 581 /// this initialization invariant. 582 /// 583 /// [inv]: #initialization-invariant 584 /// 585 /// On top of that, remember that most types have additional invariants beyond merely 586 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`] 587 /// is considered initialized (under the current implementation; this does not constitute 588 /// a stable guarantee) because the only requirement the compiler knows about it 589 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause 590 /// *immediate* undefined behavior, but will cause undefined behavior with most 591 /// safe operations (including dropping it). 592 /// 593 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html 594 /// 595 /// # Examples 596 /// 597 /// Correct usage of this method: 598 /// 599 /// ```rust 600 /// use std::mem::MaybeUninit; 601 /// 602 /// let mut x = MaybeUninit::<bool>::uninit(); 603 /// x.write(true); 604 /// let x_init = unsafe { x.assume_init() }; 605 /// assert_eq!(x_init, true); 606 /// ``` 607 /// 608 /// *Incorrect* usage of this method: 609 /// 610 /// ```rust,no_run 611 /// use std::mem::MaybeUninit; 612 /// 613 /// let x = MaybeUninit::<Vec<u32>>::uninit(); 614 /// let x_init = unsafe { x.assume_init() }; 615 /// // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️ 616 /// ``` 617 #[stable(feature = "maybe_uninit", since = "1.36.0")] 618 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_by_value", since = "1.59.0")] 619 #[inline(always)] 620 #[rustc_diagnostic_item = "assume_init"] 621 #[track_caller] assume_init(self) -> T622 pub const unsafe fn assume_init(self) -> T { 623 // SAFETY: the caller must guarantee that `self` is initialized. 624 // This also means that `self` must be a `value` variant. 625 unsafe { 626 intrinsics::assert_inhabited::<T>(); 627 ManuallyDrop::into_inner(self.value) 628 } 629 } 630 631 /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject 632 /// to the usual drop handling. 633 /// 634 /// Whenever possible, it is preferable to use [`assume_init`] instead, which 635 /// prevents duplicating the content of the `MaybeUninit<T>`. 636 /// 637 /// # Safety 638 /// 639 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized 640 /// state. Calling this when the content is not yet fully initialized causes undefined 641 /// behavior. The [type-level documentation][inv] contains more information about 642 /// this initialization invariant. 643 /// 644 /// Moreover, similar to the [`ptr::read`] function, this function creates a 645 /// bitwise copy of the contents, regardless whether the contained type 646 /// implements the [`Copy`] trait or not. When using multiple copies of the 647 /// data (by calling `assume_init_read` multiple times, or first calling 648 /// `assume_init_read` and then [`assume_init`]), it is your responsibility 649 /// to ensure that data may indeed be duplicated. 650 /// 651 /// [inv]: #initialization-invariant 652 /// [`assume_init`]: MaybeUninit::assume_init 653 /// 654 /// # Examples 655 /// 656 /// Correct usage of this method: 657 /// 658 /// ```rust 659 /// use std::mem::MaybeUninit; 660 /// 661 /// let mut x = MaybeUninit::<u32>::uninit(); 662 /// x.write(13); 663 /// let x1 = unsafe { x.assume_init_read() }; 664 /// // `u32` is `Copy`, so we may read multiple times. 665 /// let x2 = unsafe { x.assume_init_read() }; 666 /// assert_eq!(x1, x2); 667 /// 668 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit(); 669 /// x.write(None); 670 /// let x1 = unsafe { x.assume_init_read() }; 671 /// // Duplicating a `None` value is okay, so we may read multiple times. 672 /// let x2 = unsafe { x.assume_init_read() }; 673 /// assert_eq!(x1, x2); 674 /// ``` 675 /// 676 /// *Incorrect* usage of this method: 677 /// 678 /// ```rust,no_run 679 /// use std::mem::MaybeUninit; 680 /// 681 /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit(); 682 /// x.write(Some(vec![0, 1, 2])); 683 /// let x1 = unsafe { x.assume_init_read() }; 684 /// let x2 = unsafe { x.assume_init_read() }; 685 /// // We now created two copies of the same vector, leading to a double-free ⚠️ when 686 /// // they both get dropped! 687 /// ``` 688 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")] 689 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init_read", issue = "63567")] 690 #[inline(always)] 691 #[track_caller] assume_init_read(&self) -> T692 pub const unsafe fn assume_init_read(&self) -> T { 693 // SAFETY: the caller must guarantee that `self` is initialized. 694 // Reading from `self.as_ptr()` is safe since `self` should be initialized. 695 unsafe { 696 intrinsics::assert_inhabited::<T>(); 697 self.as_ptr().read() 698 } 699 } 700 701 /// Drops the contained value in place. 702 /// 703 /// If you have ownership of the `MaybeUninit`, you can also use 704 /// [`assume_init`] as an alternative. 705 /// 706 /// # Safety 707 /// 708 /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is 709 /// in an initialized state. Calling this when the content is not yet fully 710 /// initialized causes undefined behavior. 711 /// 712 /// On top of that, all additional invariants of the type `T` must be 713 /// satisfied, as the `Drop` implementation of `T` (or its members) may 714 /// rely on this. For example, setting a [`Vec<T>`] to an invalid but 715 /// non-null address makes it initialized (under the current implementation; 716 /// this does not constitute a stable guarantee), because the only 717 /// requirement the compiler knows about it is that the data pointer must be 718 /// non-null. Dropping such a `Vec<T>` however will cause undefined 719 /// behaviour. 720 /// 721 /// [`assume_init`]: MaybeUninit::assume_init 722 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html 723 #[stable(feature = "maybe_uninit_extra", since = "1.60.0")] assume_init_drop(&mut self)724 pub unsafe fn assume_init_drop(&mut self) { 725 // SAFETY: the caller must guarantee that `self` is initialized and 726 // satisfies all invariants of `T`. 727 // Dropping the value in place is safe if that is the case. 728 unsafe { ptr::drop_in_place(self.as_mut_ptr()) } 729 } 730 731 /// Gets a shared reference to the contained value. 732 /// 733 /// This can be useful when we want to access a `MaybeUninit` that has been 734 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use 735 /// of `.assume_init()`). 736 /// 737 /// # Safety 738 /// 739 /// Calling this when the content is not yet fully initialized causes undefined 740 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really 741 /// is in an initialized state. 742 /// 743 /// # Examples 744 /// 745 /// ### Correct usage of this method: 746 /// 747 /// ```rust 748 /// use std::mem::MaybeUninit; 749 /// 750 /// let mut x = MaybeUninit::<Vec<u32>>::uninit(); 751 /// // Initialize `x`: 752 /// x.write(vec![1, 2, 3]); 753 /// // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to 754 /// // create a shared reference to it: 755 /// let x: &Vec<u32> = unsafe { 756 /// // SAFETY: `x` has been initialized. 757 /// x.assume_init_ref() 758 /// }; 759 /// assert_eq!(x, &vec![1, 2, 3]); 760 /// ``` 761 /// 762 /// ### *Incorrect* usages of this method: 763 /// 764 /// ```rust,no_run 765 /// use std::mem::MaybeUninit; 766 /// 767 /// let x = MaybeUninit::<Vec<u32>>::uninit(); 768 /// let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() }; 769 /// // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️ 770 /// ``` 771 /// 772 /// ```rust,no_run 773 /// use std::{cell::Cell, mem::MaybeUninit}; 774 /// 775 /// let b = MaybeUninit::<Cell<bool>>::uninit(); 776 /// // Initialize the `MaybeUninit` using `Cell::set`: 777 /// unsafe { 778 /// b.assume_init_ref().set(true); 779 /// // ^^^^^^^^^^^^^^^ 780 /// // Reference to an uninitialized `Cell<bool>`: UB! 781 /// } 782 /// ``` 783 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")] 784 #[rustc_const_stable(feature = "const_maybe_uninit_assume_init_ref", since = "1.59.0")] 785 #[inline(always)] assume_init_ref(&self) -> &T786 pub const unsafe fn assume_init_ref(&self) -> &T { 787 // SAFETY: the caller must guarantee that `self` is initialized. 788 // This also means that `self` must be a `value` variant. 789 unsafe { 790 intrinsics::assert_inhabited::<T>(); 791 &*self.as_ptr() 792 } 793 } 794 795 /// Gets a mutable (unique) reference to the contained value. 796 /// 797 /// This can be useful when we want to access a `MaybeUninit` that has been 798 /// initialized but don't have ownership of the `MaybeUninit` (preventing the use 799 /// of `.assume_init()`). 800 /// 801 /// # Safety 802 /// 803 /// Calling this when the content is not yet fully initialized causes undefined 804 /// behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really 805 /// is in an initialized state. For instance, `.assume_init_mut()` cannot be used to 806 /// initialize a `MaybeUninit`. 807 /// 808 /// # Examples 809 /// 810 /// ### Correct usage of this method: 811 /// 812 /// ```rust 813 /// # #![allow(unexpected_cfgs)] 814 /// use std::mem::MaybeUninit; 815 /// 816 /// # unsafe extern "C" fn initialize_buffer(buf: *mut [u8; 1024]) { *buf = [0; 1024] } 817 /// # #[cfg(FALSE)] 818 /// extern "C" { 819 /// /// Initializes *all* the bytes of the input buffer. 820 /// fn initialize_buffer(buf: *mut [u8; 1024]); 821 /// } 822 /// 823 /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit(); 824 /// 825 /// // Initialize `buf`: 826 /// unsafe { initialize_buffer(buf.as_mut_ptr()); } 827 /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it. 828 /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes. 829 /// // To assert our buffer has been initialized without copying it, we upgrade 830 /// // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`: 831 /// let buf: &mut [u8; 1024] = unsafe { 832 /// // SAFETY: `buf` has been initialized. 833 /// buf.assume_init_mut() 834 /// }; 835 /// 836 /// // Now we can use `buf` as a normal slice: 837 /// buf.sort_unstable(); 838 /// assert!( 839 /// buf.windows(2).all(|pair| pair[0] <= pair[1]), 840 /// "buffer is sorted", 841 /// ); 842 /// ``` 843 /// 844 /// ### *Incorrect* usages of this method: 845 /// 846 /// You cannot use `.assume_init_mut()` to initialize a value: 847 /// 848 /// ```rust,no_run 849 /// use std::mem::MaybeUninit; 850 /// 851 /// let mut b = MaybeUninit::<bool>::uninit(); 852 /// unsafe { 853 /// *b.assume_init_mut() = true; 854 /// // We have created a (mutable) reference to an uninitialized `bool`! 855 /// // This is undefined behavior. ⚠️ 856 /// } 857 /// ``` 858 /// 859 /// For instance, you cannot [`Read`] into an uninitialized buffer: 860 /// 861 /// [`Read`]: ../../std/io/trait.Read.html 862 /// 863 /// ```rust,no_run 864 /// use std::{io, mem::MaybeUninit}; 865 /// 866 /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]> 867 /// { 868 /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit(); 869 /// reader.read_exact(unsafe { buffer.assume_init_mut() })?; 870 /// // ^^^^^^^^^^^^^^^^^^^^^^^^ 871 /// // (mutable) reference to uninitialized memory! 872 /// // This is undefined behavior. 873 /// Ok(unsafe { buffer.assume_init() }) 874 /// } 875 /// ``` 876 /// 877 /// Nor can you use direct field access to do field-by-field gradual initialization: 878 /// 879 /// ```rust,no_run 880 /// use std::{mem::MaybeUninit, ptr}; 881 /// 882 /// struct Foo { 883 /// a: u32, 884 /// b: u8, 885 /// } 886 /// 887 /// let foo: Foo = unsafe { 888 /// let mut foo = MaybeUninit::<Foo>::uninit(); 889 /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337); 890 /// // ^^^^^^^^^^^^^^^^^^^^^ 891 /// // (mutable) reference to uninitialized memory! 892 /// // This is undefined behavior. 893 /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42); 894 /// // ^^^^^^^^^^^^^^^^^^^^^ 895 /// // (mutable) reference to uninitialized memory! 896 /// // This is undefined behavior. 897 /// foo.assume_init() 898 /// }; 899 /// ``` 900 #[stable(feature = "maybe_uninit_ref", since = "1.55.0")] 901 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")] 902 #[inline(always)] assume_init_mut(&mut self) -> &mut T903 pub const unsafe fn assume_init_mut(&mut self) -> &mut T { 904 // SAFETY: the caller must guarantee that `self` is initialized. 905 // This also means that `self` must be a `value` variant. 906 unsafe { 907 intrinsics::assert_inhabited::<T>(); 908 &mut *self.as_mut_ptr() 909 } 910 } 911 912 /// Extracts the values from an array of `MaybeUninit` containers. 913 /// 914 /// # Safety 915 /// 916 /// It is up to the caller to guarantee that all elements of the array are 917 /// in an initialized state. 918 /// 919 /// # Examples 920 /// 921 /// ``` 922 /// #![feature(maybe_uninit_uninit_array)] 923 /// #![feature(maybe_uninit_array_assume_init)] 924 /// use std::mem::MaybeUninit; 925 /// 926 /// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array(); 927 /// array[0].write(0); 928 /// array[1].write(1); 929 /// array[2].write(2); 930 /// 931 /// // SAFETY: Now safe as we initialised all elements 932 /// let array = unsafe { 933 /// MaybeUninit::array_assume_init(array) 934 /// }; 935 /// 936 /// assert_eq!(array, [0, 1, 2]); 937 /// ``` 938 #[unstable(feature = "maybe_uninit_array_assume_init", issue = "96097")] 939 #[rustc_const_unstable(feature = "const_maybe_uninit_array_assume_init", issue = "96097")] 940 #[inline(always)] 941 #[track_caller] array_assume_init<const N: usize>(array: [Self; N]) -> [T; N]942 pub const unsafe fn array_assume_init<const N: usize>(array: [Self; N]) -> [T; N] { 943 // SAFETY: 944 // * The caller guarantees that all elements of the array are initialized 945 // * `MaybeUninit<T>` and T are guaranteed to have the same layout 946 // * `MaybeUninit` does not drop, so there are no double-frees 947 // And thus the conversion is safe 948 unsafe { 949 intrinsics::assert_inhabited::<[T; N]>(); 950 intrinsics::transmute_unchecked(array) 951 } 952 } 953 954 /// Assuming all the elements are initialized, get a slice to them. 955 /// 956 /// # Safety 957 /// 958 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements 959 /// really are in an initialized state. 960 /// Calling this when the content is not yet fully initialized causes undefined behavior. 961 /// 962 /// See [`assume_init_ref`] for more details and examples. 963 /// 964 /// [`assume_init_ref`]: MaybeUninit::assume_init_ref 965 #[unstable(feature = "maybe_uninit_slice", issue = "63569")] 966 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")] 967 #[inline(always)] slice_assume_init_ref(slice: &[Self]) -> &[T]968 pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] { 969 // SAFETY: casting `slice` to a `*const [T]` is safe since the caller guarantees that 970 // `slice` is initialized, and `MaybeUninit` is guaranteed to have the same layout as `T`. 971 // The pointer obtained is valid since it refers to memory owned by `slice` which is a 972 // reference and thus guaranteed to be valid for reads. 973 unsafe { &*(slice as *const [Self] as *const [T]) } 974 } 975 976 /// Assuming all the elements are initialized, get a mutable slice to them. 977 /// 978 /// # Safety 979 /// 980 /// It is up to the caller to guarantee that the `MaybeUninit<T>` elements 981 /// really are in an initialized state. 982 /// Calling this when the content is not yet fully initialized causes undefined behavior. 983 /// 984 /// See [`assume_init_mut`] for more details and examples. 985 /// 986 /// [`assume_init_mut`]: MaybeUninit::assume_init_mut 987 #[unstable(feature = "maybe_uninit_slice", issue = "63569")] 988 #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")] 989 #[inline(always)] slice_assume_init_mut(slice: &mut [Self]) -> &mut [T]990 pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] { 991 // SAFETY: similar to safety notes for `slice_get_ref`, but we have a 992 // mutable reference which is also guaranteed to be valid for writes. 993 unsafe { &mut *(slice as *mut [Self] as *mut [T]) } 994 } 995 996 /// Gets a pointer to the first element of the array. 997 #[unstable(feature = "maybe_uninit_slice", issue = "63569")] 998 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")] 999 #[inline(always)] slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T1000 pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T { 1001 this.as_ptr() as *const T 1002 } 1003 1004 /// Gets a mutable pointer to the first element of the array. 1005 #[unstable(feature = "maybe_uninit_slice", issue = "63569")] 1006 #[rustc_const_unstable(feature = "maybe_uninit_slice", issue = "63569")] 1007 #[inline(always)] slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T1008 pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T { 1009 this.as_mut_ptr() as *mut T 1010 } 1011 1012 /// Copies the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`. 1013 /// 1014 /// If `T` does not implement `Copy`, use [`write_slice_cloned`] 1015 /// 1016 /// This is similar to [`slice::copy_from_slice`]. 1017 /// 1018 /// # Panics 1019 /// 1020 /// This function will panic if the two slices have different lengths. 1021 /// 1022 /// # Examples 1023 /// 1024 /// ``` 1025 /// #![feature(maybe_uninit_write_slice)] 1026 /// use std::mem::MaybeUninit; 1027 /// 1028 /// let mut dst = [MaybeUninit::uninit(); 32]; 1029 /// let src = [0; 32]; 1030 /// 1031 /// let init = MaybeUninit::write_slice(&mut dst, &src); 1032 /// 1033 /// assert_eq!(init, src); 1034 /// ``` 1035 /// 1036 /// ``` 1037 /// #![feature(maybe_uninit_write_slice)] 1038 /// use std::mem::MaybeUninit; 1039 /// 1040 /// let mut vec = Vec::with_capacity(32); 1041 /// let src = [0; 16]; 1042 /// 1043 /// MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src); 1044 /// 1045 /// // SAFETY: we have just copied all the elements of len into the spare capacity 1046 /// // the first src.len() elements of the vec are valid now. 1047 /// unsafe { 1048 /// vec.set_len(src.len()); 1049 /// } 1050 /// 1051 /// assert_eq!(vec, src); 1052 /// ``` 1053 /// 1054 /// [`write_slice_cloned`]: MaybeUninit::write_slice_cloned 1055 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")] write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] where T: Copy,1056 pub fn write_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] 1057 where 1058 T: Copy, 1059 { 1060 // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout 1061 let uninit_src: &[MaybeUninit<T>] = unsafe { super::transmute(src) }; 1062 1063 this.copy_from_slice(uninit_src); 1064 1065 // SAFETY: Valid elements have just been copied into `this` so it is initialized 1066 unsafe { MaybeUninit::slice_assume_init_mut(this) } 1067 } 1068 1069 /// Clones the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`. 1070 /// Any already initialized elements will not be dropped. 1071 /// 1072 /// If `T` implements `Copy`, use [`write_slice`] 1073 /// 1074 /// This is similar to [`slice::clone_from_slice`] but does not drop existing elements. 1075 /// 1076 /// # Panics 1077 /// 1078 /// This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics. 1079 /// 1080 /// If there is a panic, the already cloned elements will be dropped. 1081 /// 1082 /// # Examples 1083 /// 1084 /// ``` 1085 /// #![feature(maybe_uninit_write_slice)] 1086 /// use std::mem::MaybeUninit; 1087 /// 1088 /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()]; 1089 /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()]; 1090 /// 1091 /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src); 1092 /// 1093 /// assert_eq!(init, src); 1094 /// ``` 1095 /// 1096 /// ``` 1097 /// #![feature(maybe_uninit_write_slice)] 1098 /// use std::mem::MaybeUninit; 1099 /// 1100 /// let mut vec = Vec::with_capacity(32); 1101 /// let src = ["rust", "is", "a", "pretty", "cool", "language"]; 1102 /// 1103 /// MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src); 1104 /// 1105 /// // SAFETY: we have just cloned all the elements of len into the spare capacity 1106 /// // the first src.len() elements of the vec are valid now. 1107 /// unsafe { 1108 /// vec.set_len(src.len()); 1109 /// } 1110 /// 1111 /// assert_eq!(vec, src); 1112 /// ``` 1113 /// 1114 /// [`write_slice`]: MaybeUninit::write_slice 1115 #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")] write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] where T: Clone,1116 pub fn write_slice_cloned<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] 1117 where 1118 T: Clone, 1119 { 1120 // unlike copy_from_slice this does not call clone_from_slice on the slice 1121 // this is because `MaybeUninit<T: Clone>` does not implement Clone. 1122 1123 struct Guard<'a, T> { 1124 slice: &'a mut [MaybeUninit<T>], 1125 initialized: usize, 1126 } 1127 1128 impl<'a, T> Drop for Guard<'a, T> { 1129 fn drop(&mut self) { 1130 let initialized_part = &mut self.slice[..self.initialized]; 1131 // SAFETY: this raw slice will contain only initialized objects 1132 // that's why, it is allowed to drop it. 1133 unsafe { 1134 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(initialized_part)); 1135 } 1136 } 1137 } 1138 1139 assert_eq!(this.len(), src.len(), "destination and source slices have different lengths"); 1140 // NOTE: We need to explicitly slice them to the same length 1141 // for bounds checking to be elided, and the optimizer will 1142 // generate memcpy for simple cases (for example T = u8). 1143 let len = this.len(); 1144 let src = &src[..len]; 1145 1146 // guard is needed b/c panic might happen during a clone 1147 let mut guard = Guard { slice: this, initialized: 0 }; 1148 1149 for i in 0..len { 1150 guard.slice[i].write(src[i].clone()); 1151 guard.initialized += 1; 1152 } 1153 1154 super::forget(guard); 1155 1156 // SAFETY: Valid elements have just been written into `this` so it is initialized 1157 unsafe { MaybeUninit::slice_assume_init_mut(this) } 1158 } 1159 1160 /// Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes. 1161 /// 1162 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still 1163 /// contain padding bytes which are left uninitialized. 1164 /// 1165 /// # Examples 1166 /// 1167 /// ``` 1168 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_slice)] 1169 /// use std::mem::MaybeUninit; 1170 /// 1171 /// let val = 0x12345678_i32; 1172 /// let uninit = MaybeUninit::new(val); 1173 /// let uninit_bytes = uninit.as_bytes(); 1174 /// let bytes = unsafe { MaybeUninit::slice_assume_init_ref(uninit_bytes) }; 1175 /// assert_eq!(bytes, val.to_ne_bytes()); 1176 /// ``` 1177 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")] as_bytes(&self) -> &[MaybeUninit<u8>]1178 pub fn as_bytes(&self) -> &[MaybeUninit<u8>] { 1179 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes 1180 unsafe { 1181 slice::from_raw_parts(self.as_ptr() as *const MaybeUninit<u8>, mem::size_of::<T>()) 1182 } 1183 } 1184 1185 /// Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized 1186 /// bytes. 1187 /// 1188 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still 1189 /// contain padding bytes which are left uninitialized. 1190 /// 1191 /// # Examples 1192 /// 1193 /// ``` 1194 /// #![feature(maybe_uninit_as_bytes)] 1195 /// use std::mem::MaybeUninit; 1196 /// 1197 /// let val = 0x12345678_i32; 1198 /// let mut uninit = MaybeUninit::new(val); 1199 /// let uninit_bytes = uninit.as_bytes_mut(); 1200 /// if cfg!(target_endian = "little") { 1201 /// uninit_bytes[0].write(0xcd); 1202 /// } else { 1203 /// uninit_bytes[3].write(0xcd); 1204 /// } 1205 /// let val2 = unsafe { uninit.assume_init() }; 1206 /// assert_eq!(val2, 0x123456cd); 1207 /// ``` 1208 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")] as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>]1209 pub fn as_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] { 1210 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes 1211 unsafe { 1212 slice::from_raw_parts_mut( 1213 self.as_mut_ptr() as *mut MaybeUninit<u8>, 1214 mem::size_of::<T>(), 1215 ) 1216 } 1217 } 1218 1219 /// Returns the contents of this slice of `MaybeUninit` as a slice of potentially uninitialized 1220 /// bytes. 1221 /// 1222 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still 1223 /// contain padding bytes which are left uninitialized. 1224 /// 1225 /// # Examples 1226 /// 1227 /// ``` 1228 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)] 1229 /// use std::mem::MaybeUninit; 1230 /// 1231 /// let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)]; 1232 /// let uninit_bytes = MaybeUninit::slice_as_bytes(&uninit); 1233 /// let bytes = unsafe { MaybeUninit::slice_assume_init_ref(&uninit_bytes) }; 1234 /// let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap()); 1235 /// let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap()); 1236 /// assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]); 1237 /// ``` 1238 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")] slice_as_bytes(this: &[MaybeUninit<T>]) -> &[MaybeUninit<u8>]1239 pub fn slice_as_bytes(this: &[MaybeUninit<T>]) -> &[MaybeUninit<u8>] { 1240 let bytes = mem::size_of_val(this); 1241 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes 1242 unsafe { slice::from_raw_parts(this.as_ptr() as *const MaybeUninit<u8>, bytes) } 1243 } 1244 1245 /// Returns the contents of this mutable slice of `MaybeUninit` as a mutable slice of 1246 /// potentially uninitialized bytes. 1247 /// 1248 /// Note that even if the contents of a `MaybeUninit` have been initialized, the value may still 1249 /// contain padding bytes which are left uninitialized. 1250 /// 1251 /// # Examples 1252 /// 1253 /// ``` 1254 /// #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)] 1255 /// use std::mem::MaybeUninit; 1256 /// 1257 /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()]; 1258 /// let uninit_bytes = MaybeUninit::slice_as_bytes_mut(&mut uninit); 1259 /// MaybeUninit::write_slice(uninit_bytes, &[0x12, 0x34, 0x56, 0x78]); 1260 /// let vals = unsafe { MaybeUninit::slice_assume_init_ref(&uninit) }; 1261 /// if cfg!(target_endian = "little") { 1262 /// assert_eq!(vals, &[0x3412u16, 0x7856u16]); 1263 /// } else { 1264 /// assert_eq!(vals, &[0x1234u16, 0x5678u16]); 1265 /// } 1266 /// ``` 1267 #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")] slice_as_bytes_mut(this: &mut [MaybeUninit<T>]) -> &mut [MaybeUninit<u8>]1268 pub fn slice_as_bytes_mut(this: &mut [MaybeUninit<T>]) -> &mut [MaybeUninit<u8>] { 1269 let bytes = mem::size_of_val(this); 1270 // SAFETY: MaybeUninit<u8> is always valid, even for padding bytes 1271 unsafe { slice::from_raw_parts_mut(this.as_mut_ptr() as *mut MaybeUninit<u8>, bytes) } 1272 } 1273 } 1274 1275 impl<T, const N: usize> MaybeUninit<[T; N]> { 1276 /// Transposes a `MaybeUninit<[T; N]>` into a `[MaybeUninit<T>; N]`. 1277 /// 1278 /// # Examples 1279 /// 1280 /// ``` 1281 /// #![feature(maybe_uninit_uninit_array_transpose)] 1282 /// # use std::mem::MaybeUninit; 1283 /// 1284 /// let data: [MaybeUninit<u8>; 1000] = MaybeUninit::uninit().transpose(); 1285 /// ``` 1286 #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")] 1287 #[inline] transpose(self) -> [MaybeUninit<T>; N]1288 pub const fn transpose(self) -> [MaybeUninit<T>; N] { 1289 // SAFETY: T and MaybeUninit<T> have the same layout 1290 unsafe { intrinsics::transmute_unchecked(self) } 1291 } 1292 } 1293 1294 impl<T, const N: usize> [MaybeUninit<T>; N] { 1295 /// Transposes a `[MaybeUninit<T>; N]` into a `MaybeUninit<[T; N]>`. 1296 /// 1297 /// # Examples 1298 /// 1299 /// ``` 1300 /// #![feature(maybe_uninit_uninit_array_transpose)] 1301 /// # use std::mem::MaybeUninit; 1302 /// 1303 /// let data = [MaybeUninit::<u8>::uninit(); 1000]; 1304 /// let data: MaybeUninit<[u8; 1000]> = data.transpose(); 1305 /// ``` 1306 #[unstable(feature = "maybe_uninit_uninit_array_transpose", issue = "96097")] 1307 #[inline] transpose(self) -> MaybeUninit<[T; N]>1308 pub const fn transpose(self) -> MaybeUninit<[T; N]> { 1309 // SAFETY: T and MaybeUninit<T> have the same layout 1310 unsafe { intrinsics::transmute_unchecked(self) } 1311 } 1312 } 1313