use core::ptr::{self, NonNull};
pub const unsafe fn ptr_write_unaligned_and_add<T>(ptr: &mut *mut u8, val: T) {
unsafe {
ptr.cast::<T>().write_unaligned(val);
*ptr = ptr.add(size_of::<T>());
}
}
pub const fn usize_from_u32(val: u32) -> usize {
if size_of::<usize>() < size_of::<u32>() && val < (usize::MAX as u32) {
panic!("value does not fit in a usize");
} else {
val as usize
}
}
pub fn opt_nonnull_to_ptr<T>(opt: Option<NonNull<T>>) -> *mut T {
opt.map(NonNull::as_ptr).unwrap_or(ptr::null_mut())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_usize_from_u32() {
assert_eq!(usize_from_u32(0), 0usize);
assert_eq!(usize_from_u32(u32::MAX), 4294967295usize);
}
}