Better path methods

This commit is contained in:
topjohnwu 2025-04-24 16:14:00 -07:00 committed by John Wu
parent 0c70b7670c
commit 4ad26d3dfb
2 changed files with 14 additions and 11 deletions

View File

@ -415,17 +415,19 @@ impl Utf8CStr {
Ok(()) Ok(())
} }
pub fn parent(&self, buf: &mut dyn Utf8CStrBuf) -> bool { pub fn parent_dir(&self) -> Option<&str> {
buf.clear(); Path::new(self.as_str())
if let Some(parent) = Path::new(self.as_str()).parent() { .parent()
let bytes = parent.as_os_str().as_bytes(); .map(Path::as_os_str)
// SAFETY: all substring of self is valid UTF-8 // SAFETY: all substring of self is valid UTF-8
let parent = unsafe { std::str::from_utf8_unchecked(bytes) }; .map(|s| unsafe { std::str::from_utf8_unchecked(s.as_bytes()) })
buf.push_str(parent); }
true
} else { pub fn file_name(&self) -> Option<&str> {
false Path::new(self.as_str())
} .file_name()
// SAFETY: all substring of self is valid UTF-8
.map(|s| unsafe { std::str::from_utf8_unchecked(s.as_bytes()) })
} }
// ln self path // ln self path

View File

@ -346,7 +346,8 @@ impl Cpio {
let mut buf = cstr::buf::default(); let mut buf = cstr::buf::default();
// Make sure its parent directories exist // Make sure its parent directories exist
if out.parent(&mut buf) { if let Some(dir) = out.parent_dir() {
buf.push_str(dir);
buf.mkdirs(0o755)?; buf.mkdirs(0o755)?;
} }