1 | #![allow (dead_code)] |
2 | use core::{mem::MaybeUninit, ptr}; |
3 | |
4 | /// Polyfill for `maybe_uninit_slice` feature's |
5 | /// `MaybeUninit::slice_assume_init_mut`. Every element of `slice` must have |
6 | /// been initialized. |
7 | #[inline (always)] |
8 | pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] { |
9 | // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`. |
10 | &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) |
11 | } |
12 | |
13 | #[inline ] |
14 | pub fn uninit_slice_fill_zero(slice: &mut [MaybeUninit<u8>]) -> &mut [u8] { |
15 | unsafe { ptr::write_bytes(dst:slice.as_mut_ptr(), val:0, count:slice.len()) }; |
16 | unsafe { slice_assume_init_mut(slice) } |
17 | } |
18 | |
19 | #[inline (always)] |
20 | pub fn slice_as_uninit<T>(slice: &[T]) -> &[MaybeUninit<T>] { |
21 | // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`. |
22 | // There is no risk of writing a `MaybeUninit<T>` into the result since |
23 | // the result isn't mutable. |
24 | unsafe { &*(slice as *const [T] as *const [MaybeUninit<T>]) } |
25 | } |
26 | |
27 | /// View an mutable initialized array as potentially-uninitialized. |
28 | /// |
29 | /// This is unsafe because it allows assigning uninitialized values into |
30 | /// `slice`, which would be undefined behavior. |
31 | #[inline (always)] |
32 | pub unsafe fn slice_as_uninit_mut<T>(slice: &mut [T]) -> &mut [MaybeUninit<T>] { |
33 | // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`. |
34 | &mut *(slice as *mut [T] as *mut [MaybeUninit<T>]) |
35 | } |
36 | |