mirror of
https://github.com/rust-lang/rust.git
synced 2026-05-07 01:05:39 +03:00
trim prefix/suffix for paths
This commit is contained in:
@@ -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())
|
||||
|
||||
Reference in New Issue
Block a user