From 4ad26d3dfb451a3c867d45109215a447f420a0a3 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Thu, 24 Apr 2025 16:14:00 -0700 Subject: [PATCH] Better path methods --- native/src/base/files.rs | 22 ++++++++++++---------- native/src/boot/cpio.rs | 3 ++- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/native/src/base/files.rs b/native/src/base/files.rs index 1758e9717..92f1c71c9 100644 --- a/native/src/base/files.rs +++ b/native/src/base/files.rs @@ -415,17 +415,19 @@ impl Utf8CStr { Ok(()) } - pub fn parent(&self, buf: &mut dyn Utf8CStrBuf) -> bool { - buf.clear(); - if let Some(parent) = Path::new(self.as_str()).parent() { - let bytes = parent.as_os_str().as_bytes(); + pub fn parent_dir(&self) -> Option<&str> { + Path::new(self.as_str()) + .parent() + .map(Path::as_os_str) // SAFETY: all substring of self is valid UTF-8 - let parent = unsafe { std::str::from_utf8_unchecked(bytes) }; - buf.push_str(parent); - true - } else { - false - } + .map(|s| unsafe { std::str::from_utf8_unchecked(s.as_bytes()) }) + } + + pub fn file_name(&self) -> Option<&str> { + 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 diff --git a/native/src/boot/cpio.rs b/native/src/boot/cpio.rs index 25c561e89..d26edb917 100644 --- a/native/src/boot/cpio.rs +++ b/native/src/boot/cpio.rs @@ -346,7 +346,8 @@ impl Cpio { let mut buf = cstr::buf::default(); // 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)?; }