Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions library/std/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2725,6 +2725,41 @@ impl Path {
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())
Expand Down
Loading