]> git.lizzy.rs Git - rust.git/blob - src/libstd/old_path/windows.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / libstd / old_path / windows.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //
11 // ignore-lexer-test FIXME #15883
12
13 //! Windows file path handling
14
15 use self::PathPrefix::*;
16
17 use ascii::AsciiExt;
18 use char::CharExt;
19 use clone::Clone;
20 use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd};
21 use fmt;
22 use hash;
23 use old_io::Writer;
24 use iter::{AdditiveIterator, Extend};
25 use iter::{Iterator, IteratorExt, Map, repeat};
26 use mem;
27 use option::Option::{self, Some, None};
28 use result::Result::{self, Ok, Err};
29 use slice::{SliceExt, SliceConcatExt};
30 use str::{SplitTerminator, FromStr, StrExt};
31 use string::{String, ToString};
32 use vec::Vec;
33
34 use super::{contains_nul, BytesContainer, GenericPath, GenericPathUnsafe};
35
36 /// Iterator that yields successive components of a Path as &str
37 ///
38 /// Each component is yielded as Option<&str> for compatibility with PosixPath, but
39 /// every component in WindowsPath is guaranteed to be Some.
40 pub type StrComponents<'a> =
41     Map<SplitTerminator<'a, char>, fn(&'a str) -> Option<&'a str>>;
42
43 /// Iterator that yields successive components of a Path as &[u8]
44 pub type Components<'a> =
45     Map<StrComponents<'a>, fn(Option<&str>) -> &[u8]>;
46
47 /// Represents a Windows path
48 // Notes for Windows path impl:
49 // The MAX_PATH is 260, but 253 is the practical limit due to some API bugs
50 // See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx for good information
51 // about windows paths.
52 // That same page puts a bunch of restrictions on allowed characters in a path.
53 // `\foo.txt` means "relative to current drive", but will not be considered to be absolute here
54 // as `∃P | P.join("\foo.txt") != "\foo.txt"`.
55 // `C:` is interesting, that means "the current directory on drive C".
56 // Long absolute paths need to have \\?\ prefix (or, for UNC, \\?\UNC\). I think that can be
57 // ignored for now, though, and only added in a hypothetical .to_pwstr() function.
58 // However, if a path is parsed that has \\?\, this needs to be preserved as it disables the
59 // processing of "." and ".." components and / as a separator.
60 // Experimentally, \\?\foo is not the same thing as \foo.
61 // Also, \\foo is not valid either (certainly not equivalent to \foo).
62 // Similarly, C:\\Users is not equivalent to C:\Users, although C:\Users\\foo is equivalent
63 // to C:\Users\foo. In fact the command prompt treats C:\\foo\bar as UNC path. But it might be
64 // best to just ignore that and normalize it to C:\foo\bar.
65 //
66 // Based on all this, I think the right approach is to do the following:
67 // * Require valid utf-8 paths. Windows API may use WCHARs, but we don't, and utf-8 is convertible
68 // to UTF-16 anyway (though does Windows use UTF-16 or UCS-2? Not sure).
69 // * Parse the prefixes \\?\UNC\, \\?\, and \\.\ explicitly.
70 // * If \\?\UNC\, treat following two path components as server\share. Don't error for missing
71 //   server\share.
72 // * If \\?\, parse disk from following component, if present. Don't error for missing disk.
73 // * If \\.\, treat rest of path as just regular components. I don't know how . and .. are handled
74 //   here, they probably aren't, but I'm not going to worry about that.
75 // * Else if starts with \\, treat following two components as server\share. Don't error for missing
76 //   server\share.
77 // * Otherwise, attempt to parse drive from start of path.
78 //
79 // The only error condition imposed here is valid utf-8. All other invalid paths are simply
80 // preserved by the data structure; let the Windows API error out on them.
81 #[derive(Clone)]
82 pub struct Path {
83     repr: String, // assumed to never be empty
84     prefix: Option<PathPrefix>,
85     sepidx: Option<uint> // index of the final separator in the non-prefix portion of repr
86 }
87
88 #[stable(feature = "rust1", since = "1.0.0")]
89 impl fmt::Debug for Path {
90     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91         fmt::Debug::fmt(&self.display(), f)
92     }
93 }
94
95 impl PartialEq for Path {
96     #[inline]
97     fn eq(&self, other: &Path) -> bool {
98         self.repr == other.repr
99     }
100 }
101
102 impl Eq for Path {}
103
104 impl PartialOrd for Path {
105     fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
106         Some(self.cmp(other))
107     }
108 }
109
110 impl Ord for Path {
111     fn cmp(&self, other: &Path) -> Ordering {
112         self.repr.cmp(&other.repr)
113     }
114 }
115
116 impl FromStr for Path {
117     type Err = ParsePathError;
118     fn from_str(s: &str) -> Result<Path, ParsePathError> {
119         match Path::new_opt(s) {
120             Some(p) => Ok(p),
121             None => Err(ParsePathError),
122         }
123     }
124 }
125
126 /// Value indicating that a path could not be parsed from a string.
127 #[derive(Debug, Clone, PartialEq, Copy)]
128 pub struct ParsePathError;
129
130 impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Path {
131     #[cfg(not(test))]
132     #[inline]
133     fn hash(&self, state: &mut S) {
134         self.repr.hash(state)
135     }
136
137     #[cfg(test)]
138     #[inline]
139     fn hash(&self, _: &mut S) {
140         // No-op because the `hash` implementation will be wrong.
141     }
142 }
143
144 impl BytesContainer for Path {
145     #[inline]
146     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
147         self.as_vec()
148     }
149     #[inline]
150     fn container_as_str<'a>(&'a self) -> Option<&'a str> {
151         self.as_str()
152     }
153     #[inline]
154     fn is_str(_: Option<&Path>) -> bool { true }
155 }
156
157 impl GenericPathUnsafe for Path {
158     /// See `GenericPathUnsafe::from_vec_unchecked`.
159     ///
160     /// # Panics
161     ///
162     /// Panics if not valid UTF-8.
163     #[inline]
164     unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
165         let (prefix, path) = Path::normalize_(path.container_as_str().unwrap());
166         assert!(!path.is_empty());
167         let mut ret = Path{ repr: path, prefix: prefix, sepidx: None };
168         ret.update_sepidx();
169         ret
170     }
171
172     /// See `GenericPathUnsafe::set_filename_unchecked`.
173     ///
174     /// # Panics
175     ///
176     /// Panics if not valid UTF-8.
177     unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
178         let filename = filename.container_as_str().unwrap();
179         match self.sepidx_or_prefix_len() {
180             None if ".." == self.repr => {
181                 let mut s = String::with_capacity(3 + filename.len());
182                 s.push_str("..");
183                 s.push(SEP);
184                 s.push_str(filename);
185                 self.update_normalized(&s[]);
186             }
187             None => {
188                 self.update_normalized(filename);
189             }
190             Some((_,idxa,end)) if &self.repr[idxa..end] == ".." => {
191                 let mut s = String::with_capacity(end + 1 + filename.len());
192                 s.push_str(&self.repr[..end]);
193                 s.push(SEP);
194                 s.push_str(filename);
195                 self.update_normalized(&s[]);
196             }
197             Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => {
198                 let mut s = String::with_capacity(idxb + filename.len());
199                 s.push_str(&self.repr[..idxb]);
200                 s.push_str(filename);
201                 self.update_normalized(&s[]);
202             }
203             Some((idxb,_,_)) => {
204                 let mut s = String::with_capacity(idxb + 1 + filename.len());
205                 s.push_str(&self.repr[..idxb]);
206                 s.push(SEP);
207                 s.push_str(filename);
208                 self.update_normalized(&s[]);
209             }
210         }
211     }
212
213     /// See `GenericPathUnsafe::push_unchecked`.
214     ///
215     /// Concatenating two Windows Paths is rather complicated.
216     /// For the most part, it will behave as expected, except in the case of
217     /// pushing a volume-relative path, e.g. `C:foo.txt`. Because we have no
218     /// concept of per-volume cwds like Windows does, we can't behave exactly
219     /// like Windows will. Instead, if the receiver is an absolute path on
220     /// the same volume as the new path, it will be treated as the cwd that
221     /// the new path is relative to. Otherwise, the new path will be treated
222     /// as if it were absolute and will replace the receiver outright.
223     unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
224         let path = path.container_as_str().unwrap();
225         fn is_vol_abs(path: &str, prefix: Option<PathPrefix>) -> bool {
226             // assume prefix is Some(DiskPrefix)
227             let rest = &path[prefix_len(prefix)..];
228             !rest.is_empty() && rest.as_bytes()[0].is_ascii() && is_sep(rest.as_bytes()[0] as char)
229         }
230         fn shares_volume(me: &Path, path: &str) -> bool {
231             // path is assumed to have a prefix of Some(DiskPrefix)
232             let repr = &me.repr[];
233             match me.prefix {
234                 Some(DiskPrefix) => {
235                     repr.as_bytes()[0] == path.as_bytes()[0].to_ascii_uppercase()
236                 }
237                 Some(VerbatimDiskPrefix) => {
238                     repr.as_bytes()[4] == path.as_bytes()[0].to_ascii_uppercase()
239                 }
240                 _ => false
241             }
242         }
243         fn is_sep_(prefix: Option<PathPrefix>, u: u8) -> bool {
244             if prefix_is_verbatim(prefix) { is_sep_verbatim(u as char) }
245             else { is_sep(u as char) }
246         }
247
248         fn replace_path(me: &mut Path, path: &str, prefix: Option<PathPrefix>) {
249             let newpath = Path::normalize__(path, prefix);
250             me.repr = match newpath {
251                 Some(p) => p,
252                 None => String::from_str(path)
253             };
254             me.prefix = prefix;
255             me.update_sepidx();
256         }
257         fn append_path(me: &mut Path, path: &str) {
258             // appends a path that has no prefix
259             // if me is verbatim, we need to pre-normalize the new path
260             let path_ = if is_verbatim(me) { Path::normalize__(path, None) }
261                         else { None };
262             let pathlen = path_.as_ref().map_or(path.len(), |p| p.len());
263             let mut s = String::with_capacity(me.repr.len() + 1 + pathlen);
264             s.push_str(&me.repr[]);
265             let plen = me.prefix_len();
266             // if me is "C:" we don't want to add a path separator
267             match me.prefix {
268                 Some(DiskPrefix) if me.repr.len() == plen => (),
269                 _ if !(me.repr.len() > plen && me.repr.as_bytes()[me.repr.len()-1] == SEP_BYTE) => {
270                     s.push(SEP);
271                 }
272                 _ => ()
273             }
274             match path_ {
275                 None => s.push_str(path),
276                 Some(p) => s.push_str(&p[]),
277             };
278             me.update_normalized(&s[])
279         }
280
281         if !path.is_empty() {
282             let prefix = parse_prefix(path);
283             match prefix {
284                 Some(DiskPrefix) if !is_vol_abs(path, prefix) && shares_volume(self, path) => {
285                     // cwd-relative path, self is on the same volume
286                     append_path(self, &path[prefix_len(prefix)..]);
287                 }
288                 Some(_) => {
289                     // absolute path, or cwd-relative and self is not same volume
290                     replace_path(self, path, prefix);
291                 }
292                 None if !path.is_empty() && is_sep_(self.prefix, path.as_bytes()[0]) => {
293                     // volume-relative path
294                     if self.prefix.is_some() {
295                         // truncate self down to the prefix, then append
296                         let n = self.prefix_len();
297                         self.repr.truncate(n);
298                         append_path(self, path);
299                     } else {
300                         // we have no prefix, so nothing to be relative to
301                         replace_path(self, path, prefix);
302                     }
303                 }
304                 None => {
305                     // relative path
306                     append_path(self, path);
307                 }
308             }
309         }
310     }
311 }
312
313 impl GenericPath for Path {
314     #[inline]
315     fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
316         match path.container_as_str() {
317             None => None,
318             Some(ref s) => {
319                 if contains_nul(s) {
320                     None
321                 } else {
322                     Some(unsafe { GenericPathUnsafe::new_unchecked(*s) })
323                 }
324             }
325         }
326     }
327
328     /// See `GenericPath::as_str` for info.
329     /// Always returns a `Some` value.
330     #[inline]
331     fn as_str<'a>(&'a self) -> Option<&'a str> {
332         Some(&self.repr[])
333     }
334
335     #[inline]
336     fn as_vec<'a>(&'a self) -> &'a [u8] {
337         self.repr.as_bytes()
338     }
339
340     #[inline]
341     fn into_vec(self) -> Vec<u8> {
342         self.repr.into_bytes()
343     }
344
345     #[inline]
346     fn dirname<'a>(&'a self) -> &'a [u8] {
347         self.dirname_str().unwrap().as_bytes()
348     }
349
350     /// See `GenericPath::dirname_str` for info.
351     /// Always returns a `Some` value.
352     fn dirname_str<'a>(&'a self) -> Option<&'a str> {
353         Some(match self.sepidx_or_prefix_len() {
354             None if ".." == self.repr => &self.repr[],
355             None => ".",
356             Some((_,idxa,end)) if &self.repr[idxa..end] == ".." => {
357                 &self.repr[]
358             }
359             Some((idxb,_,end)) if &self.repr[idxb..end] == "\\" => {
360                 &self.repr[]
361             }
362             Some((0,idxa,_)) => &self.repr[..idxa],
363             Some((idxb,idxa,_)) => {
364                 match self.prefix {
365                     Some(DiskPrefix) | Some(VerbatimDiskPrefix) if idxb == self.prefix_len() => {
366                         &self.repr[..idxa]
367                     }
368                     _ => &self.repr[..idxb]
369                 }
370             }
371         })
372     }
373
374     #[inline]
375     fn filename<'a>(&'a self) -> Option<&'a [u8]> {
376         self.filename_str().map(|x| x.as_bytes())
377     }
378
379     /// See `GenericPath::filename_str` for info.
380     /// Always returns a `Some` value if `filename` returns a `Some` value.
381     fn filename_str<'a>(&'a self) -> Option<&'a str> {
382         let repr = &self.repr[];
383         match self.sepidx_or_prefix_len() {
384             None if "." == repr || ".." == repr => None,
385             None => Some(repr),
386             Some((_,idxa,end)) if &repr[idxa..end] == ".." => None,
387             Some((_,idxa,end)) if idxa == end => None,
388             Some((_,idxa,end)) => Some(&repr[idxa..end])
389         }
390     }
391
392     /// See `GenericPath::filestem_str` for info.
393     /// Always returns a `Some` value if `filestem` returns a `Some` value.
394     #[inline]
395     fn filestem_str<'a>(&'a self) -> Option<&'a str> {
396         // filestem() returns a byte vector that's guaranteed valid UTF-8
397         self.filestem().map(|t| unsafe { mem::transmute(t) })
398     }
399
400     #[inline]
401     fn extension_str<'a>(&'a self) -> Option<&'a str> {
402         // extension() returns a byte vector that's guaranteed valid UTF-8
403         self.extension().map(|t| unsafe { mem::transmute(t) })
404     }
405
406     fn dir_path(&self) -> Path {
407         unsafe { GenericPathUnsafe::new_unchecked(self.dirname_str().unwrap()) }
408     }
409
410     #[inline]
411     fn pop(&mut self) -> bool {
412         match self.sepidx_or_prefix_len() {
413             None if "." == self.repr => false,
414             None => {
415                 self.repr = String::from_str(".");
416                 self.sepidx = None;
417                 true
418             }
419             Some((idxb,idxa,end)) if idxb == idxa && idxb == end => false,
420             Some((idxb,_,end)) if &self.repr[idxb..end] == "\\" => false,
421             Some((idxb,idxa,_)) => {
422                 let trunc = match self.prefix {
423                     Some(DiskPrefix) | Some(VerbatimDiskPrefix) | None => {
424                         let plen = self.prefix_len();
425                         if idxb == plen { idxa } else { idxb }
426                     }
427                     _ => idxb
428                 };
429                 self.repr.truncate(trunc);
430                 self.update_sepidx();
431                 true
432             }
433         }
434     }
435
436     fn root_path(&self) -> Option<Path> {
437         if self.prefix.is_some() {
438             Some(Path::new(match self.prefix {
439                 Some(DiskPrefix) if self.is_absolute() => {
440                     &self.repr[..self.prefix_len()+1]
441                 }
442                 Some(VerbatimDiskPrefix) => {
443                     &self.repr[..self.prefix_len()+1]
444                 }
445                 _ => &self.repr[..self.prefix_len()]
446             }))
447         } else if is_vol_relative(self) {
448             Some(Path::new(&self.repr[..1]))
449         } else {
450             None
451         }
452     }
453
454     /// See `GenericPath::is_absolute` for info.
455     ///
456     /// A Windows Path is considered absolute only if it has a non-volume prefix,
457     /// or if it has a volume prefix and the path starts with '\'.
458     /// A path of `\foo` is not considered absolute because it's actually
459     /// relative to the "current volume". A separate method `Path::is_vol_relative`
460     /// is provided to indicate this case. Similarly a path of `C:foo` is not
461     /// considered absolute because it's relative to the cwd on volume C:. A
462     /// separate method `Path::is_cwd_relative` is provided to indicate this case.
463     #[inline]
464     fn is_absolute(&self) -> bool {
465         match self.prefix {
466             Some(DiskPrefix) => {
467                 let rest = &self.repr[self.prefix_len()..];
468                 rest.len() > 0 && rest.as_bytes()[0] == SEP_BYTE
469             }
470             Some(_) => true,
471             None => false
472         }
473     }
474
475     #[inline]
476     fn is_relative(&self) -> bool {
477         self.prefix.is_none() && !is_vol_relative(self)
478     }
479
480     fn is_ancestor_of(&self, other: &Path) -> bool {
481         if !self.equiv_prefix(other) {
482             false
483         } else if self.is_absolute() != other.is_absolute() ||
484                   is_vol_relative(self) != is_vol_relative(other) {
485             false
486         } else {
487             let mut ita = self.str_components().map(|x|x.unwrap());
488             let mut itb = other.str_components().map(|x|x.unwrap());
489             if "." == self.repr {
490                 return itb.next() != Some("..");
491             }
492             loop {
493                 match (ita.next(), itb.next()) {
494                     (None, _) => break,
495                     (Some(a), Some(b)) if a == b => { continue },
496                     (Some(a), _) if a == ".." => {
497                         // if ita contains only .. components, it's an ancestor
498                         return ita.all(|x| x == "..");
499                     }
500                     _ => return false
501                 }
502             }
503             true
504         }
505     }
506
507     fn path_relative_from(&self, base: &Path) -> Option<Path> {
508         fn comp_requires_verbatim(s: &str) -> bool {
509             s == "." || s == ".." || s.contains_char(SEP2)
510         }
511
512         if !self.equiv_prefix(base) {
513             // prefixes differ
514             if self.is_absolute() {
515                 Some(self.clone())
516             } else if self.prefix == Some(DiskPrefix) && base.prefix == Some(DiskPrefix) {
517                 // both drives, drive letters must differ or they'd be equiv
518                 Some(self.clone())
519             } else {
520                 None
521             }
522         } else if self.is_absolute() != base.is_absolute() {
523             if self.is_absolute() {
524                 Some(self.clone())
525             } else {
526                 None
527             }
528         } else if is_vol_relative(self) != is_vol_relative(base) {
529             if is_vol_relative(self) {
530                 Some(self.clone())
531             } else {
532                 None
533             }
534         } else {
535             let mut ita = self.str_components().map(|x|x.unwrap());
536             let mut itb = base.str_components().map(|x|x.unwrap());
537             let mut comps = vec![];
538
539             let a_verb = is_verbatim(self);
540             let b_verb = is_verbatim(base);
541             loop {
542                 match (ita.next(), itb.next()) {
543                     (None, None) => break,
544                     (Some(a), None) if a_verb && comp_requires_verbatim(a) => {
545                         return Some(self.clone())
546                     }
547                     (Some(a), None) => {
548                         comps.push(a);
549                         if !a_verb {
550                             comps.extend(ita.by_ref());
551                             break;
552                         }
553                     }
554                     (None, _) => comps.push(".."),
555                     (Some(a), Some(b)) if comps.is_empty() && a == b => (),
556                     (Some(a), Some(b)) if !b_verb && b == "." => {
557                         if a_verb && comp_requires_verbatim(a) {
558                             return Some(self.clone())
559                         } else { comps.push(a) }
560                     }
561                     (Some(_), Some(b)) if !b_verb && b == ".." => return None,
562                     (Some(a), Some(_)) if a_verb && comp_requires_verbatim(a) => {
563                         return Some(self.clone())
564                     }
565                     (Some(a), Some(_)) => {
566                         comps.push("..");
567                         for _ in itb.by_ref() {
568                             comps.push("..");
569                         }
570                         comps.push(a);
571                         if !a_verb {
572                             comps.extend(ita.by_ref());
573                             break;
574                         }
575                     }
576                 }
577             }
578             Some(Path::new(comps.connect("\\")))
579         }
580     }
581
582     fn ends_with_path(&self, child: &Path) -> bool {
583         if !child.is_relative() { return false; }
584         let mut selfit = self.str_components().rev();
585         let mut childit = child.str_components().rev();
586         loop {
587             match (selfit.next(), childit.next()) {
588                 (Some(a), Some(b)) => if a != b { return false; },
589                 (Some(_), None) => break,
590                 (None, Some(_)) => return false,
591                 (None, None) => break
592             }
593         }
594         true
595     }
596 }
597
598 impl Path {
599     /// Returns a new `Path` from a `BytesContainer`.
600     ///
601     /// # Panics
602     ///
603     /// Panics if the vector contains a `NUL`, or if it contains invalid UTF-8.
604     ///
605     /// # Example
606     ///
607     /// ```
608     /// println!("{}", Path::new(r"C:\some\path").display());
609     /// ```
610     #[inline]
611     pub fn new<T: BytesContainer>(path: T) -> Path {
612         GenericPath::new(path)
613     }
614
615     /// Returns a new `Some(Path)` from a `BytesContainer`.
616     ///
617     /// Returns `None` if the vector contains a `NUL`, or if it contains invalid UTF-8.
618     ///
619     /// # Example
620     ///
621     /// ```
622     /// let path = Path::new_opt(r"C:\some\path");
623     ///
624     /// match path {
625     ///     Some(path) => println!("{}", path.display()),
626     ///     None       => println!("There was a problem with your path."),
627     /// }
628     /// ```
629     #[inline]
630     pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
631         GenericPath::new_opt(path)
632     }
633
634     /// Returns an iterator that yields each component of the path in turn as a Option<&str>.
635     /// Every component is guaranteed to be Some.
636     /// Does not yield the path prefix (including server/share components in UNC paths).
637     /// Does not distinguish between volume-relative and relative paths, e.g.
638     /// \a\b\c and a\b\c.
639     /// Does not distinguish between absolute and cwd-relative paths, e.g.
640     /// C:\foo and C:foo.
641     pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
642         let repr = &self.repr[];
643         let s = match self.prefix {
644             Some(_) => {
645                 let plen = self.prefix_len();
646                 if repr.len() > plen && repr.as_bytes()[plen] == SEP_BYTE {
647                     &repr[plen+1..]
648                 } else { &repr[plen..] }
649             }
650             None if repr.as_bytes()[0] == SEP_BYTE => &repr[1..],
651             None => repr
652         };
653         let some: fn(&'a str) -> Option<&'a str> = Some; // coerce to fn ptr
654         let ret = s.split_terminator(SEP).map(some);
655         ret
656     }
657
658     /// Returns an iterator that yields each component of the path in turn as a &[u8].
659     /// See str_components() for details.
660     pub fn components<'a>(&'a self) -> Components<'a> {
661         fn convert<'a>(x: Option<&'a str>) -> &'a [u8] {
662             #![inline]
663             x.unwrap().as_bytes()
664         }
665         let convert: for<'b> fn(Option<&'b str>) -> &'b [u8] = convert; // coerce to fn ptr
666         self.str_components().map(convert)
667     }
668
669     fn equiv_prefix(&self, other: &Path) -> bool {
670         let s_repr = &self.repr[];
671         let o_repr = &other.repr[];
672         match (self.prefix, other.prefix) {
673             (Some(DiskPrefix), Some(VerbatimDiskPrefix)) => {
674                 self.is_absolute() &&
675                     s_repr.as_bytes()[0].to_ascii_lowercase() ==
676                         o_repr.as_bytes()[4].to_ascii_lowercase()
677             }
678             (Some(VerbatimDiskPrefix), Some(DiskPrefix)) => {
679                 other.is_absolute() &&
680                     s_repr.as_bytes()[4].to_ascii_lowercase() ==
681                         o_repr.as_bytes()[0].to_ascii_lowercase()
682             }
683             (Some(VerbatimDiskPrefix), Some(VerbatimDiskPrefix)) => {
684                 s_repr.as_bytes()[4].to_ascii_lowercase() ==
685                     o_repr.as_bytes()[4].to_ascii_lowercase()
686             }
687             (Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => {
688                 &s_repr[2..self.prefix_len()] == &o_repr[8..other.prefix_len()]
689             }
690             (Some(VerbatimUNCPrefix(_,_)), Some(UNCPrefix(_,_))) => {
691                 &s_repr[8..self.prefix_len()] == &o_repr[2..other.prefix_len()]
692             }
693             (None, None) => true,
694             (a, b) if a == b => {
695                 &s_repr[..self.prefix_len()] == &o_repr[..other.prefix_len()]
696             }
697             _ => false
698         }
699     }
700
701     fn normalize_(s: &str) -> (Option<PathPrefix>, String) {
702         // make borrowck happy
703         let (prefix, val) = {
704             let prefix = parse_prefix(s);
705             let path = Path::normalize__(s, prefix);
706             (prefix, path)
707         };
708         (prefix, match val {
709             None => s.to_string(),
710             Some(val) => val
711         })
712     }
713
714     fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<String> {
715         if prefix_is_verbatim(prefix) {
716             // don't do any normalization
717             match prefix {
718                 Some(VerbatimUNCPrefix(x, 0)) if s.len() == 8 + x => {
719                     // the server component has no trailing '\'
720                     let mut s = String::from_str(s);
721                     s.push(SEP);
722                     Some(s)
723                 }
724                 _ => None
725             }
726         } else {
727             let (is_abs, comps) = normalize_helper(s, prefix);
728             let mut comps = comps;
729             match (comps.is_some(),prefix) {
730                 (false, Some(DiskPrefix)) => {
731                     if s.as_bytes()[0] >= b'a' && s.as_bytes()[0] <= b'z' {
732                         comps = Some(vec![]);
733                     }
734                 }
735                 (false, Some(VerbatimDiskPrefix)) => {
736                     if s.as_bytes()[4] >= b'a' && s.as_bytes()[0] <= b'z' {
737                         comps = Some(vec![]);
738                     }
739                 }
740                 _ => ()
741             }
742             match comps {
743                 None => None,
744                 Some(comps) => {
745                     if prefix.is_some() && comps.is_empty() {
746                         match prefix.unwrap() {
747                             DiskPrefix => {
748                                 let len = prefix_len(prefix) + is_abs as uint;
749                                 let mut s = String::from_str(&s[..len]);
750                                 unsafe {
751                                     let v = s.as_mut_vec();
752                                     v[0] = (*v)[0].to_ascii_uppercase();
753                                 }
754                                 if is_abs {
755                                     // normalize C:/ to C:\
756                                     unsafe {
757                                         s.as_mut_vec()[2] = SEP_BYTE;
758                                     }
759                                 }
760                                 Some(s)
761                             }
762                             VerbatimDiskPrefix => {
763                                 let len = prefix_len(prefix) + is_abs as uint;
764                                 let mut s = String::from_str(&s[..len]);
765                                 unsafe {
766                                     let v = s.as_mut_vec();
767                                     v[4] = (*v)[4].to_ascii_uppercase();
768                                 }
769                                 Some(s)
770                             }
771                             _ => {
772                                 let plen = prefix_len(prefix);
773                                 if s.len() > plen {
774                                     Some(String::from_str(&s[..plen]))
775                                 } else { None }
776                             }
777                         }
778                     } else if is_abs && comps.is_empty() {
779                         Some(repeat(SEP).take(1).collect())
780                     } else {
781                         let prefix_ = &s[..prefix_len(prefix)];
782                         let n = prefix_.len() +
783                                 if is_abs { comps.len() } else { comps.len() - 1} +
784                                 comps.iter().map(|v| v.len()).sum();
785                         let mut s = String::with_capacity(n);
786                         match prefix {
787                             Some(DiskPrefix) => {
788                                 s.push(prefix_.as_bytes()[0].to_ascii_uppercase() as char);
789                                 s.push(':');
790                             }
791                             Some(VerbatimDiskPrefix) => {
792                                 s.push_str(&prefix_[..4]);
793                                 s.push(prefix_.as_bytes()[4].to_ascii_uppercase() as char);
794                                 s.push_str(&prefix_[5..]);
795                             }
796                             Some(UNCPrefix(a,b)) => {
797                                 s.push_str("\\\\");
798                                 s.push_str(&prefix_[2..a+2]);
799                                 s.push(SEP);
800                                 s.push_str(&prefix_[3+a..3+a+b]);
801                             }
802                             Some(_) => s.push_str(prefix_),
803                             None => ()
804                         }
805                         let mut it = comps.into_iter();
806                         if !is_abs {
807                             match it.next() {
808                                 None => (),
809                                 Some(comp) => s.push_str(comp)
810                             }
811                         }
812                         for comp in it {
813                             s.push(SEP);
814                             s.push_str(comp);
815                         }
816                         Some(s)
817                     }
818                 }
819             }
820         }
821     }
822
823     fn update_sepidx(&mut self) {
824         let s = if self.has_nonsemantic_trailing_slash() {
825                     &self.repr[..self.repr.len()-1]
826                 } else { &self.repr[] };
827         let sep_test: fn(char) -> bool = if !prefix_is_verbatim(self.prefix) {
828             is_sep
829         } else {
830             is_sep_verbatim
831         };
832         let idx = s.rfind(sep_test);
833         let prefixlen = self.prefix_len();
834         self.sepidx = idx.and_then(|x| if x < prefixlen { None } else { Some(x) });
835     }
836
837     fn prefix_len(&self) -> uint {
838         prefix_len(self.prefix)
839     }
840
841     // Returns a tuple (before, after, end) where before is the index of the separator
842     // and after is the index just after the separator.
843     // end is the length of the string, normally, or the index of the final character if it is
844     // a non-semantic trailing separator in a verbatim string.
845     // If the prefix is considered the separator, before and after are the same.
846     fn sepidx_or_prefix_len(&self) -> Option<(uint,uint,uint)> {
847         match self.sepidx {
848             None => match self.prefix_len() { 0 => None, x => Some((x,x,self.repr.len())) },
849             Some(x) => {
850                 if self.has_nonsemantic_trailing_slash() {
851                     Some((x,x+1,self.repr.len()-1))
852                 } else { Some((x,x+1,self.repr.len())) }
853             }
854         }
855     }
856
857     fn has_nonsemantic_trailing_slash(&self) -> bool {
858         is_verbatim(self) && self.repr.len() > self.prefix_len()+1 &&
859             self.repr.as_bytes()[self.repr.len()-1] == SEP_BYTE
860     }
861
862     fn update_normalized(&mut self, s: &str) {
863         let (prefix, path) = Path::normalize_(s);
864         self.repr = path;
865         self.prefix = prefix;
866         self.update_sepidx();
867     }
868 }
869
870 /// Returns whether the path is considered "volume-relative", which means a path
871 /// that looks like "\foo". Paths of this form are relative to the current volume,
872 /// but absolute within that volume.
873 #[inline]
874 pub fn is_vol_relative(path: &Path) -> bool {
875     path.prefix.is_none() && is_sep_byte(&path.repr.as_bytes()[0])
876 }
877
878 /// Returns whether the path is considered "cwd-relative", which means a path
879 /// with a volume prefix that is not absolute. This look like "C:foo.txt". Paths
880 /// of this form are relative to the cwd on the given volume.
881 #[inline]
882 pub fn is_cwd_relative(path: &Path) -> bool {
883     path.prefix == Some(DiskPrefix) && !path.is_absolute()
884 }
885
886 /// Returns the PathPrefix for this Path
887 #[inline]
888 pub fn prefix(path: &Path) -> Option<PathPrefix> {
889     path.prefix
890 }
891
892 /// Returns whether the Path's prefix is a verbatim prefix, i.e. `\\?\`
893 #[inline]
894 pub fn is_verbatim(path: &Path) -> bool {
895     prefix_is_verbatim(path.prefix)
896 }
897
898 /// Returns the non-verbatim equivalent of the input path, if possible.
899 /// If the input path is a device namespace path, None is returned.
900 /// If the input path is not verbatim, it is returned as-is.
901 /// If the input path is verbatim, but the same path can be expressed as
902 /// non-verbatim, the non-verbatim version is returned.
903 /// Otherwise, None is returned.
904 pub fn make_non_verbatim(path: &Path) -> Option<Path> {
905     let repr = &path.repr[];
906     let new_path = match path.prefix {
907         Some(VerbatimPrefix(_)) | Some(DeviceNSPrefix(_)) => return None,
908         Some(UNCPrefix(_,_)) | Some(DiskPrefix) | None => return Some(path.clone()),
909         Some(VerbatimDiskPrefix) => {
910             // \\?\D:\
911             Path::new(&repr[4..])
912         }
913         Some(VerbatimUNCPrefix(_,_)) => {
914             // \\?\UNC\server\share
915             Path::new(format!(r"\{}", &repr[7..]))
916         }
917     };
918     if new_path.prefix.is_none() {
919         // \\?\UNC\server is a VerbatimUNCPrefix
920         // but \\server is nothing
921         return None;
922     }
923     // now ensure normalization didn't change anything
924     if &repr[path.prefix_len()..] == &new_path.repr[new_path.prefix_len()..] {
925         Some(new_path)
926     } else {
927         None
928     }
929 }
930
931 /// The standard path separator character
932 pub const SEP: char = '\\';
933 /// The standard path separator byte
934 pub const SEP_BYTE: u8 = SEP as u8;
935
936 /// The alternative path separator character
937 pub const SEP2: char = '/';
938 /// The alternative path separator character
939 pub const SEP2_BYTE: u8 = SEP2 as u8;
940
941 /// Returns whether the given char is a path separator.
942 /// Allows both the primary separator '\' and the alternative separator '/'.
943 #[inline]
944 pub fn is_sep(c: char) -> bool {
945     c == SEP || c == SEP2
946 }
947
948 /// Returns whether the given char is a path separator.
949 /// Only allows the primary separator '\'; use is_sep to allow '/'.
950 #[inline]
951 pub fn is_sep_verbatim(c: char) -> bool {
952     c == SEP
953 }
954
955 /// Returns whether the given byte is a path separator.
956 /// Allows both the primary separator '\' and the alternative separator '/'.
957 #[inline]
958 pub fn is_sep_byte(u: &u8) -> bool {
959     *u == SEP_BYTE || *u == SEP2_BYTE
960 }
961
962 /// Returns whether the given byte is a path separator.
963 /// Only allows the primary separator '\'; use is_sep_byte to allow '/'.
964 #[inline]
965 pub fn is_sep_byte_verbatim(u: &u8) -> bool {
966     *u == SEP_BYTE
967 }
968
969 /// Prefix types for Path
970 #[derive(Copy, PartialEq, Clone, Debug)]
971 pub enum PathPrefix {
972     /// Prefix `\\?\`, uint is the length of the following component
973     VerbatimPrefix(uint),
974     /// Prefix `\\?\UNC\`, uints are the lengths of the UNC components
975     VerbatimUNCPrefix(uint, uint),
976     /// Prefix `\\?\C:\` (for any alphabetic character)
977     VerbatimDiskPrefix,
978     /// Prefix `\\.\`, uint is the length of the following component
979     DeviceNSPrefix(uint),
980     /// UNC prefix `\\server\share`, uints are the lengths of the server/share
981     UNCPrefix(uint, uint),
982     /// Prefix `C:` for any alphabetic character
983     DiskPrefix
984 }
985
986 fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> {
987     if path.starts_with("\\\\") {
988         // \\
989         path = &path[2..];
990         if path.starts_with("?\\") {
991             // \\?\
992             path = &path[2..];
993             if path.starts_with("UNC\\") {
994                 // \\?\UNC\server\share
995                 path = &path[4..];
996                 let (idx_a, idx_b) = match parse_two_comps(path, is_sep_verbatim) {
997                     Some(x) => x,
998                     None => (path.len(), 0)
999                 };
1000                 return Some(VerbatimUNCPrefix(idx_a, idx_b));
1001             } else {
1002                 // \\?\path
1003                 let idx = path.find('\\');
1004                 if idx == Some(2) && path.as_bytes()[1] == b':' {
1005                     let c = path.as_bytes()[0];
1006                     if c.is_ascii() && (c as char).is_alphabetic() {
1007                         // \\?\C:\ path
1008                         return Some(VerbatimDiskPrefix);
1009                     }
1010                 }
1011                 let idx = idx.unwrap_or(path.len());
1012                 return Some(VerbatimPrefix(idx));
1013             }
1014         } else if path.starts_with(".\\") {
1015             // \\.\path
1016             path = &path[2..];
1017             let idx = path.find('\\').unwrap_or(path.len());
1018             return Some(DeviceNSPrefix(idx));
1019         }
1020         match parse_two_comps(path, is_sep) {
1021             Some((idx_a, idx_b)) if idx_a > 0 && idx_b > 0 => {
1022                 // \\server\share
1023                 return Some(UNCPrefix(idx_a, idx_b));
1024             }
1025             _ => ()
1026         }
1027     } else if path.len() > 1 && path.as_bytes()[1] == b':' {
1028         // C:
1029         let c = path.as_bytes()[0];
1030         if c.is_ascii() && (c as char).is_alphabetic() {
1031             return Some(DiskPrefix);
1032         }
1033     }
1034     return None;
1035
1036     fn parse_two_comps(mut path: &str, f: fn(char) -> bool) -> Option<(uint, uint)> {
1037         let idx_a = match path.find(f) {
1038             None => return None,
1039             Some(x) => x
1040         };
1041         path = &path[idx_a+1..];
1042         let idx_b = path.find(f).unwrap_or(path.len());
1043         Some((idx_a, idx_b))
1044     }
1045 }
1046
1047 // None result means the string didn't need normalizing
1048 fn normalize_helper<'a>(s: &'a str, prefix: Option<PathPrefix>) -> (bool, Option<Vec<&'a str>>) {
1049     let f: fn(char) -> bool = if !prefix_is_verbatim(prefix) {
1050         is_sep
1051     } else {
1052         is_sep_verbatim
1053     };
1054     let is_abs = s.len() > prefix_len(prefix) && f(s.char_at(prefix_len(prefix)));
1055     let s_ = &s[prefix_len(prefix)..];
1056     let s_ = if is_abs { &s_[1..] } else { s_ };
1057
1058     if is_abs && s_.is_empty() {
1059         return (is_abs, match prefix {
1060             Some(DiskPrefix) | None => (if is_sep_verbatim(s.char_at(prefix_len(prefix))) { None }
1061                                         else { Some(vec![]) }),
1062             Some(_) => Some(vec![]), // need to trim the trailing separator
1063         });
1064     }
1065     let mut comps: Vec<&'a str> = vec![];
1066     let mut n_up = 0;
1067     let mut changed = false;
1068     for comp in s_.split(f) {
1069         if comp.is_empty() { changed = true }
1070         else if comp == "." { changed = true }
1071         else if comp == ".." {
1072             let has_abs_prefix = match prefix {
1073                 Some(DiskPrefix) => false,
1074                 Some(_) => true,
1075                 None => false
1076             };
1077             if (is_abs || has_abs_prefix) && comps.is_empty() { changed = true }
1078             else if comps.len() == n_up { comps.push(".."); n_up += 1 }
1079             else { comps.pop().unwrap(); changed = true }
1080         } else { comps.push(comp) }
1081     }
1082     if !changed && !prefix_is_verbatim(prefix) {
1083         changed = s.find(is_sep).is_some();
1084     }
1085     if changed {
1086         if comps.is_empty() && !is_abs && prefix.is_none() {
1087             if s == "." {
1088                 return (is_abs, None);
1089             }
1090             comps.push(".");
1091         }
1092         (is_abs, Some(comps))
1093     } else {
1094         (is_abs, None)
1095     }
1096 }
1097
1098 fn prefix_is_verbatim(p: Option<PathPrefix>) -> bool {
1099     match p {
1100         Some(VerbatimPrefix(_)) | Some(VerbatimUNCPrefix(_,_)) | Some(VerbatimDiskPrefix) => true,
1101         Some(DeviceNSPrefix(_)) => true, // not really sure, but I think so
1102         _ => false
1103     }
1104 }
1105
1106 fn prefix_len(p: Option<PathPrefix>) -> uint {
1107     match p {
1108         None => 0,
1109         Some(VerbatimPrefix(x)) => 4 + x,
1110         Some(VerbatimUNCPrefix(x,y)) => 8 + x + 1 + y,
1111         Some(VerbatimDiskPrefix) => 6,
1112         Some(UNCPrefix(x,y)) => 2 + x + 1 + y,
1113         Some(DeviceNSPrefix(x)) => 4 + x,
1114         Some(DiskPrefix) => 2
1115     }
1116 }
1117
1118 #[cfg(test)]
1119 mod tests {
1120     use super::PathPrefix::*;
1121     use super::parse_prefix;
1122     use super::*;
1123
1124     use clone::Clone;
1125     use iter::IteratorExt;
1126     use option::Option::{self, Some, None};
1127     use old_path::GenericPath;
1128     use slice::{AsSlice, SliceExt};
1129     use str::Str;
1130     use string::ToString;
1131     use vec::Vec;
1132
1133     macro_rules! t {
1134         (s: $path:expr, $exp:expr) => (
1135             {
1136                 let path = $path;
1137                 assert_eq!(path.as_str(), Some($exp));
1138             }
1139         );
1140         (v: $path:expr, $exp:expr) => (
1141             {
1142                 let path = $path;
1143                 assert_eq!(path.as_vec(), $exp);
1144             }
1145         )
1146     }
1147
1148     #[test]
1149     fn test_parse_prefix() {
1150         macro_rules! t {
1151             ($path:expr, $exp:expr) => (
1152                 {
1153                     let path = $path;
1154                     let exp = $exp;
1155                     let res = parse_prefix(path);
1156                     assert_eq!(res, exp);
1157                 }
1158             )
1159         }
1160
1161         t!("\\\\SERVER\\share\\foo", Some(UNCPrefix(6,5)));
1162         t!("\\\\", None);
1163         t!("\\\\SERVER", None);
1164         t!("\\\\SERVER\\", None);
1165         t!("\\\\SERVER\\\\", None);
1166         t!("\\\\SERVER\\\\foo", None);
1167         t!("\\\\SERVER\\share", Some(UNCPrefix(6,5)));
1168         t!("\\\\SERVER/share/foo", Some(UNCPrefix(6,5)));
1169         t!("\\\\SERVER\\share/foo", Some(UNCPrefix(6,5)));
1170         t!("//SERVER/share/foo", None);
1171         t!("\\\\\\a\\b\\c", None);
1172         t!("\\\\?\\a\\b\\c", Some(VerbatimPrefix(1)));
1173         t!("\\\\?\\a/b/c", Some(VerbatimPrefix(5)));
1174         t!("//?/a/b/c", None);
1175         t!("\\\\.\\a\\b", Some(DeviceNSPrefix(1)));
1176         t!("\\\\.\\a/b", Some(DeviceNSPrefix(3)));
1177         t!("//./a/b", None);
1178         t!("\\\\?\\UNC\\server\\share\\foo", Some(VerbatimUNCPrefix(6,5)));
1179         t!("\\\\?\\UNC\\\\share\\foo", Some(VerbatimUNCPrefix(0,5)));
1180         t!("\\\\?\\UNC\\", Some(VerbatimUNCPrefix(0,0)));
1181         t!("\\\\?\\UNC\\server/share/foo", Some(VerbatimUNCPrefix(16,0)));
1182         t!("\\\\?\\UNC\\server", Some(VerbatimUNCPrefix(6,0)));
1183         t!("\\\\?\\UNC\\server\\", Some(VerbatimUNCPrefix(6,0)));
1184         t!("\\\\?\\UNC/server/share", Some(VerbatimPrefix(16)));
1185         t!("\\\\?\\UNC", Some(VerbatimPrefix(3)));
1186         t!("\\\\?\\C:\\a\\b.txt", Some(VerbatimDiskPrefix));
1187         t!("\\\\?\\z:\\", Some(VerbatimDiskPrefix));
1188         t!("\\\\?\\C:", Some(VerbatimPrefix(2)));
1189         t!("\\\\?\\C:a.txt", Some(VerbatimPrefix(7)));
1190         t!("\\\\?\\C:a\\b.txt", Some(VerbatimPrefix(3)));
1191         t!("\\\\?\\C:/a", Some(VerbatimPrefix(4)));
1192         t!("C:\\foo", Some(DiskPrefix));
1193         t!("z:/foo", Some(DiskPrefix));
1194         t!("d:", Some(DiskPrefix));
1195         t!("ab:", None);
1196         t!("ü:\\foo", None);
1197         t!("3:\\foo", None);
1198         t!(" :\\foo", None);
1199         t!("::\\foo", None);
1200         t!("\\\\?\\C:", Some(VerbatimPrefix(2)));
1201         t!("\\\\?\\z:\\", Some(VerbatimDiskPrefix));
1202         t!("\\\\?\\ab:\\", Some(VerbatimPrefix(3)));
1203         t!("\\\\?\\C:\\a", Some(VerbatimDiskPrefix));
1204         t!("\\\\?\\C:/a", Some(VerbatimPrefix(4)));
1205         t!("\\\\?\\C:\\a/b", Some(VerbatimDiskPrefix));
1206     }
1207
1208     #[test]
1209     fn test_paths() {
1210         let empty: &[u8] = &[];
1211         t!(v: Path::new(empty), b".");
1212         t!(v: Path::new(b"\\"), b"\\");
1213         t!(v: Path::new(b"a\\b\\c"), b"a\\b\\c");
1214
1215         t!(s: Path::new(""), ".");
1216         t!(s: Path::new("\\"), "\\");
1217         t!(s: Path::new("hi"), "hi");
1218         t!(s: Path::new("hi\\"), "hi");
1219         t!(s: Path::new("\\lib"), "\\lib");
1220         t!(s: Path::new("\\lib\\"), "\\lib");
1221         t!(s: Path::new("hi\\there"), "hi\\there");
1222         t!(s: Path::new("hi\\there.txt"), "hi\\there.txt");
1223         t!(s: Path::new("/"), "\\");
1224         t!(s: Path::new("hi/"), "hi");
1225         t!(s: Path::new("/lib"), "\\lib");
1226         t!(s: Path::new("/lib/"), "\\lib");
1227         t!(s: Path::new("hi/there"), "hi\\there");
1228
1229         t!(s: Path::new("hi\\there\\"), "hi\\there");
1230         t!(s: Path::new("hi\\..\\there"), "there");
1231         t!(s: Path::new("hi/../there"), "there");
1232         t!(s: Path::new("..\\hi\\there"), "..\\hi\\there");
1233         t!(s: Path::new("\\..\\hi\\there"), "\\hi\\there");
1234         t!(s: Path::new("/../hi/there"), "\\hi\\there");
1235         t!(s: Path::new("foo\\.."), ".");
1236         t!(s: Path::new("\\foo\\.."), "\\");
1237         t!(s: Path::new("\\foo\\..\\.."), "\\");
1238         t!(s: Path::new("\\foo\\..\\..\\bar"), "\\bar");
1239         t!(s: Path::new("\\.\\hi\\.\\there\\."), "\\hi\\there");
1240         t!(s: Path::new("\\.\\hi\\.\\there\\.\\.."), "\\hi");
1241         t!(s: Path::new("foo\\..\\.."), "..");
1242         t!(s: Path::new("foo\\..\\..\\.."), "..\\..");
1243         t!(s: Path::new("foo\\..\\..\\bar"), "..\\bar");
1244
1245         assert_eq!(Path::new(b"foo\\bar").into_vec(), b"foo\\bar");
1246         assert_eq!(Path::new(b"\\foo\\..\\..\\bar").into_vec(), b"\\bar");
1247
1248         t!(s: Path::new("\\\\a"), "\\a");
1249         t!(s: Path::new("\\\\a\\"), "\\a");
1250         t!(s: Path::new("\\\\a\\b"), "\\\\a\\b");
1251         t!(s: Path::new("\\\\a\\b\\"), "\\\\a\\b");
1252         t!(s: Path::new("\\\\a\\b/"), "\\\\a\\b");
1253         t!(s: Path::new("\\\\\\b"), "\\b");
1254         t!(s: Path::new("\\\\a\\\\b"), "\\a\\b");
1255         t!(s: Path::new("\\\\a\\b\\c"), "\\\\a\\b\\c");
1256         t!(s: Path::new("\\\\server\\share/path"), "\\\\server\\share\\path");
1257         t!(s: Path::new("\\\\server/share/path"), "\\\\server\\share\\path");
1258         t!(s: Path::new("C:a\\b.txt"), "C:a\\b.txt");
1259         t!(s: Path::new("C:a/b.txt"), "C:a\\b.txt");
1260         t!(s: Path::new("z:\\a\\b.txt"), "Z:\\a\\b.txt");
1261         t!(s: Path::new("z:/a/b.txt"), "Z:\\a\\b.txt");
1262         t!(s: Path::new("ab:/a/b.txt"), "ab:\\a\\b.txt");
1263         t!(s: Path::new("C:\\"), "C:\\");
1264         t!(s: Path::new("C:"), "C:");
1265         t!(s: Path::new("q:"), "Q:");
1266         t!(s: Path::new("C:/"), "C:\\");
1267         t!(s: Path::new("C:\\foo\\.."), "C:\\");
1268         t!(s: Path::new("C:foo\\.."), "C:");
1269         t!(s: Path::new("C:\\a\\"), "C:\\a");
1270         t!(s: Path::new("C:\\a/"), "C:\\a");
1271         t!(s: Path::new("C:\\a\\b\\"), "C:\\a\\b");
1272         t!(s: Path::new("C:\\a\\b/"), "C:\\a\\b");
1273         t!(s: Path::new("C:a\\"), "C:a");
1274         t!(s: Path::new("C:a/"), "C:a");
1275         t!(s: Path::new("C:a\\b\\"), "C:a\\b");
1276         t!(s: Path::new("C:a\\b/"), "C:a\\b");
1277         t!(s: Path::new("\\\\?\\z:\\a\\b.txt"), "\\\\?\\z:\\a\\b.txt");
1278         t!(s: Path::new("\\\\?\\C:/a/b.txt"), "\\\\?\\C:/a/b.txt");
1279         t!(s: Path::new("\\\\?\\C:\\a/b.txt"), "\\\\?\\C:\\a/b.txt");
1280         t!(s: Path::new("\\\\?\\test\\a\\b.txt"), "\\\\?\\test\\a\\b.txt");
1281         t!(s: Path::new("\\\\?\\foo\\bar\\"), "\\\\?\\foo\\bar\\");
1282         t!(s: Path::new("\\\\.\\foo\\bar"), "\\\\.\\foo\\bar");
1283         t!(s: Path::new("\\\\.\\"), "\\\\.\\");
1284         t!(s: Path::new("\\\\?\\UNC\\server\\share\\foo"), "\\\\?\\UNC\\server\\share\\foo");
1285         t!(s: Path::new("\\\\?\\UNC\\server/share"), "\\\\?\\UNC\\server/share\\");
1286         t!(s: Path::new("\\\\?\\UNC\\server"), "\\\\?\\UNC\\server\\");
1287         t!(s: Path::new("\\\\?\\UNC\\"), "\\\\?\\UNC\\\\");
1288         t!(s: Path::new("\\\\?\\UNC"), "\\\\?\\UNC");
1289
1290         // I'm not sure whether \\.\foo/bar should normalize to \\.\foo\bar
1291         // as information is sparse and this isn't really googleable.
1292         // I'm going to err on the side of not normalizing it, as this skips the filesystem
1293         t!(s: Path::new("\\\\.\\foo/bar"), "\\\\.\\foo/bar");
1294         t!(s: Path::new("\\\\.\\foo\\bar"), "\\\\.\\foo\\bar");
1295     }
1296
1297     #[test]
1298     fn test_opt_paths() {
1299         assert!(Path::new_opt(b"foo\\bar\0") == None);
1300         assert!(Path::new_opt(b"foo\\bar\x80") == None);
1301         t!(v: Path::new_opt(b"foo\\bar").unwrap(), b"foo\\bar");
1302         assert!(Path::new_opt("foo\\bar\0") == None);
1303         t!(s: Path::new_opt("foo\\bar").unwrap(), "foo\\bar");
1304     }
1305
1306     #[test]
1307     fn test_null_byte() {
1308         use thread;
1309         let result = thread::spawn(move|| {
1310             Path::new(b"foo/bar\0");
1311         }).join();
1312         assert!(result.is_err());
1313
1314         let result = thread::spawn(move|| {
1315             Path::new("test").set_filename(b"f\0o")
1316         }).join();
1317         assert!(result.is_err());
1318
1319         let result = thread::spawn(move || {
1320             Path::new("test").push(b"f\0o");
1321         }).join();
1322         assert!(result.is_err());
1323     }
1324
1325     #[test]
1326     #[should_fail]
1327     fn test_not_utf8_panics() {
1328         Path::new(b"hello\x80.txt");
1329     }
1330
1331     #[test]
1332     fn test_display_str() {
1333         let path = Path::new("foo");
1334         assert_eq!(path.display().to_string(), "foo");
1335         let path = Path::new(b"\\");
1336         assert_eq!(path.filename_display().to_string(), "");
1337
1338         let path = Path::new("foo");
1339         let mo = path.display().as_cow();
1340         assert_eq!(mo, "foo");
1341         let path = Path::new(b"\\");
1342         let mo = path.filename_display().as_cow();
1343         assert_eq!(mo, "");
1344     }
1345
1346     #[test]
1347     fn test_display() {
1348         macro_rules! t {
1349             ($path:expr, $exp:expr, $expf:expr) => (
1350                 {
1351                     let path = Path::new($path);
1352                     let f = format!("{}", path.display());
1353                     assert_eq!(f, $exp);
1354                     let f = format!("{}", path.filename_display());
1355                     assert_eq!(f, $expf);
1356                 }
1357             )
1358         }
1359
1360         t!("foo", "foo", "foo");
1361         t!("foo\\bar", "foo\\bar", "bar");
1362         t!("\\", "\\", "");
1363     }
1364
1365     #[test]
1366     fn test_components() {
1367         macro_rules! t {
1368             (s: $path:expr, $op:ident, $exp:expr) => (
1369                 {
1370                     let path = $path;
1371                     let path = Path::new(path);
1372                     assert_eq!(path.$op(), Some($exp));
1373                 }
1374             );
1375             (s: $path:expr, $op:ident, $exp:expr, opt) => (
1376                 {
1377                     let path = $path;
1378                     let path = Path::new(path);
1379                     let left = path.$op();
1380                     assert_eq!(left, $exp);
1381                 }
1382             );
1383             (v: $path:expr, $op:ident, $exp:expr) => (
1384                 {
1385                     let path = $path;
1386                     let path = Path::new(path);
1387                     assert_eq!(path.$op(), $exp);
1388                 }
1389             )
1390         }
1391
1392         t!(v: b"a\\b\\c", filename, Some(b"c"));
1393         t!(s: "a\\b\\c", filename_str, "c");
1394         t!(s: "\\a\\b\\c", filename_str, "c");
1395         t!(s: "a", filename_str, "a");
1396         t!(s: "\\a", filename_str, "a");
1397         t!(s: ".", filename_str, None, opt);
1398         t!(s: "\\", filename_str, None, opt);
1399         t!(s: "..", filename_str, None, opt);
1400         t!(s: "..\\..", filename_str, None, opt);
1401         t!(s: "c:\\foo.txt", filename_str, "foo.txt");
1402         t!(s: "C:\\", filename_str, None, opt);
1403         t!(s: "C:", filename_str, None, opt);
1404         t!(s: "\\\\server\\share\\foo.txt", filename_str, "foo.txt");
1405         t!(s: "\\\\server\\share", filename_str, None, opt);
1406         t!(s: "\\\\server", filename_str, "server");
1407         t!(s: "\\\\?\\bar\\foo.txt", filename_str, "foo.txt");
1408         t!(s: "\\\\?\\bar", filename_str, None, opt);
1409         t!(s: "\\\\?\\", filename_str, None, opt);
1410         t!(s: "\\\\?\\UNC\\server\\share\\foo.txt", filename_str, "foo.txt");
1411         t!(s: "\\\\?\\UNC\\server", filename_str, None, opt);
1412         t!(s: "\\\\?\\UNC\\", filename_str, None, opt);
1413         t!(s: "\\\\?\\C:\\foo.txt", filename_str, "foo.txt");
1414         t!(s: "\\\\?\\C:\\", filename_str, None, opt);
1415         t!(s: "\\\\?\\C:", filename_str, None, opt);
1416         t!(s: "\\\\?\\foo/bar", filename_str, None, opt);
1417         t!(s: "\\\\?\\C:/foo", filename_str, None, opt);
1418         t!(s: "\\\\.\\foo\\bar", filename_str, "bar");
1419         t!(s: "\\\\.\\foo", filename_str, None, opt);
1420         t!(s: "\\\\.\\foo/bar", filename_str, None, opt);
1421         t!(s: "\\\\.\\foo\\bar/baz", filename_str, "bar/baz");
1422         t!(s: "\\\\.\\", filename_str, None, opt);
1423         t!(s: "\\\\?\\a\\b\\", filename_str, "b");
1424
1425         t!(v: b"a\\b\\c", dirname, b"a\\b");
1426         t!(s: "a\\b\\c", dirname_str, "a\\b");
1427         t!(s: "\\a\\b\\c", dirname_str, "\\a\\b");
1428         t!(s: "a", dirname_str, ".");
1429         t!(s: "\\a", dirname_str, "\\");
1430         t!(s: ".", dirname_str, ".");
1431         t!(s: "\\", dirname_str, "\\");
1432         t!(s: "..", dirname_str, "..");
1433         t!(s: "..\\..", dirname_str, "..\\..");
1434         t!(s: "c:\\foo.txt", dirname_str, "C:\\");
1435         t!(s: "C:\\", dirname_str, "C:\\");
1436         t!(s: "C:", dirname_str, "C:");
1437         t!(s: "C:foo.txt", dirname_str, "C:");
1438         t!(s: "\\\\server\\share\\foo.txt", dirname_str, "\\\\server\\share");
1439         t!(s: "\\\\server\\share", dirname_str, "\\\\server\\share");
1440         t!(s: "\\\\server", dirname_str, "\\");
1441         t!(s: "\\\\?\\bar\\foo.txt", dirname_str, "\\\\?\\bar");
1442         t!(s: "\\\\?\\bar", dirname_str, "\\\\?\\bar");
1443         t!(s: "\\\\?\\", dirname_str, "\\\\?\\");
1444         t!(s: "\\\\?\\UNC\\server\\share\\foo.txt", dirname_str, "\\\\?\\UNC\\server\\share");
1445         t!(s: "\\\\?\\UNC\\server", dirname_str, "\\\\?\\UNC\\server\\");
1446         t!(s: "\\\\?\\UNC\\", dirname_str, "\\\\?\\UNC\\\\");
1447         t!(s: "\\\\?\\C:\\foo.txt", dirname_str, "\\\\?\\C:\\");
1448         t!(s: "\\\\?\\C:\\", dirname_str, "\\\\?\\C:\\");
1449         t!(s: "\\\\?\\C:", dirname_str, "\\\\?\\C:");
1450         t!(s: "\\\\?\\C:/foo/bar", dirname_str, "\\\\?\\C:/foo/bar");
1451         t!(s: "\\\\?\\foo/bar", dirname_str, "\\\\?\\foo/bar");
1452         t!(s: "\\\\.\\foo\\bar", dirname_str, "\\\\.\\foo");
1453         t!(s: "\\\\.\\foo", dirname_str, "\\\\.\\foo");
1454         t!(s: "\\\\?\\a\\b\\", dirname_str, "\\\\?\\a");
1455
1456         t!(v: b"hi\\there.txt", filestem, Some(b"there"));
1457         t!(s: "hi\\there.txt", filestem_str, "there");
1458         t!(s: "hi\\there", filestem_str, "there");
1459         t!(s: "there.txt", filestem_str, "there");
1460         t!(s: "there", filestem_str, "there");
1461         t!(s: ".", filestem_str, None, opt);
1462         t!(s: "\\", filestem_str, None, opt);
1463         t!(s: "foo\\.bar", filestem_str, ".bar");
1464         t!(s: ".bar", filestem_str, ".bar");
1465         t!(s: "..bar", filestem_str, ".");
1466         t!(s: "hi\\there..txt", filestem_str, "there.");
1467         t!(s: "..", filestem_str, None, opt);
1468         t!(s: "..\\..", filestem_str, None, opt);
1469         // filestem is based on filename, so we don't need the full set of prefix tests
1470
1471         t!(v: b"hi\\there.txt", extension, Some(b"txt"));
1472         t!(v: b"hi\\there", extension, None);
1473         t!(s: "hi\\there.txt", extension_str, Some("txt"), opt);
1474         t!(s: "hi\\there", extension_str, None, opt);
1475         t!(s: "there.txt", extension_str, Some("txt"), opt);
1476         t!(s: "there", extension_str, None, opt);
1477         t!(s: ".", extension_str, None, opt);
1478         t!(s: "\\", extension_str, None, opt);
1479         t!(s: "foo\\.bar", extension_str, None, opt);
1480         t!(s: ".bar", extension_str, None, opt);
1481         t!(s: "..bar", extension_str, Some("bar"), opt);
1482         t!(s: "hi\\there..txt", extension_str, Some("txt"), opt);
1483         t!(s: "..", extension_str, None, opt);
1484         t!(s: "..\\..", extension_str, None, opt);
1485         // extension is based on filename, so we don't need the full set of prefix tests
1486     }
1487
1488     #[test]
1489     fn test_push() {
1490         macro_rules! t {
1491             (s: $path:expr, $join:expr) => (
1492                 {
1493                     let path = $path;
1494                     let join = $join;
1495                     let mut p1 = Path::new(path);
1496                     let p2 = p1.clone();
1497                     p1.push(join);
1498                     assert_eq!(p1, p2.join(join));
1499                 }
1500             )
1501         }
1502
1503         t!(s: "a\\b\\c", "..");
1504         t!(s: "\\a\\b\\c", "d");
1505         t!(s: "a\\b", "c\\d");
1506         t!(s: "a\\b", "\\c\\d");
1507         // this is just a sanity-check test. push and join share an implementation,
1508         // so there's no need for the full set of prefix tests
1509
1510         // we do want to check one odd case though to ensure the prefix is re-parsed
1511         let mut p = Path::new("\\\\?\\C:");
1512         assert_eq!(prefix(&p), Some(VerbatimPrefix(2)));
1513         p.push("foo");
1514         assert_eq!(prefix(&p), Some(VerbatimDiskPrefix));
1515         assert_eq!(p.as_str(), Some("\\\\?\\C:\\foo"));
1516
1517         // and another with verbatim non-normalized paths
1518         let mut p = Path::new("\\\\?\\C:\\a\\");
1519         p.push("foo");
1520         assert_eq!(p.as_str(), Some("\\\\?\\C:\\a\\foo"));
1521     }
1522
1523     #[test]
1524     fn test_push_path() {
1525         macro_rules! t {
1526             (s: $path:expr, $push:expr, $exp:expr) => (
1527                 {
1528                     let mut p = Path::new($path);
1529                     let push = Path::new($push);
1530                     p.push(&push);
1531                     assert_eq!(p.as_str(), Some($exp));
1532                 }
1533             )
1534         }
1535
1536         t!(s: "a\\b\\c", "d", "a\\b\\c\\d");
1537         t!(s: "\\a\\b\\c", "d", "\\a\\b\\c\\d");
1538         t!(s: "a\\b", "c\\d", "a\\b\\c\\d");
1539         t!(s: "a\\b", "\\c\\d", "\\c\\d");
1540         t!(s: "a\\b", ".", "a\\b");
1541         t!(s: "a\\b", "..\\c", "a\\c");
1542         t!(s: "a\\b", "C:a.txt", "C:a.txt");
1543         t!(s: "a\\b", "..\\..\\..\\c", "..\\c");
1544         t!(s: "a\\b", "C:\\a.txt", "C:\\a.txt");
1545         t!(s: "C:\\a", "C:\\b.txt", "C:\\b.txt");
1546         t!(s: "C:\\a\\b\\c", "C:d", "C:\\a\\b\\c\\d");
1547         t!(s: "C:a\\b\\c", "C:d", "C:a\\b\\c\\d");
1548         t!(s: "C:a\\b", "..\\..\\..\\c", "C:..\\c");
1549         t!(s: "C:\\a\\b", "..\\..\\..\\c", "C:\\c");
1550         t!(s: "C:", r"a\b\c", r"C:a\b\c");
1551         t!(s: "C:", r"..\a", r"C:..\a");
1552         t!(s: "\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
1553         t!(s: "\\\\server\\share\\foo", "..\\..\\bar", "\\\\server\\share\\bar");
1554         t!(s: "\\\\server\\share\\foo", "C:baz", "C:baz");
1555         t!(s: "\\\\?\\C:\\a\\b", "C:c\\d", "\\\\?\\C:\\a\\b\\c\\d");
1556         t!(s: "\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
1557         t!(s: "\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
1558         t!(s: "\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
1559         t!(s: "\\\\?\\C:\\a\\b", "..\\..\\..\\c", "\\\\?\\C:\\a\\b\\..\\..\\..\\c");
1560         t!(s: "\\\\?\\foo\\bar", "..\\..\\c", "\\\\?\\foo\\bar\\..\\..\\c");
1561         t!(s: "\\\\?\\", "foo", "\\\\?\\\\foo");
1562         t!(s: "\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
1563         t!(s: "\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
1564         t!(s: "\\\\?\\UNC\\server\\share", "C:a", "C:a");
1565         t!(s: "\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\\\foo");
1566         t!(s: "C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
1567         t!(s: "\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
1568         t!(s: "\\\\.\\foo\\bar", "C:a", "C:a");
1569         // again, not sure about the following, but I'm assuming \\.\ should be verbatim
1570         t!(s: "\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
1571
1572         t!(s: "\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
1573     }
1574
1575     #[test]
1576     fn test_push_many() {
1577         macro_rules! t {
1578             (s: $path:expr, $push:expr, $exp:expr) => (
1579                 {
1580                     let mut p = Path::new($path);
1581                     p.push_many(&$push);
1582                     assert_eq!(p.as_str(), Some($exp));
1583                 }
1584             );
1585             (v: $path:expr, $push:expr, $exp:expr) => (
1586                 {
1587                     let mut p = Path::new($path);
1588                     p.push_many(&$push);
1589                     assert_eq!(p.as_vec(), $exp);
1590                 }
1591             )
1592         }
1593
1594         t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
1595         t!(s: "a\\b\\c", ["d", "\\e"], "\\e");
1596         t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
1597         t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
1598         t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
1599         t!(v: b"a\\b\\c", [b"d", b"\\e", b"f"], b"\\e\\f");
1600         t!(v: b"a\\b\\c", [b"d".to_vec(), b"e".to_vec()],
1601            b"a\\b\\c\\d\\e");
1602     }
1603
1604     #[test]
1605     fn test_pop() {
1606         macro_rules! t {
1607             (s: $path:expr, $left:expr, $right:expr) => (
1608                 {
1609                     let pstr = $path;
1610                     let mut p = Path::new(pstr);
1611                     let result = p.pop();
1612                     let left = $left;
1613                     assert_eq!(p.as_str(), Some(left));
1614                     assert_eq!(result, $right);
1615                 }
1616             );
1617             (b: $path:expr, $left:expr, $right:expr) => (
1618                 {
1619                     let mut p = Path::new($path);
1620                     let result = p.pop();
1621                     assert_eq!(p.as_vec(), $left);
1622                     assert_eq!(result, $right);
1623                 }
1624             )
1625         }
1626
1627         t!(s: "a\\b\\c", "a\\b", true);
1628         t!(s: "a", ".", true);
1629         t!(s: ".", ".", false);
1630         t!(s: "\\a", "\\", true);
1631         t!(s: "\\", "\\", false);
1632         t!(b: b"a\\b\\c", b"a\\b", true);
1633         t!(b: b"a", b".", true);
1634         t!(b: b".", b".", false);
1635         t!(b: b"\\a", b"\\", true);
1636         t!(b: b"\\", b"\\", false);
1637
1638         t!(s: "C:\\a\\b", "C:\\a", true);
1639         t!(s: "C:\\a", "C:\\", true);
1640         t!(s: "C:\\", "C:\\", false);
1641         t!(s: "C:a\\b", "C:a", true);
1642         t!(s: "C:a", "C:", true);
1643         t!(s: "C:", "C:", false);
1644         t!(s: "\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
1645         t!(s: "\\\\server\\share\\a", "\\\\server\\share", true);
1646         t!(s: "\\\\server\\share", "\\\\server\\share", false);
1647         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
1648         t!(s: "\\\\?\\a\\b", "\\\\?\\a", true);
1649         t!(s: "\\\\?\\a", "\\\\?\\a", false);
1650         t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
1651         t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\", true);
1652         t!(s: "\\\\?\\C:\\", "\\\\?\\C:\\", false);
1653         t!(s: "\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
1654         t!(s: "\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share", true);
1655         t!(s: "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
1656         t!(s: "\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
1657         t!(s: "\\\\.\\a\\b", "\\\\.\\a", true);
1658         t!(s: "\\\\.\\a", "\\\\.\\a", false);
1659
1660         t!(s: "\\\\?\\a\\b\\", "\\\\?\\a", true);
1661     }
1662
1663     #[test]
1664     fn test_root_path() {
1665         assert_eq!(Path::new("a\\b\\c").root_path(),  None);
1666         assert_eq!(Path::new("\\a\\b\\c").root_path(), Some(Path::new("\\")));
1667         assert_eq!(Path::new("C:a").root_path(), Some(Path::new("C:")));
1668         assert_eq!(Path::new("C:\\a").root_path(), Some(Path::new("C:\\")));
1669         assert_eq!(Path::new("\\\\a\\b\\c").root_path(), Some(Path::new("\\\\a\\b")));
1670         assert_eq!(Path::new("\\\\?\\a\\b").root_path(), Some(Path::new("\\\\?\\a")));
1671         assert_eq!(Path::new("\\\\?\\C:\\a").root_path(), Some(Path::new("\\\\?\\C:\\")));
1672         assert_eq!(Path::new("\\\\?\\UNC\\a\\b\\c").root_path(),
1673                 Some(Path::new("\\\\?\\UNC\\a\\b")));
1674         assert_eq!(Path::new("\\\\.\\a\\b").root_path(), Some(Path::new("\\\\.\\a")));
1675     }
1676
1677     #[test]
1678     fn test_join() {
1679         t!(s: Path::new("a\\b\\c").join(".."), "a\\b");
1680         t!(s: Path::new("\\a\\b\\c").join("d"), "\\a\\b\\c\\d");
1681         t!(s: Path::new("a\\b").join("c\\d"), "a\\b\\c\\d");
1682         t!(s: Path::new("a\\b").join("\\c\\d"), "\\c\\d");
1683         t!(s: Path::new(".").join("a\\b"), "a\\b");
1684         t!(s: Path::new("\\").join("a\\b"), "\\a\\b");
1685         t!(v: Path::new(b"a\\b\\c").join(b".."), b"a\\b");
1686         t!(v: Path::new(b"\\a\\b\\c").join(b"d"), b"\\a\\b\\c\\d");
1687         // full join testing is covered under test_push_path, so no need for
1688         // the full set of prefix tests
1689     }
1690
1691     #[test]
1692     fn test_join_path() {
1693         macro_rules! t {
1694             (s: $path:expr, $join:expr, $exp:expr) => (
1695                 {
1696                     let path = Path::new($path);
1697                     let join = Path::new($join);
1698                     let res = path.join(&join);
1699                     assert_eq!(res.as_str(), Some($exp));
1700                 }
1701             )
1702         }
1703
1704         t!(s: "a\\b\\c", "..", "a\\b");
1705         t!(s: "\\a\\b\\c", "d", "\\a\\b\\c\\d");
1706         t!(s: "a\\b", "c\\d", "a\\b\\c\\d");
1707         t!(s: "a\\b", "\\c\\d", "\\c\\d");
1708         t!(s: ".", "a\\b", "a\\b");
1709         t!(s: "\\", "a\\b", "\\a\\b");
1710         // join is implemented using push, so there's no need for
1711         // the full set of prefix tests
1712     }
1713
1714     #[test]
1715     fn test_join_many() {
1716         macro_rules! t {
1717             (s: $path:expr, $join:expr, $exp:expr) => (
1718                 {
1719                     let path = Path::new($path);
1720                     let res = path.join_many(&$join);
1721                     assert_eq!(res.as_str(), Some($exp));
1722                 }
1723             );
1724             (v: $path:expr, $join:expr, $exp:expr) => (
1725                 {
1726                     let path = Path::new($path);
1727                     let res = path.join_many(&$join);
1728                     assert_eq!(res.as_vec(), $exp);
1729                 }
1730             )
1731         }
1732
1733         t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
1734         t!(s: "a\\b\\c", ["..", "d"], "a\\b\\d");
1735         t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
1736         t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
1737         t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
1738         t!(v: b"a\\b\\c", [b"d".to_vec(), b"e".to_vec()],
1739            b"a\\b\\c\\d\\e");
1740     }
1741
1742     #[test]
1743     fn test_with_helpers() {
1744         macro_rules! t {
1745             (s: $path:expr, $op:ident, $arg:expr, $res:expr) => (
1746                 {
1747                     let pstr = $path;
1748                     let path = Path::new(pstr);
1749                     let arg = $arg;
1750                     let res = path.$op(arg);
1751                     let exp = Path::new($res);
1752                     assert_eq!(res, exp);
1753                 }
1754             )
1755         }
1756
1757         t!(s: "a\\b\\c", with_filename, "d", "a\\b\\d");
1758         t!(s: ".", with_filename, "foo", "foo");
1759         t!(s: "\\a\\b\\c", with_filename, "d", "\\a\\b\\d");
1760         t!(s: "\\", with_filename, "foo", "\\foo");
1761         t!(s: "\\a", with_filename, "foo", "\\foo");
1762         t!(s: "foo", with_filename, "bar", "bar");
1763         t!(s: "\\", with_filename, "foo\\", "\\foo");
1764         t!(s: "\\a", with_filename, "foo\\", "\\foo");
1765         t!(s: "a\\b\\c", with_filename, "", "a\\b");
1766         t!(s: "a\\b\\c", with_filename, ".", "a\\b");
1767         t!(s: "a\\b\\c", with_filename, "..", "a");
1768         t!(s: "\\a", with_filename, "", "\\");
1769         t!(s: "foo", with_filename, "", ".");
1770         t!(s: "a\\b\\c", with_filename, "d\\e", "a\\b\\d\\e");
1771         t!(s: "a\\b\\c", with_filename, "\\d", "a\\b\\d");
1772         t!(s: "..", with_filename, "foo", "..\\foo");
1773         t!(s: "..\\..", with_filename, "foo", "..\\..\\foo");
1774         t!(s: "..", with_filename, "", "..");
1775         t!(s: "..\\..", with_filename, "", "..\\..");
1776         t!(s: "C:\\foo\\bar", with_filename, "baz", "C:\\foo\\baz");
1777         t!(s: "C:\\foo", with_filename, "bar", "C:\\bar");
1778         t!(s: "C:\\", with_filename, "foo", "C:\\foo");
1779         t!(s: "C:foo\\bar", with_filename, "baz", "C:foo\\baz");
1780         t!(s: "C:foo", with_filename, "bar", "C:bar");
1781         t!(s: "C:", with_filename, "foo", "C:foo");
1782         t!(s: "C:\\foo", with_filename, "", "C:\\");
1783         t!(s: "C:foo", with_filename, "", "C:");
1784         t!(s: "C:\\foo\\bar", with_filename, "..", "C:\\");
1785         t!(s: "C:\\foo", with_filename, "..", "C:\\");
1786         t!(s: "C:\\", with_filename, "..", "C:\\");
1787         t!(s: "C:foo\\bar", with_filename, "..", "C:");
1788         t!(s: "C:foo", with_filename, "..", "C:..");
1789         t!(s: "C:", with_filename, "..", "C:..");
1790         t!(s: "\\\\server\\share\\foo", with_filename, "bar", "\\\\server\\share\\bar");
1791         t!(s: "\\\\server\\share", with_filename, "foo", "\\\\server\\share\\foo");
1792         t!(s: "\\\\server\\share\\foo", with_filename, "", "\\\\server\\share");
1793         t!(s: "\\\\server\\share", with_filename, "", "\\\\server\\share");
1794         t!(s: "\\\\server\\share\\foo", with_filename, "..", "\\\\server\\share");
1795         t!(s: "\\\\server\\share", with_filename, "..", "\\\\server\\share");
1796         t!(s: "\\\\?\\C:\\foo\\bar", with_filename, "baz", "\\\\?\\C:\\foo\\baz");
1797         t!(s: "\\\\?\\C:\\foo", with_filename, "bar", "\\\\?\\C:\\bar");
1798         t!(s: "\\\\?\\C:\\", with_filename, "foo", "\\\\?\\C:\\foo");
1799         t!(s: "\\\\?\\C:\\foo", with_filename, "..", "\\\\?\\C:\\..");
1800         t!(s: "\\\\?\\foo\\bar", with_filename, "baz", "\\\\?\\foo\\baz");
1801         t!(s: "\\\\?\\foo", with_filename, "bar", "\\\\?\\foo\\bar");
1802         t!(s: "\\\\?\\", with_filename, "foo", "\\\\?\\\\foo");
1803         t!(s: "\\\\?\\foo\\bar", with_filename, "..", "\\\\?\\foo\\..");
1804         t!(s: "\\\\.\\foo\\bar", with_filename, "baz", "\\\\.\\foo\\baz");
1805         t!(s: "\\\\.\\foo", with_filename, "bar", "\\\\.\\foo\\bar");
1806         t!(s: "\\\\.\\foo\\bar", with_filename, "..", "\\\\.\\foo\\..");
1807
1808         t!(s: "hi\\there.txt", with_extension, "exe", "hi\\there.exe");
1809         t!(s: "hi\\there.txt", with_extension, "", "hi\\there");
1810         t!(s: "hi\\there.txt", with_extension, ".", "hi\\there..");
1811         t!(s: "hi\\there.txt", with_extension, "..", "hi\\there...");
1812         t!(s: "hi\\there", with_extension, "txt", "hi\\there.txt");
1813         t!(s: "hi\\there", with_extension, ".", "hi\\there..");
1814         t!(s: "hi\\there", with_extension, "..", "hi\\there...");
1815         t!(s: "hi\\there.", with_extension, "txt", "hi\\there.txt");
1816         t!(s: "hi\\.foo", with_extension, "txt", "hi\\.foo.txt");
1817         t!(s: "hi\\there.txt", with_extension, ".foo", "hi\\there..foo");
1818         t!(s: "\\", with_extension, "txt", "\\");
1819         t!(s: "\\", with_extension, ".", "\\");
1820         t!(s: "\\", with_extension, "..", "\\");
1821         t!(s: ".", with_extension, "txt", ".");
1822         // extension setter calls filename setter internally, no need for extended tests
1823     }
1824
1825     #[test]
1826     fn test_setters() {
1827         macro_rules! t {
1828             (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
1829                 {
1830                     let path = $path;
1831                     let arg = $arg;
1832                     let mut p1 = Path::new(path);
1833                     p1.$set(arg);
1834                     let p2 = Path::new(path);
1835                     assert_eq!(p1, p2.$with(arg));
1836                 }
1837             );
1838             (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
1839                 {
1840                     let path = $path;
1841                     let arg = $arg;
1842                     let mut p1 = Path::new(path);
1843                     p1.$set(arg);
1844                     let p2 = Path::new(path);
1845                     assert_eq!(p1, p2.$with(arg));
1846                 }
1847             )
1848         }
1849
1850         t!(v: b"a\\b\\c", set_filename, with_filename, b"d");
1851         t!(v: b"\\", set_filename, with_filename, b"foo");
1852         t!(s: "a\\b\\c", set_filename, with_filename, "d");
1853         t!(s: "\\", set_filename, with_filename, "foo");
1854         t!(s: ".", set_filename, with_filename, "foo");
1855         t!(s: "a\\b", set_filename, with_filename, "");
1856         t!(s: "a", set_filename, with_filename, "");
1857
1858         t!(v: b"hi\\there.txt", set_extension, with_extension, b"exe");
1859         t!(s: "hi\\there.txt", set_extension, with_extension, "exe");
1860         t!(s: "hi\\there.", set_extension, with_extension, "txt");
1861         t!(s: "hi\\there", set_extension, with_extension, "txt");
1862         t!(s: "hi\\there.txt", set_extension, with_extension, "");
1863         t!(s: "hi\\there", set_extension, with_extension, "");
1864         t!(s: ".", set_extension, with_extension, "txt");
1865
1866         // with_ helpers use the setter internally, so the tests for the with_ helpers
1867         // will suffice. No need for the full set of prefix tests.
1868     }
1869
1870     #[test]
1871     fn test_getters() {
1872         macro_rules! t {
1873             (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
1874                 {
1875                     let path = $path;
1876                     assert_eq!(path.filename_str(), $filename);
1877                     assert_eq!(path.dirname_str(), $dirname);
1878                     assert_eq!(path.filestem_str(), $filestem);
1879                     assert_eq!(path.extension_str(), $ext);
1880                 }
1881             );
1882             (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
1883                 {
1884                     let path = $path;
1885                     assert_eq!(path.filename(), $filename);
1886                     assert_eq!(path.dirname(), $dirname);
1887                     assert_eq!(path.filestem(), $filestem);
1888                     assert_eq!(path.extension(), $ext);
1889                 }
1890             )
1891         }
1892
1893         t!(v: Path::new(b"a\\b\\c"), Some(b"c"), b"a\\b", Some(b"c"), None);
1894         t!(s: Path::new("a\\b\\c"), Some("c"), Some("a\\b"), Some("c"), None);
1895         t!(s: Path::new("."), None, Some("."), None, None);
1896         t!(s: Path::new("\\"), None, Some("\\"), None, None);
1897         t!(s: Path::new(".."), None, Some(".."), None, None);
1898         t!(s: Path::new("..\\.."), None, Some("..\\.."), None, None);
1899         t!(s: Path::new("hi\\there.txt"), Some("there.txt"), Some("hi"),
1900               Some("there"), Some("txt"));
1901         t!(s: Path::new("hi\\there"), Some("there"), Some("hi"), Some("there"), None);
1902         t!(s: Path::new("hi\\there."), Some("there."), Some("hi"),
1903               Some("there"), Some(""));
1904         t!(s: Path::new("hi\\.there"), Some(".there"), Some("hi"), Some(".there"), None);
1905         t!(s: Path::new("hi\\..there"), Some("..there"), Some("hi"),
1906               Some("."), Some("there"));
1907
1908         // these are already tested in test_components, so no need for extended tests
1909     }
1910
1911     #[test]
1912     fn test_dir_path() {
1913         t!(s: Path::new("hi\\there").dir_path(), "hi");
1914         t!(s: Path::new("hi").dir_path(), ".");
1915         t!(s: Path::new("\\hi").dir_path(), "\\");
1916         t!(s: Path::new("\\").dir_path(), "\\");
1917         t!(s: Path::new("..").dir_path(), "..");
1918         t!(s: Path::new("..\\..").dir_path(), "..\\..");
1919
1920         // dir_path is just dirname interpreted as a path.
1921         // No need for extended tests
1922     }
1923
1924     #[test]
1925     fn test_is_absolute() {
1926         macro_rules! t {
1927             ($path:expr, $abs:expr, $vol:expr, $cwd:expr, $rel:expr) => (
1928                 {
1929                     let path = Path::new($path);
1930                     let (abs, vol, cwd, rel) = ($abs, $vol, $cwd, $rel);
1931                     assert_eq!(path.is_absolute(), abs);
1932                     assert_eq!(is_vol_relative(&path), vol);
1933                     assert_eq!(is_cwd_relative(&path), cwd);
1934                     assert_eq!(path.is_relative(), rel);
1935                 }
1936             )
1937         }
1938         t!("a\\b\\c", false, false, false, true);
1939         t!("\\a\\b\\c", false, true, false, false);
1940         t!("a", false, false, false, true);
1941         t!("\\a", false, true, false, false);
1942         t!(".", false, false, false, true);
1943         t!("\\", false, true, false, false);
1944         t!("..", false, false, false, true);
1945         t!("..\\..", false, false, false, true);
1946         t!("C:a\\b.txt", false, false, true, false);
1947         t!("C:\\a\\b.txt", true, false, false, false);
1948         t!("\\\\server\\share\\a\\b.txt", true, false, false, false);
1949         t!("\\\\?\\a\\b\\c.txt", true, false, false, false);
1950         t!("\\\\?\\C:\\a\\b.txt", true, false, false, false);
1951         t!("\\\\?\\C:a\\b.txt", true, false, false, false); // NB: not equivalent to C:a\b.txt
1952         t!("\\\\?\\UNC\\server\\share\\a\\b.txt", true, false, false, false);
1953         t!("\\\\.\\a\\b", true, false, false, false);
1954     }
1955
1956     #[test]
1957     fn test_is_ancestor_of() {
1958         macro_rules! t {
1959             (s: $path:expr, $dest:expr, $exp:expr) => (
1960                 {
1961                     let path = Path::new($path);
1962                     let dest = Path::new($dest);
1963                     let exp = $exp;
1964                     let res = path.is_ancestor_of(&dest);
1965                     assert_eq!(res, exp);
1966                 }
1967             )
1968         }
1969
1970         t!(s: "a\\b\\c", "a\\b\\c\\d", true);
1971         t!(s: "a\\b\\c", "a\\b\\c", true);
1972         t!(s: "a\\b\\c", "a\\b", false);
1973         t!(s: "\\a\\b\\c", "\\a\\b\\c", true);
1974         t!(s: "\\a\\b", "\\a\\b\\c", true);
1975         t!(s: "\\a\\b\\c\\d", "\\a\\b\\c", false);
1976         t!(s: "\\a\\b", "a\\b\\c", false);
1977         t!(s: "a\\b", "\\a\\b\\c", false);
1978         t!(s: "a\\b\\c", "a\\b\\d", false);
1979         t!(s: "..\\a\\b\\c", "a\\b\\c", false);
1980         t!(s: "a\\b\\c", "..\\a\\b\\c", false);
1981         t!(s: "a\\b\\c", "a\\b\\cd", false);
1982         t!(s: "a\\b\\cd", "a\\b\\c", false);
1983         t!(s: "..\\a\\b", "..\\a\\b\\c", true);
1984         t!(s: ".", "a\\b", true);
1985         t!(s: ".", ".", true);
1986         t!(s: "\\", "\\", true);
1987         t!(s: "\\", "\\a\\b", true);
1988         t!(s: "..", "a\\b", true);
1989         t!(s: "..\\..", "a\\b", true);
1990         t!(s: "foo\\bar", "foobar", false);
1991         t!(s: "foobar", "foo\\bar", false);
1992
1993         t!(s: "foo", "C:foo", false);
1994         t!(s: "C:foo", "foo", false);
1995         t!(s: "C:foo", "C:foo\\bar", true);
1996         t!(s: "C:foo\\bar", "C:foo", false);
1997         t!(s: "C:\\foo", "C:\\foo\\bar", true);
1998         t!(s: "C:", "C:", true);
1999         t!(s: "C:", "C:\\", false);
2000         t!(s: "C:\\", "C:", false);
2001         t!(s: "C:\\", "C:\\", true);
2002         t!(s: "C:\\foo\\bar", "C:\\foo", false);
2003         t!(s: "C:foo\\bar", "C:foo", false);
2004         t!(s: "C:\\foo", "\\foo", false);
2005         t!(s: "\\foo", "C:\\foo", false);
2006         t!(s: "\\\\server\\share\\foo", "\\\\server\\share\\foo\\bar", true);
2007         t!(s: "\\\\server\\share", "\\\\server\\share\\foo", true);
2008         t!(s: "\\\\server\\share\\foo", "\\\\server\\share", false);
2009         t!(s: "C:\\foo", "\\\\server\\share\\foo", false);
2010         t!(s: "\\\\server\\share\\foo", "C:\\foo", false);
2011         t!(s: "\\\\?\\foo\\bar", "\\\\?\\foo\\bar\\baz", true);
2012         t!(s: "\\\\?\\foo\\bar\\baz", "\\\\?\\foo\\bar", false);
2013         t!(s: "\\\\?\\foo\\bar", "\\foo\\bar\\baz", false);
2014         t!(s: "\\foo\\bar", "\\\\?\\foo\\bar\\baz", false);
2015         t!(s: "\\\\?\\C:\\foo\\bar", "\\\\?\\C:\\foo\\bar\\baz", true);
2016         t!(s: "\\\\?\\C:\\foo\\bar\\baz", "\\\\?\\C:\\foo\\bar", false);
2017         t!(s: "\\\\?\\C:\\", "\\\\?\\C:\\foo", true);
2018         t!(s: "\\\\?\\C:", "\\\\?\\C:\\", false); // this is a weird one
2019         t!(s: "\\\\?\\C:\\", "\\\\?\\C:", false);
2020         t!(s: "\\\\?\\C:\\a", "\\\\?\\c:\\a\\b", true);
2021         t!(s: "\\\\?\\c:\\a", "\\\\?\\C:\\a\\b", true);
2022         t!(s: "\\\\?\\C:\\a", "\\\\?\\D:\\a\\b", false);
2023         t!(s: "\\\\?\\foo", "\\\\?\\foobar", false);
2024         t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\c", true);
2025         t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\", true);
2026         t!(s: "\\\\?\\a\\b\\", "\\\\?\\a\\b", true);
2027         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", false);
2028         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b\\", false);
2029         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\b\\c\\d", true);
2030         t!(s: "\\\\?\\UNC\\a\\b\\c\\d", "\\\\?\\UNC\\a\\b\\c", false);
2031         t!(s: "\\\\?\\UNC\\a\\b", "\\\\?\\UNC\\a\\b\\c", true);
2032         t!(s: "\\\\.\\foo\\bar", "\\\\.\\foo\\bar\\baz", true);
2033         t!(s: "\\\\.\\foo\\bar\\baz", "\\\\.\\foo\\bar", false);
2034         t!(s: "\\\\.\\foo", "\\\\.\\foo\\bar", true);
2035         t!(s: "\\\\.\\foo", "\\\\.\\foobar", false);
2036
2037         t!(s: "\\a\\b", "\\\\?\\a\\b", false);
2038         t!(s: "\\\\?\\a\\b", "\\a\\b", false);
2039         t!(s: "\\a\\b", "\\\\?\\C:\\a\\b", false);
2040         t!(s: "\\\\?\\C:\\a\\b", "\\a\\b", false);
2041         t!(s: "Z:\\a\\b", "\\\\?\\z:\\a\\b", true);
2042         t!(s: "C:\\a\\b", "\\\\?\\D:\\a\\b", false);
2043         t!(s: "a\\b", "\\\\?\\a\\b", false);
2044         t!(s: "\\\\?\\a\\b", "a\\b", false);
2045         t!(s: "C:\\a\\b", "\\\\?\\C:\\a\\b", true);
2046         t!(s: "\\\\?\\C:\\a\\b", "C:\\a\\b", true);
2047         t!(s: "C:a\\b", "\\\\?\\C:\\a\\b", false);
2048         t!(s: "C:a\\b", "\\\\?\\C:a\\b", false);
2049         t!(s: "\\\\?\\C:\\a\\b", "C:a\\b", false);
2050         t!(s: "\\\\?\\C:a\\b", "C:a\\b", false);
2051         t!(s: "C:\\a\\b", "\\\\?\\C:\\a\\b\\", true);
2052         t!(s: "\\\\?\\C:\\a\\b\\", "C:\\a\\b", true);
2053         t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\b\\c", true);
2054         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\b\\c", true);
2055     }
2056
2057     #[test]
2058     fn test_ends_with_path() {
2059         macro_rules! t {
2060             (s: $path:expr, $child:expr, $exp:expr) => (
2061                 {
2062                     let path = Path::new($path);
2063                     let child = Path::new($child);
2064                     assert_eq!(path.ends_with_path(&child), $exp);
2065                 }
2066             );
2067         }
2068
2069         t!(s: "a\\b\\c", "c", true);
2070         t!(s: "a\\b\\c", "d", false);
2071         t!(s: "foo\\bar\\quux", "bar", false);
2072         t!(s: "foo\\bar\\quux", "barquux", false);
2073         t!(s: "a\\b\\c", "b\\c", true);
2074         t!(s: "a\\b\\c", "a\\b\\c", true);
2075         t!(s: "a\\b\\c", "foo\\a\\b\\c", false);
2076         t!(s: "\\a\\b\\c", "a\\b\\c", true);
2077         t!(s: "\\a\\b\\c", "\\a\\b\\c", false); // child must be relative
2078         t!(s: "\\a\\b\\c", "foo\\a\\b\\c", false);
2079         t!(s: "a\\b\\c", "", false);
2080         t!(s: "", "", true);
2081         t!(s: "\\a\\b\\c", "d\\e\\f", false);
2082         t!(s: "a\\b\\c", "a\\b", false);
2083         t!(s: "a\\b\\c", "b", false);
2084         t!(s: "C:\\a\\b", "b", true);
2085         t!(s: "C:\\a\\b", "C:b", false);
2086         t!(s: "C:\\a\\b", "C:a\\b", false);
2087     }
2088
2089     #[test]
2090     fn test_path_relative_from() {
2091         macro_rules! t {
2092             (s: $path:expr, $other:expr, $exp:expr) => (
2093                 {
2094                     assert_eq!(Path::new($path).path_relative_from(&Path::new($other))
2095                               .as_ref().and_then(|x| x.as_str()), $exp);
2096                 }
2097             )
2098         }
2099
2100         t!(s: "a\\b\\c", "a\\b", Some("c"));
2101         t!(s: "a\\b\\c", "a\\b\\d", Some("..\\c"));
2102         t!(s: "a\\b\\c", "a\\b\\c\\d", Some(".."));
2103         t!(s: "a\\b\\c", "a\\b\\c", Some("."));
2104         t!(s: "a\\b\\c", "a\\b\\c\\d\\e", Some("..\\.."));
2105         t!(s: "a\\b\\c", "a\\d\\e", Some("..\\..\\b\\c"));
2106         t!(s: "a\\b\\c", "d\\e\\f", Some("..\\..\\..\\a\\b\\c"));
2107         t!(s: "a\\b\\c", "\\a\\b\\c", None);
2108         t!(s: "\\a\\b\\c", "a\\b\\c", Some("\\a\\b\\c"));
2109         t!(s: "\\a\\b\\c", "\\a\\b\\c\\d", Some(".."));
2110         t!(s: "\\a\\b\\c", "\\a\\b", Some("c"));
2111         t!(s: "\\a\\b\\c", "\\a\\b\\c\\d\\e", Some("..\\.."));
2112         t!(s: "\\a\\b\\c", "\\a\\d\\e", Some("..\\..\\b\\c"));
2113         t!(s: "\\a\\b\\c", "\\d\\e\\f", Some("..\\..\\..\\a\\b\\c"));
2114         t!(s: "hi\\there.txt", "hi\\there", Some("..\\there.txt"));
2115         t!(s: ".", "a", Some(".."));
2116         t!(s: ".", "a\\b", Some("..\\.."));
2117         t!(s: ".", ".", Some("."));
2118         t!(s: "a", ".", Some("a"));
2119         t!(s: "a\\b", ".", Some("a\\b"));
2120         t!(s: "..", ".", Some(".."));
2121         t!(s: "a\\b\\c", "a\\b\\c", Some("."));
2122         t!(s: "\\a\\b\\c", "\\a\\b\\c", Some("."));
2123         t!(s: "\\", "\\", Some("."));
2124         t!(s: "\\", ".", Some("\\"));
2125         t!(s: "..\\..\\a", "b", Some("..\\..\\..\\a"));
2126         t!(s: "a", "..\\..\\b", None);
2127         t!(s: "..\\..\\a", "..\\..\\b", Some("..\\a"));
2128         t!(s: "..\\..\\a", "..\\..\\a\\b", Some(".."));
2129         t!(s: "..\\..\\a\\b", "..\\..\\a", Some("b"));
2130
2131         t!(s: "C:a\\b\\c", "C:a\\b", Some("c"));
2132         t!(s: "C:a\\b", "C:a\\b\\c", Some(".."));
2133         t!(s: "C:" ,"C:a\\b", Some("..\\.."));
2134         t!(s: "C:a\\b", "C:c\\d", Some("..\\..\\a\\b"));
2135         t!(s: "C:a\\b", "D:c\\d", Some("C:a\\b"));
2136         t!(s: "C:a\\b", "C:..\\c", None);
2137         t!(s: "C:..\\a", "C:b\\c", Some("..\\..\\..\\a"));
2138         t!(s: "C:\\a\\b\\c", "C:\\a\\b", Some("c"));
2139         t!(s: "C:\\a\\b", "C:\\a\\b\\c", Some(".."));
2140         t!(s: "C:\\", "C:\\a\\b", Some("..\\.."));
2141         t!(s: "C:\\a\\b", "C:\\c\\d", Some("..\\..\\a\\b"));
2142         t!(s: "C:\\a\\b", "C:a\\b", Some("C:\\a\\b"));
2143         t!(s: "C:a\\b", "C:\\a\\b", None);
2144         t!(s: "\\a\\b", "C:\\a\\b", None);
2145         t!(s: "\\a\\b", "C:a\\b", None);
2146         t!(s: "a\\b", "C:\\a\\b", None);
2147         t!(s: "a\\b", "C:a\\b", None);
2148
2149         t!(s: "\\\\a\\b\\c", "\\\\a\\b", Some("c"));
2150         t!(s: "\\\\a\\b", "\\\\a\\b\\c", Some(".."));
2151         t!(s: "\\\\a\\b\\c\\e", "\\\\a\\b\\c\\d", Some("..\\e"));
2152         t!(s: "\\\\a\\c\\d", "\\\\a\\b\\d", Some("\\\\a\\c\\d"));
2153         t!(s: "\\\\b\\c\\d", "\\\\a\\c\\d", Some("\\\\b\\c\\d"));
2154         t!(s: "\\\\a\\b\\c", "\\d\\e", Some("\\\\a\\b\\c"));
2155         t!(s: "\\d\\e", "\\\\a\\b\\c", None);
2156         t!(s: "d\\e", "\\\\a\\b\\c", None);
2157         t!(s: "C:\\a\\b\\c", "\\\\a\\b\\c", Some("C:\\a\\b\\c"));
2158         t!(s: "C:\\c", "\\\\a\\b\\c", Some("C:\\c"));
2159
2160         t!(s: "\\\\?\\a\\b", "\\a\\b", Some("\\\\?\\a\\b"));
2161         t!(s: "\\\\?\\a\\b", "a\\b", Some("\\\\?\\a\\b"));
2162         t!(s: "\\\\?\\a\\b", "\\b", Some("\\\\?\\a\\b"));
2163         t!(s: "\\\\?\\a\\b", "b", Some("\\\\?\\a\\b"));
2164         t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\c", Some(".."));
2165         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", Some("c"));
2166         t!(s: "\\\\?\\a\\b", "\\\\?\\c\\d", Some("\\\\?\\a\\b"));
2167         t!(s: "\\\\?\\a", "\\\\?\\b", Some("\\\\?\\a"));
2168
2169         t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", Some("b"));
2170         t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\a\\b", Some(".."));
2171         t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\b", Some("..\\a"));
2172         t!(s: "\\\\?\\C:\\a", "\\\\?\\D:\\a", Some("\\\\?\\C:\\a"));
2173         t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\c:\\a", Some("b"));
2174         t!(s: "\\\\?\\C:\\a\\b", "C:\\a", Some("b"));
2175         t!(s: "\\\\?\\C:\\a", "C:\\a\\b", Some(".."));
2176         t!(s: "C:\\a\\b", "\\\\?\\C:\\a", Some("b"));
2177         t!(s: "C:\\a", "\\\\?\\C:\\a\\b", Some(".."));
2178         t!(s: "\\\\?\\C:\\a", "D:\\a", Some("\\\\?\\C:\\a"));
2179         t!(s: "\\\\?\\c:\\a\\b", "C:\\a", Some("b"));
2180         t!(s: "\\\\?\\C:\\a\\b", "C:a\\b", Some("\\\\?\\C:\\a\\b"));
2181         t!(s: "\\\\?\\C:\\a\\.\\b", "C:\\a", Some("\\\\?\\C:\\a\\.\\b"));
2182         t!(s: "\\\\?\\C:\\a\\b/c", "C:\\a", Some("\\\\?\\C:\\a\\b/c"));
2183         t!(s: "\\\\?\\C:\\a\\..\\b", "C:\\a", Some("\\\\?\\C:\\a\\..\\b"));
2184         t!(s: "C:a\\b", "\\\\?\\C:\\a\\b", None);
2185         t!(s: "\\\\?\\C:\\a\\.\\b", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\.\\b"));
2186         t!(s: "\\\\?\\C:\\a\\b/c", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\b/c"));
2187         t!(s: "\\\\?\\C:\\a\\..\\b", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\..\\b"));
2188         t!(s: "\\\\?\\C:\\a\\b\\", "\\\\?\\C:\\a", Some("b"));
2189         t!(s: "\\\\?\\C:\\.\\b", "\\\\?\\C:\\.", Some("b"));
2190         t!(s: "C:\\b", "\\\\?\\C:\\.", Some("..\\b"));
2191         t!(s: "\\\\?\\a\\.\\b\\c", "\\\\?\\a\\.\\b", Some("c"));
2192         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\.\\d", Some("..\\..\\b\\c"));
2193         t!(s: "\\\\?\\a\\..\\b", "\\\\?\\a\\..", Some("b"));
2194         t!(s: "\\\\?\\a\\b\\..", "\\\\?\\a\\b", Some("\\\\?\\a\\b\\.."));
2195         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\..\\b", Some("..\\..\\b\\c"));
2196
2197         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\b", Some("c"));
2198         t!(s: "\\\\?\\UNC\\a\\b", "\\\\?\\UNC\\a\\b\\c", Some(".."));
2199         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\c\\d", Some("\\\\?\\UNC\\a\\b\\c"));
2200         t!(s: "\\\\?\\UNC\\b\\c\\d", "\\\\?\\UNC\\a\\c\\d", Some("\\\\?\\UNC\\b\\c\\d"));
2201         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\a\\b\\c", Some("\\\\?\\UNC\\a\\b\\c"));
2202         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\C:\\a\\b\\c", Some("\\\\?\\UNC\\a\\b\\c"));
2203         t!(s: "\\\\?\\UNC\\a\\b\\c/d", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\c/d"));
2204         t!(s: "\\\\?\\UNC\\a\\b\\.", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\."));
2205         t!(s: "\\\\?\\UNC\\a\\b\\..", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\.."));
2206         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\b", Some("c"));
2207         t!(s: "\\\\?\\UNC\\a\\b", "\\\\a\\b\\c", Some(".."));
2208         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\c\\d", Some("\\\\?\\UNC\\a\\b\\c"));
2209         t!(s: "\\\\?\\UNC\\b\\c\\d", "\\\\a\\c\\d", Some("\\\\?\\UNC\\b\\c\\d"));
2210         t!(s: "\\\\?\\UNC\\a\\b\\.", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\."));
2211         t!(s: "\\\\?\\UNC\\a\\b\\c/d", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\c/d"));
2212         t!(s: "\\\\?\\UNC\\a\\b\\..", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\.."));
2213         t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\b", Some("c"));
2214         t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\c\\d", Some("\\\\a\\b\\c"));
2215     }
2216
2217     #[test]
2218     fn test_str_components() {
2219         macro_rules! t {
2220             (s: $path:expr, $exp:expr) => (
2221                 {
2222                     let path = Path::new($path);
2223                     let comps = path.str_components().map(|x|x.unwrap())
2224                                 .collect::<Vec<&str>>();
2225                     let exp: &[&str] = &$exp;
2226                     assert_eq!(comps, exp);
2227                     let comps = path.str_components().rev().map(|x|x.unwrap())
2228                                 .collect::<Vec<&str>>();
2229                     let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&str>>();
2230                     assert_eq!(comps, exp);
2231                 }
2232             );
2233         }
2234
2235         t!(s: b"a\\b\\c", ["a", "b", "c"]);
2236         t!(s: "a\\b\\c", ["a", "b", "c"]);
2237         t!(s: "a\\b\\d", ["a", "b", "d"]);
2238         t!(s: "a\\b\\cd", ["a", "b", "cd"]);
2239         t!(s: "\\a\\b\\c", ["a", "b", "c"]);
2240         t!(s: "a", ["a"]);
2241         t!(s: "\\a", ["a"]);
2242         t!(s: "\\", []);
2243         t!(s: ".", ["."]);
2244         t!(s: "..", [".."]);
2245         t!(s: "..\\..", ["..", ".."]);
2246         t!(s: "..\\..\\foo", ["..", "..", "foo"]);
2247         t!(s: "C:foo\\bar", ["foo", "bar"]);
2248         t!(s: "C:foo", ["foo"]);
2249         t!(s: "C:", []);
2250         t!(s: "C:\\foo\\bar", ["foo", "bar"]);
2251         t!(s: "C:\\foo", ["foo"]);
2252         t!(s: "C:\\", []);
2253         t!(s: "\\\\server\\share\\foo\\bar", ["foo", "bar"]);
2254         t!(s: "\\\\server\\share\\foo", ["foo"]);
2255         t!(s: "\\\\server\\share", []);
2256         t!(s: "\\\\?\\foo\\bar\\baz", ["bar", "baz"]);
2257         t!(s: "\\\\?\\foo\\bar", ["bar"]);
2258         t!(s: "\\\\?\\foo", []);
2259         t!(s: "\\\\?\\", []);
2260         t!(s: "\\\\?\\a\\b", ["b"]);
2261         t!(s: "\\\\?\\a\\b\\", ["b"]);
2262         t!(s: "\\\\?\\foo\\bar\\\\baz", ["bar", "", "baz"]);
2263         t!(s: "\\\\?\\C:\\foo\\bar", ["foo", "bar"]);
2264         t!(s: "\\\\?\\C:\\foo", ["foo"]);
2265         t!(s: "\\\\?\\C:\\", []);
2266         t!(s: "\\\\?\\C:\\foo\\", ["foo"]);
2267         t!(s: "\\\\?\\UNC\\server\\share\\foo\\bar", ["foo", "bar"]);
2268         t!(s: "\\\\?\\UNC\\server\\share\\foo", ["foo"]);
2269         t!(s: "\\\\?\\UNC\\server\\share", []);
2270         t!(s: "\\\\.\\foo\\bar\\baz", ["bar", "baz"]);
2271         t!(s: "\\\\.\\foo\\bar", ["bar"]);
2272         t!(s: "\\\\.\\foo", []);
2273     }
2274
2275     #[test]
2276     fn test_components_iter() {
2277         macro_rules! t {
2278             (s: $path:expr, $exp:expr) => (
2279                 {
2280                     let path = Path::new($path);
2281                     let comps = path.components().collect::<Vec<&[u8]>>();
2282                     let exp: &[&[u8]] = &$exp;
2283                     assert_eq!(comps, exp);
2284                     let comps = path.components().rev().collect::<Vec<&[u8]>>();
2285                     let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
2286                     assert_eq!(comps, exp);
2287                 }
2288             )
2289         }
2290
2291         t!(s: "a\\b\\c", [b"a", b"b", b"c"]);
2292         t!(s: ".", [b"."]);
2293         // since this is really a wrapper around str_components, those tests suffice
2294     }
2295
2296     #[test]
2297     fn test_make_non_verbatim() {
2298         macro_rules! t {
2299             ($path:expr, $exp:expr) => (
2300                 {
2301                     let path = Path::new($path);
2302                     let exp: Option<&str> = $exp;
2303                     let exp = exp.map(|s| Path::new(s));
2304                     assert_eq!(make_non_verbatim(&path), exp);
2305                 }
2306             )
2307         }
2308
2309         t!(r"\a\b\c", Some(r"\a\b\c"));
2310         t!(r"a\b\c", Some(r"a\b\c"));
2311         t!(r"C:\a\b\c", Some(r"C:\a\b\c"));
2312         t!(r"C:a\b\c", Some(r"C:a\b\c"));
2313         t!(r"\\server\share\foo", Some(r"\\server\share\foo"));
2314         t!(r"\\.\foo", None);
2315         t!(r"\\?\foo", None);
2316         t!(r"\\?\C:", None);
2317         t!(r"\\?\C:foo", None);
2318         t!(r"\\?\C:\", Some(r"C:\"));
2319         t!(r"\\?\C:\foo", Some(r"C:\foo"));
2320         t!(r"\\?\C:\foo\bar\baz", Some(r"C:\foo\bar\baz"));
2321         t!(r"\\?\C:\foo\.\bar\baz", None);
2322         t!(r"\\?\C:\foo\bar\..\baz", None);
2323         t!(r"\\?\C:\foo\bar\..", None);
2324         t!(r"\\?\UNC\server\share\foo", Some(r"\\server\share\foo"));
2325         t!(r"\\?\UNC\server\share", Some(r"\\server\share"));
2326         t!(r"\\?\UNC\server", None);
2327         t!(r"\\?\UNC\server\", None);
2328     }
2329 }