diff options
| author | Tim Chevalier <chevalier@alum.wellesley.edu> | 2013-09-24 12:10:36 -0700 |
|---|---|---|
| committer | Tim Chevalier <chevalier@alum.wellesley.edu> | 2013-09-25 11:08:30 -0700 |
| commit | 22654165c697cac912159daedbfb731fbc7c175d (patch) | |
| tree | c7c96e46b10829c94fe817ef2cf785b1c527d2bd /src/libstd | |
| parent | 5375cf87182555e7d91089b95c088793db32fa05 (diff) | |
| download | rust-22654165c697cac912159daedbfb731fbc7c175d.tar.gz rust-22654165c697cac912159daedbfb731fbc7c175d.zip | |
std: Add an is_parent_of method to Path
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/path.rs | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/libstd/path.rs b/src/libstd/path.rs index 336284963a2..c33a1ad11ee 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -233,6 +233,21 @@ pub trait GenericPath : Clone + Eq + ToStr { result } + + /// Returns `true` iff `child` is a suffix of `parent`. See the test + /// case for examples. + pub fn is_parent_of(parent: &Path, child: &Path) -> bool { + if !parent.is_absolute() || child.is_absolute() + || parent.components.len() < child.components.len() + || parent.components.is_empty() { + return false; + } + let child_components = child.components().len(); + let parent_components = parent.components().len(); + let to_drop = parent.components.len() - child_components; + parent.components.slice(to_drop, parent_components) == child.components + } + fn components<'a>(&'a self) -> &'a [~str]; } @@ -1450,4 +1465,34 @@ mod tests { } + + #[test] + fn test_is_parent_of() { + assert!(is_parent_of(&PosixPath("/a/b/c/d/e"), &PosixPath("c/d/e"))); + assert!(!is_parent_of(&PosixPath("a/b/c/d/e"), &PosixPath("c/d/e"))); + assert!(!is_parent_of(&PosixPath("/a/b/c/d/e"), &PosixPath("/c/d/e"))); + assert!(!is_parent_of(&PosixPath(""), &PosixPath(""))); + assert!(!is_parent_of(&PosixPath(""), &PosixPath("a/b/c"))); + assert!(is_parent_of(&PosixPath("/a/b/c"), &PosixPath(""))); + assert!(is_parent_of(&PosixPath("/a/b/c"), &PosixPath("a/b/c"))); + assert!(!is_parent_of(&PosixPath("/a/b/c"), &PosixPath("d/e/f"))); + + let abcde = WindowsPath("C:\\a\\b\\c\\d\\e"); + let rel_abcde = WindowsPath("a\\b\\c\\d\\e"); + let cde = WindowsPath("c\\d\\e"); + let slashcde = WindowsPath("C:\\c\\d\\e"); + let empty = WindowsPath(""); + let abc = WindowsPath("C:\\a\\b\\c"); + let rel_abc = WindowsPath("a\\b\\c"); + let def = WindowsPath("d\\e\\f"); + + assert!(is_parent_of(&abcde, &cde)); + assert!(!is_parent_of(&rel_abcde, &cde)); + assert!(!is_parent_of(&abcde, &slashcde)); + assert!(!is_parent_of(&empty, &empty)); + assert!(is_parent_of(&abc, &empty); + assert!(is_parent_of(&abc, &rel_abc)); + assert!(!is_parent_of(&abc, &def)); + } + } |
