#![allow(dead_code)] use crate::Error; use core::{mem::MaybeUninit, ptr, slice}; /// Polyfill for `maybe_uninit_slice` feature's /// `MaybeUninit::slice_assume_init_mut`. Every element of `slice` must have /// been initialized. #[inline(always)] #[allow(unused_unsafe)] // TODO(MSRV 1.65): Remove this. pub unsafe fn slice_assume_init_mut(slice: &mut [MaybeUninit]) -> &mut [T] { let ptr = ptr_from_mut::<[MaybeUninit]>(slice) as *mut [T]; // SAFETY: `MaybeUninit` is guaranteed to be layout-compatible with `T`. unsafe { &mut *ptr } } #[inline] pub fn uninit_slice_fill_zero(slice: &mut [MaybeUninit]) -> &mut [u8] { unsafe { ptr::write_bytes(slice.as_mut_ptr(), 0, slice.len()) }; unsafe { slice_assume_init_mut(slice) } } #[inline(always)] pub fn slice_as_uninit(slice: &[T]) -> &[MaybeUninit] { let ptr = ptr_from_ref::<[T]>(slice) as *const [MaybeUninit]; // SAFETY: `MaybeUninit` is guaranteed to be layout-compatible with `T`. unsafe { &*ptr } } /// View an mutable initialized array as potentially-uninitialized. /// /// This is unsafe because it allows assigning uninitialized values into /// `slice`, which would be undefined behavior. #[inline(always)] #[allow(unused_unsafe)] // TODO(MSRV 1.65): Remove this. pub unsafe fn slice_as_uninit_mut(slice: &mut [T]) -> &mut [MaybeUninit] { let ptr = ptr_from_mut::<[T]>(slice) as *mut [MaybeUninit]; // SAFETY: `MaybeUninit` is guaranteed to be layout-compatible with `T`. unsafe { &mut *ptr } } // TODO: MSRV(1.76.0): Replace with `core::ptr::from_mut`. fn ptr_from_mut(r: &mut T) -> *mut T { r } // TODO: MSRV(1.76.0): Replace with `core::ptr::from_ref`. fn ptr_from_ref(r: &T) -> *const T { r } /// Default implementation of `inner_u32` on top of `fill_uninit` #[inline] pub fn inner_u32() -> Result { let mut res = MaybeUninit::::uninit(); // SAFETY: the created slice has the same size as `res` let dst = unsafe { let p: *mut MaybeUninit = res.as_mut_ptr().cast(); slice::from_raw_parts_mut(p, core::mem::size_of::()) }; crate::fill_uninit(dst)?; // SAFETY: `dst` has been fully initialized by `imp::fill_inner` // since it returned `Ok`. Ok(unsafe { res.assume_init() }) } /// Default implementation of `inner_u64` on top of `fill_uninit` #[inline] pub fn inner_u64() -> Result { let mut res = MaybeUninit::::uninit(); // SAFETY: the created slice has the same size as `res` let dst = unsafe { let p: *mut MaybeUninit = res.as_mut_ptr().cast(); slice::from_raw_parts_mut(p, core::mem::size_of::()) }; crate::fill_uninit(dst)?; // SAFETY: `dst` has been fully initialized by `imp::fill_inner` // since it returned `Ok`. Ok(unsafe { res.assume_init() }) } /// Truncates `u64` and returns the lower 32 bits as `u32` pub(crate) fn truncate(val: u64) -> u32 { u32::try_from(val & u64::from(u32::MAX)).expect("The higher 32 bits are masked") }