Skip to content

Commit df53a07

Browse files
committed
Implemented Path::strip_prefix
1 parent 942403c commit df53a07

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/path/path.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::ffi::OsStr;
22

3-
use crate::path::{Ancestors, Components, Display, Iter, PathBuf};
3+
use crate::path::{Ancestors, Components, Display, Iter, PathBuf, StripPrefixError};
44
use crate::{fs, io};
55

66
/// This struct is an async version of [`std::path::Path`].
@@ -591,6 +591,41 @@ impl Path {
591591
self.inner.starts_with(base)
592592
}
593593

594+
/// Returns a path that, when joined onto `base`, yields `self`.
595+
///
596+
/// # Errors
597+
///
598+
/// If `base` is not a prefix of `self` (i.e., [`starts_with`]
599+
/// returns `false`), returns [`Err`].
600+
///
601+
/// [`starts_with`]: #method.starts_with
602+
/// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
603+
///
604+
/// # Examples
605+
///
606+
/// ```
607+
/// use async_std::path::{Path, PathBuf};
608+
///
609+
/// let path = Path::new("/test/haha/foo.txt");
610+
///
611+
/// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
612+
/// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
613+
/// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
614+
/// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
615+
/// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
616+
/// assert_eq!(path.strip_prefix("test").is_ok(), false);
617+
/// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
618+
///
619+
/// let prefix = PathBuf::from("/test/");
620+
/// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
621+
/// ```
622+
pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
623+
where
624+
P: AsRef<std::path::Path>,
625+
{
626+
Ok(self.inner.strip_prefix(base)?.into())
627+
}
628+
594629
/// Queries the metadata about a file without following symlinks.
595630
///
596631
/// This is an alias to [`fs::symlink_metadata`].

src/path/pathbuf.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,9 @@ impl AsRef<Path> for PathBuf {
3939
Path::new(&self.inner)
4040
}
4141
}
42+
43+
impl AsRef<std::path::Path> for PathBuf {
44+
fn as_ref(&self) -> &std::path::Path {
45+
self.inner.as_ref()
46+
}
47+
}

0 commit comments

Comments
 (0)