use std::ptr::NonNull;
pub(super) struct RawPtrBox<T> {
ptr: NonNull<T>,
}
impl<T> Clone for RawPtrBox<T> {
fn clone(&self) -> Self {
Self { ptr: self.ptr }
}
}
impl<T> Copy for RawPtrBox<T> {}
impl<T> RawPtrBox<T> {
pub(super) unsafe fn new(ptr: *const u8) -> Self {
let ptr = NonNull::new(ptr as *mut u8).expect("Pointer cannot be null");
assert_eq!(
ptr.as_ptr().align_offset(std::mem::align_of::<T>()),
0,
"memory is not aligned"
);
Self { ptr: ptr.cast() }
}
pub(super) fn as_ptr(&self) -> *const T {
self.ptr.as_ptr()
}
}
unsafe impl<T> Send for RawPtrBox<T> {}
unsafe impl<T> Sync for RawPtrBox<T> {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "memory is not aligned")]
#[cfg_attr(miri, ignore)] fn test_primitive_array_alignment() {
let bytes = vec![0u8, 1u8];
unsafe { RawPtrBox::<u64>::new(bytes.as_ptr().offset(1)) };
}
}