|
1 | 1 | use std::ffi::OsStr;
|
2 | 2 |
|
3 |
| -use crate::path::{Ancestors, Components, Display, Iter, PathBuf}; |
| 3 | +use crate::path::{Ancestors, Components, Display, Iter, PathBuf, StripPrefixError}; |
4 | 4 | use crate::{fs, io};
|
5 | 5 |
|
6 | 6 | /// This struct is an async version of [`std::path::Path`].
|
@@ -591,6 +591,41 @@ impl Path {
|
591 | 591 | self.inner.starts_with(base)
|
592 | 592 | }
|
593 | 593 |
|
| 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 | + |
594 | 629 | /// Queries the metadata about a file without following symlinks.
|
595 | 630 | ///
|
596 | 631 | /// This is an alias to [`fs::symlink_metadata`].
|
|
0 commit comments