Skip to content

Commit 9f3c8ba

Browse files
Rollup merge of rust-lang#154320 - bend-n:trim_prefix_suffix_for_paths, r=Mark-Simulacrum
`trim_prefix` for paths under rust-lang#142312? its a useful method.
2 parents c60ea4b + cc65ec1 commit 9f3c8ba

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

library/std/src/path.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2725,6 +2725,41 @@ impl Path {
27252725
self._strip_prefix(base.as_ref())
27262726
}
27272727

2728+
/// Returns a path with the optional prefix removed.
2729+
///
2730+
/// If `base` is not a prefix of `self` (i.e., [`starts_with`] returns `false`), returns the original path (`self`)
2731+
///
2732+
/// [`starts_with`]: Path::starts_with
2733+
///
2734+
/// # Examples
2735+
///
2736+
/// ```
2737+
/// #![feature(trim_prefix_suffix)]
2738+
/// use std::path::Path;
2739+
///
2740+
/// let path = Path::new("/test/haha/foo.txt");
2741+
///
2742+
/// // Prefix present - remove it
2743+
/// assert_eq!(path.trim_prefix("/"), Path::new("test/haha/foo.txt"));
2744+
/// assert_eq!(path.trim_prefix("/test"), Path::new("haha/foo.txt"));
2745+
/// assert_eq!(path.trim_prefix("/test/"), Path::new("haha/foo.txt"));
2746+
/// assert_eq!(path.trim_prefix("/test/haha/foo.txt"), Path::new(""));
2747+
/// assert_eq!(path.trim_prefix("/test/haha/foo.txt/"), Path::new(""));
2748+
///
2749+
/// // Prefix absent - return original
2750+
/// assert_eq!(path.trim_prefix("test"), path);
2751+
/// assert_eq!(path.trim_prefix("/te"), path);
2752+
/// assert_eq!(path.trim_prefix("/haha"), path);
2753+
/// ```
2754+
#[must_use = "this returns the remaining path as a new path, without modifying the original"]
2755+
#[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2756+
pub fn trim_prefix<P>(&self, base: P) -> &Path
2757+
where
2758+
P: AsRef<Path>,
2759+
{
2760+
self._strip_prefix(base.as_ref()).unwrap_or(self)
2761+
}
2762+
27282763
fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
27292764
iter_after(self.components(), base.components())
27302765
.map(|c| c.as_path())

0 commit comments

Comments
 (0)