1#![allow(dead_code)]
2use crate::Error;
3use core::{mem::MaybeUninit, ptr, slice};
4
5#[inline(always)]
9#[allow(unused_unsafe)] pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] {
11 let ptr = ptr_from_mut::<[MaybeUninit<T>]>(slice) as *mut [T];
12 unsafe { &mut *ptr }
14}
15
16#[inline]
17pub fn uninit_slice_fill_zero(slice: &mut [MaybeUninit<u8>]) -> &mut [u8] {
18 unsafe { ptr::write_bytes(slice.as_mut_ptr(), 0, slice.len()) };
19 unsafe { slice_assume_init_mut(slice) }
20}
21
22#[inline(always)]
23pub fn slice_as_uninit<T>(slice: &[T]) -> &[MaybeUninit<T>] {
24 let ptr = ptr_from_ref::<[T]>(slice) as *const [MaybeUninit<T>];
25 unsafe { &*ptr }
27}
28
29#[inline(always)]
34#[allow(unused_unsafe)] pub unsafe fn slice_as_uninit_mut<T>(slice: &mut [T]) -> &mut [MaybeUninit<T>] {
36 let ptr = ptr_from_mut::<[T]>(slice) as *mut [MaybeUninit<T>];
37 unsafe { &mut *ptr }
39}
40
41fn ptr_from_mut<T: ?Sized>(r: &mut T) -> *mut T {
43 r
44}
45
46fn ptr_from_ref<T: ?Sized>(r: &T) -> *const T {
48 r
49}
50
51#[inline]
53pub fn inner_u32() -> Result<u32, Error> {
54 let mut res = MaybeUninit::<u32>::uninit();
55 let dst = unsafe {
57 let p: *mut MaybeUninit<u8> = res.as_mut_ptr().cast();
58 slice::from_raw_parts_mut(p, core::mem::size_of::<u32>())
59 };
60 crate::fill_uninit(dst)?;
61 Ok(unsafe { res.assume_init() })
64}
65
66#[inline]
68pub fn inner_u64() -> Result<u64, Error> {
69 let mut res = MaybeUninit::<u64>::uninit();
70 let dst = unsafe {
72 let p: *mut MaybeUninit<u8> = res.as_mut_ptr().cast();
73 slice::from_raw_parts_mut(p, core::mem::size_of::<u64>())
74 };
75 crate::fill_uninit(dst)?;
76 Ok(unsafe { res.assume_init() })
79}
80
81pub(crate) fn truncate(val: u64) -> u32 {
83 u32::try_from(val & u64::from(u32::MAX)).expect("The higher 32 bits are masked")
84}