trim prefix/suffix for paths

This commit is contained in:
bendn
2026-03-24 23:07:22 +07:00
parent cde9cf08d7
commit cc65ec1892
+35
View File
@@ -2725,6 +2725,41 @@ pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
self._strip_prefix(base.as_ref())
}
/// Returns a path with the optional prefix removed.
///
/// If `base` is not a prefix of `self` (i.e., [`starts_with`] returns `false`), returns the original path (`self`)
///
/// [`starts_with`]: Path::starts_with
///
/// # Examples
///
/// ```
/// #![feature(trim_prefix_suffix)]
/// use std::path::Path;
///
/// let path = Path::new("/test/haha/foo.txt");
///
/// // Prefix present - remove it
/// assert_eq!(path.trim_prefix("/"), Path::new("test/haha/foo.txt"));
/// assert_eq!(path.trim_prefix("/test"), Path::new("haha/foo.txt"));
/// assert_eq!(path.trim_prefix("/test/"), Path::new("haha/foo.txt"));
/// assert_eq!(path.trim_prefix("/test/haha/foo.txt"), Path::new(""));
/// assert_eq!(path.trim_prefix("/test/haha/foo.txt/"), Path::new(""));
///
/// // Prefix absent - return original
/// assert_eq!(path.trim_prefix("test"), path);
/// assert_eq!(path.trim_prefix("/te"), path);
/// assert_eq!(path.trim_prefix("/haha"), path);
/// ```
#[must_use = "this returns the remaining path as a new path, without modifying the original"]
#[unstable(feature = "trim_prefix_suffix", issue = "142312")]
pub fn trim_prefix<P>(&self, base: P) -> &Path
where
P: AsRef<Path>,
{
self._strip_prefix(base.as_ref()).unwrap_or(self)
}
fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
iter_after(self.components(), base.components())
.map(|c| c.as_path())