use std::{ffi::OsStr, path::Path, ptr}; /// Until [`Box::map()`] is stable, there's no way to do this that is safe, stable, and /// allocationless. pub trait BoxedPathExt { fn into_boxed_os_str(self) -> Box; } impl BoxedPathExt for Box { fn into_boxed_os_str(self) -> Box { let path_mut_ptr: *mut Path = Box::into_raw(self); // SAFETY: we just got `path_mut_ptr` from a valid Box. let os_str_mut_ptr: *mut OsStr = unsafe { let os_str_mut_ref = path_mut_ptr .as_mut() .expect("avoided undefined behavior") .as_mut_os_str(); ptr::from_mut(os_str_mut_ref) }; // SAFETY: allocation came from `Box::into_raw()`, and we are not extending // its lifetime. There are also no shared or exclusive references. unsafe { Box::::from_raw(os_str_mut_ptr) } } }