diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 0b2b5f7e58f46..6e8620cf4724d 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -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

(&self, base: P) -> &Path + where + P: AsRef, + { + 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())