use crate::Pun;
#[doc(hidden)]
pub const PROBE_LEN: usize = 3;
union Cast<A: Copy, B: Copy> {
from: A,
to: B,
}
#[inline(always)]
pub const unsafe fn raw_len<T: ?Sized>(ptr: *const T) -> usize {
unsafe { Cast::<*const T, *const [u8]> { from: ptr }.to }.len()
}
#[inline(always)]
pub const unsafe fn raw_with_len<T: ?Sized>(ptr: *const T, len: usize) -> *const T {
let slice = core::ptr::slice_from_raw_parts(ptr.cast::<u8>(), len);
unsafe { Cast::<*const [u8], *const T> { from: slice }.to }
}
pub const unsafe fn verify<T: ?Sized>(probe: *const T) {
const MESSAGE: &str = "unsupported compiler: unexpected wide pointer representation";
assert!(size_of::<*const T>() == size_of::<*const [u8]>(), "{}", MESSAGE);
assert!(align_of::<*const T>() == align_of::<*const [u8]>(), "{}", MESSAGE);
unsafe {
assert!(raw_len(probe) == PROBE_LEN, "{}", MESSAGE);
let other = raw_with_len(probe, PROBE_LEN + 39);
assert!(raw_len(other) == PROBE_LEN + 39, "{}", MESSAGE);
assert!(other.cast::<u8>().is_null() && probe.cast::<u8>().is_null(), "{}", MESSAGE);
}
}
#[inline(always)]
pub const fn metadata<T: ?Sized + Pun>(ptr: *const T) -> usize {
if const { !T::LAYOUT.unsized_ } {
return 0;
}
unsafe { raw_len(ptr) }
}
#[inline(always)]
pub const fn from_raw_parts<T: ?Sized + Pun>(addr: *const u8, len: usize) -> *const T {
if const { T::LAYOUT.unsized_ } {
let slice = core::ptr::slice_from_raw_parts(addr, len);
unsafe { Cast::<*const [u8], *const T> { from: slice }.to }
} else {
unsafe { Cast::<*const u8, *const T> { from: addr }.to }
}
}
#[inline(always)]
pub const unsafe fn field<T: ?Sized + Pun, F: ?Sized + Pun>(
ptr: *const T,
offset: usize,
) -> *const F {
let len = if const { F::LAYOUT.unsized_ } { metadata(ptr) } else { 0 };
from_raw_parts(unsafe { ptr.cast::<u8>().add(offset) }, len)
}
#[inline(always)]
pub const fn is_aligned(addr: *const u8, align: usize) -> bool {
let addr = unsafe { Cast::<*const u8, usize> { from: addr }.to };
addr & (align - 1) == 0
}