@@ -2,6 +2,9 @@ use crate::ffi::OsStr;
2
2
use crate :: mem;
3
3
use crate :: path:: Prefix ;
4
4
5
+ #[ cfg( test) ]
6
+ mod tests;
7
+
5
8
pub const MAIN_SEP_STR : & str = "\\ " ;
6
9
pub const MAIN_SEP : char = '\\' ;
7
10
@@ -43,7 +46,7 @@ pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
43
46
if let Some ( path) = path. strip_prefix ( br"?\" ) {
44
47
// \\?\UNC\server\share
45
48
if let Some ( path) = path. strip_prefix ( br"UNC\" ) {
46
- let ( server, share) = match parse_two_comps ( path, is_verbatim_sep) {
49
+ let ( server, share) = match get_first_two_components ( path, is_verbatim_sep) {
47
50
Some ( ( server, share) ) => {
48
51
( u8_slice_as_os_str ( server) , u8_slice_as_os_str ( share) )
49
52
}
@@ -71,7 +74,7 @@ pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
71
74
let slice = & path[ ..idx] ;
72
75
return Some ( DeviceNS ( u8_slice_as_os_str ( slice) ) ) ;
73
76
}
74
- match parse_two_comps ( path, is_sep_byte) {
77
+ match get_first_two_components ( path, is_sep_byte) {
75
78
Some ( ( server, share) ) if !server. is_empty ( ) && !share. is_empty ( ) => {
76
79
// \\server\share
77
80
return Some ( UNC ( u8_slice_as_os_str ( server) , u8_slice_as_os_str ( share) ) ) ;
@@ -86,13 +89,20 @@ pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
86
89
}
87
90
return None ;
88
91
}
89
-
90
- fn parse_two_comps ( mut path : & [ u8 ] , f : fn ( u8 ) -> bool ) -> Option < ( & [ u8 ] , & [ u8 ] ) > {
91
- let first = & path[ ..path. iter ( ) . position ( |x| f ( * x) ) ?] ;
92
- path = & path[ ( first. len ( ) + 1 ) ..] ;
93
- let idx = path. iter ( ) . position ( |x| f ( * x) ) ;
94
- let second = & path[ ..idx. unwrap_or ( path. len ( ) ) ] ;
95
- Some ( ( first, second) )
96
- }
97
92
}
98
93
94
+ /// Returns the first two path components with predicate `f`.
95
+ ///
96
+ /// The two components returned will be use by caller
97
+ /// to construct `VerbatimUNC` or `UNC` Windows path prefix.
98
+ ///
99
+ /// Returns [`None`] if there are no separators in path.
100
+ fn get_first_two_components ( path : & [ u8 ] , f : fn ( u8 ) -> bool ) -> Option < ( & [ u8 ] , & [ u8 ] ) > {
101
+ let idx = path. iter ( ) . position ( |& x| f ( x) ) ?;
102
+ // Panic safe
103
+ // The max `idx+1` is `path.len()` and `path[path.len()..]` is a valid index.
104
+ let ( first, path) = ( & path[ ..idx] , & path[ idx + 1 ..] ) ;
105
+ let idx = path. iter ( ) . position ( |& x| f ( x) ) . unwrap_or ( path. len ( ) ) ;
106
+ let second = & path[ ..idx] ;
107
+ Some ( ( first, second) )
108
+ }
0 commit comments