Is there a way to emulate the following `ptr_metadata`-dependent code on stable Rust?
⚓ Rust 📅 2026-05-13 👤 surdeus 👁️ 1I have the following function (major simplification from real code):
/// Copy `val` to `buf` and return reference to the copied value.
///
/// # Safety
/// `T` must NOT implement `Drop`.
unsafe fn foo<'a, T: ?Sized>(val: &T, buf: &'a mut [u64; 128]) -> &'a T {
assert!(align_of_val(val) <= align_of_val(buf));
assert!(size_of_val(val) <= size_of_val(buf));
let size = size_of_val(val);
let (src_ptr, metadata) = (val as *const T).to_raw_parts();
let dst_ptr: *mut u8 = buf.as_mut_ptr().cast();
core::ptr::copy_nonoverlapping(src_ptr.cast(), dst_ptr, size);
let p: *const T = core::ptr::from_raw_parts(dst_ptr, metadata);
p.as_ref_unchecked()
}
I want for this function to work with T: Copy + Sized, str, [T] where T: Copy + Sized and potentially with other compatible types.
Is there a way to implement it on stable Rust without making Miri really angry? Currently, I have to use 3 different functions for this, which is pretty inconvenient.
3 posts - 2 participants
🏷️ Rust_feed