Given a &Path and an arbitrary allocator, what's the correct/non-UB way of copying it and returning a &mut Path from it? std::mem::transmute doesn't exactly strike me as the safest way to go; yet following the std methods alone means recasting a shared reference into its exclusive counterpart, which seems even worse. MIRI happens to agree with that, too.
Is there a reliable, consistent, OS-agnostic way to do this?
use bumpalo::Bump; use std::path::Path; use std::alloc::Layout; fn main() { let ref bump = Bump::new(); let v1 = v1(bump, "/etc/apt"); println!("{}", v1.display()); let v2 = v2(bump, "/var/lib"); println!("{}", v2.display()); // let v3 = ? } fn v1(bump: &Bump, path: impl AsRef<Path>) -> &mut Path { let path = path.as_ref(); let layout = Layout::for_value(path); let alloc = bump.alloc_layout(layout).as_ptr(); let src = path as *const Path as *const u8; let len = size_of_val(path); unsafe { std::ptr::copy_nonoverlapping(src, alloc, len); let slice = std::slice::from_raw_parts_mut(alloc, len); let path: *mut Path = std::mem::transmute(slice); &mut *path } } fn v2(bump: &Bump, path: impl AsRef<Path>) -> &mut Path { let bytes = path.as_ref().as_os_str().as_encoded_bytes(); let alloc = bump.alloc_slice_copy(bytes); unsafe { use std::ffi::OsStr; let os_str = OsStr::from_encoded_bytes_unchecked(alloc); let path = Path::new(os_str) as *const Path as *mut Path; #[allow(invalid_reference_casting)] &mut *path } } 5 posts - 4 participants
