dynix/src/boxext.rs
2026-03-19 17:47:42 +01:00

27 lines
918 B
Rust

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<OsStr>;
}
impl BoxedPathExt for Box<Path> {
fn into_boxed_os_str(self) -> Box<OsStr> {
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::<OsStr>::from_raw(os_str_mut_ptr) }
}
}