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