@@ -233,6 +233,21 @@ pub trait GenericPath : Clone + Eq + ToStr {
233233 result
234234 }
235235
236+
237+ /// Returns `true` iff `child` is a suffix of `parent`. See the test
238+ /// case for examples.
239+ pub fn is_parent_of ( parent : & Path , child : & Path ) -> bool {
240+ if !parent. is_absolute ( ) || child. is_absolute ( )
241+ || parent. components . len ( ) < child. components . len ( )
242+ || parent. components . is_empty ( ) {
243+ return false ;
244+ }
245+ let child_components = child. components ( ) . len ( ) ;
246+ let parent_components = parent. components ( ) . len ( ) ;
247+ let to_drop = parent. components . len ( ) - child_components;
248+ parent. components . slice ( to_drop, parent_components) == child. components
249+ }
250+
236251 fn components < ' a > ( & ' a self ) -> & ' a [ ~str ] ;
237252}
238253
@@ -1450,4 +1465,34 @@ mod tests {
14501465
14511466 }
14521467
1468+
1469+ #[ test]
1470+ fn test_is_parent_of( ) {
1471+ assert!( is_parent_of( & PosixPath ( "/a/b/c/d/e" ) , & PosixPath ( "c/d/e" ) ) ) ;
1472+ assert!( !is_parent_of( & PosixPath ( "a/b/c/d/e" ) , & PosixPath ( "c/d/e" ) ) ) ;
1473+ assert!( !is_parent_of( & PosixPath ( "/a/b/c/d/e" ) , & PosixPath ( "/c/d/e" ) ) ) ;
1474+ assert!( !is_parent_of( & PosixPath ( "" ) , & PosixPath ( "" ) ) ) ;
1475+ assert!( !is_parent_of( & PosixPath ( "" ) , & PosixPath ( "a/b/c" ) ) ) ;
1476+ assert!( is_parent_of( & PosixPath ( "/a/b/c" ) , & PosixPath ( "" ) ) ) ;
1477+ assert!( is_parent_of( & PosixPath ( "/a/b/c" ) , & PosixPath ( "a/b/c" ) ) ) ;
1478+ assert!( !is_parent_of( & PosixPath ( "/a/b/c" ) , & PosixPath ( "d/e/f" ) ) ) ;
1479+
1480+ let abcde = WindowsPath ( "C:\\ a\\ b\\ c\\ d\\ e" ) ;
1481+ let rel_abcde = WindowsPath ( "a\\ b\\ c\\ d\\ e" ) ;
1482+ let cde = WindowsPath ( "c\\ d\\ e" ) ;
1483+ let slashcde = WindowsPath ( "C:\\ c\\ d\\ e" ) ;
1484+ let empty = WindowsPath ( "" ) ;
1485+ let abc = WindowsPath ( "C:\\ a\\ b\\ c" ) ;
1486+ let rel_abc = WindowsPath ( "a\\ b\\ c" ) ;
1487+ let def = WindowsPath ( "d\\ e\\ f" ) ;
1488+
1489+ assert!( is_parent_of( & abcde, & cde) ) ;
1490+ assert!( !is_parent_of( & rel_abcde, & cde) ) ;
1491+ assert!( !is_parent_of( & abcde, & slashcde) ) ;
1492+ assert!( !is_parent_of( & empty, & empty) ) ;
1493+ assert!( is_parent_of( & abc, & empty) ;
1494+ assert!( is_parent_of( & abc, & rel_abc) ) ;
1495+ assert!( !is_parent_of( & abc, & def) ) ;
1496+ }
1497+
14531498}
0 commit comments