]> git.lizzy.rs Git - rust.git/blob - src/libstd/path/windows.rs
176788edcc46650720f705a303e5d5c7f19ec44b
[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 //! Windows file path handling
12
13 use ascii::AsciiCast;
14 use c_str::{CString, ToCStr};
15 use clone::Clone;
16 use cmp::{Eq, TotalEq};
17 use container::Container;
18 use from_str::FromStr;
19 use io::Writer;
20 use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Rev, Iterator, Map};
21 use mem;
22 use option::{Option, Some, None};
23 use slice::{Vector, OwnedVector, ImmutableVector};
24 use str::{CharSplits, Str, StrAllocating, StrVector, StrSlice};
25 use strbuf::StrBuf;
26 use vec::Vec;
27
28 use super::{contains_nul, BytesContainer, GenericPath, GenericPathUnsafe};
29
30 /// Iterator that yields successive components of a Path as &str
31 ///
32 /// Each component is yielded as Option<&str> for compatibility with PosixPath, but
33 /// every component in WindowsPath is guaranteed to be Some.
34 pub type StrComponents<'a> = Map<'a, &'a str, Option<&'a str>,
35                                        CharSplits<'a, char>>;
36 /// Iterator that yields components of a Path in reverse 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 #[deprecated = "replaced by Rev<StrComponents<'a>>"]
41 pub type RevStrComponents<'a> = Rev<StrComponents<'a>>;
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 /// Iterator that yields components of a Path in reverse as &[u8]
47 #[deprecated = "replaced by Rev<Components<'a>>"]
48 pub type RevComponents<'a> = Rev<Components<'a>>;
49
50 /// Represents a Windows path
51 // Notes for Windows path impl:
52 // The MAX_PATH is 260, but 253 is the practical limit due to some API bugs
53 // See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx for good information
54 // about windows paths.
55 // That same page puts a bunch of restrictions on allowed characters in a path.
56 // `\foo.txt` means "relative to current drive", but will not be considered to be absolute here
57 // as `∃P | P.join("\foo.txt") != "\foo.txt"`.
58 // `C:` is interesting, that means "the current directory on drive C".
59 // Long absolute paths need to have \\?\ prefix (or, for UNC, \\?\UNC\). I think that can be
60 // ignored for now, though, and only added in a hypothetical .to_pwstr() function.
61 // However, if a path is parsed that has \\?\, this needs to be preserved as it disables the
62 // processing of "." and ".." components and / as a separator.
63 // Experimentally, \\?\foo is not the same thing as \foo.
64 // Also, \\foo is not valid either (certainly not equivalent to \foo).
65 // Similarly, C:\\Users is not equivalent to C:\Users, although C:\Users\\foo is equivalent
66 // to C:\Users\foo. In fact the command prompt treats C:\\foo\bar as UNC path. But it might be
67 // best to just ignore that and normalize it to C:\foo\bar.
68 //
69 // Based on all this, I think the right approach is to do the following:
70 // * Require valid utf-8 paths. Windows API may use WCHARs, but we don't, and utf-8 is convertible
71 // to UTF-16 anyway (though does Windows use UTF-16 or UCS-2? Not sure).
72 // * Parse the prefixes \\?\UNC\, \\?\, and \\.\ explicitly.
73 // * If \\?\UNC\, treat following two path components as server\share. Don't error for missing
74 //   server\share.
75 // * If \\?\, parse disk from following component, if present. Don't error for missing disk.
76 // * If \\.\, treat rest of path as just regular components. I don't know how . and .. are handled
77 //   here, they probably aren't, but I'm not going to worry about that.
78 // * Else if starts with \\, treat following two components as server\share. Don't error for missing
79 //   server\share.
80 // * Otherwise, attempt to parse drive from start of path.
81 //
82 // The only error condition imposed here is valid utf-8. All other invalid paths are simply
83 // preserved by the data structure; let the Windows API error out on them.
84 #[deriving(Clone)]
85 pub struct Path {
86     repr: StrBuf, // assumed to never be empty
87     prefix: Option<PathPrefix>,
88     sepidx: Option<uint> // index of the final separator in the non-prefix portion of repr
89 }
90
91 impl Eq for Path {
92     #[inline]
93     fn eq(&self, other: &Path) -> bool {
94         self.repr == other.repr
95     }
96 }
97
98 impl TotalEq for Path {}
99
100 impl FromStr for Path {
101     fn from_str(s: &str) -> Option<Path> {
102         Path::new_opt(s)
103     }
104 }
105
106 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
107 // we cannot usefully take ToCStr arguments by reference (without forcing an
108 // additional & around &str). So we are instead temporarily adding an instance
109 // for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
110 // instance should be removed, and arguments bound by ToCStr should be passed by
111 // reference.
112
113 impl ToCStr for Path {
114     #[inline]
115     fn to_c_str(&self) -> CString {
116         // The Path impl guarantees no internal NUL
117         unsafe { self.to_c_str_unchecked() }
118     }
119
120     #[inline]
121     unsafe fn to_c_str_unchecked(&self) -> CString {
122         self.as_vec().to_c_str_unchecked()
123     }
124 }
125
126 impl<'a> ToCStr for &'a Path {
127     #[inline]
128     fn to_c_str(&self) -> CString {
129         (*self).to_c_str()
130     }
131
132     #[inline]
133     unsafe fn to_c_str_unchecked(&self) -> CString {
134         (*self).to_c_str_unchecked()
135     }
136 }
137
138 impl<S: Writer> ::hash::Hash<S> for Path {
139     #[inline]
140     fn hash(&self, state: &mut S) {
141         self.repr.hash(state)
142     }
143 }
144
145 impl BytesContainer for Path {
146     #[inline]
147     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
148         self.as_vec()
149     }
150     #[inline]
151     fn container_into_owned_bytes(self) -> Vec<u8> {
152         self.into_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<'a> BytesContainer for &'a Path {
163     #[inline]
164     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
165         self.as_vec()
166     }
167     #[inline]
168     fn container_as_str<'a>(&'a self) -> Option<&'a str> {
169         self.as_str()
170     }
171     #[inline]
172     fn is_str(_: Option<&'a Path>) -> bool { true }
173 }
174
175 impl GenericPathUnsafe for Path {
176     /// See `GenericPathUnsafe::from_vec_unchecked`.
177     ///
178     /// # Failure
179     ///
180     /// Fails if not valid UTF-8.
181     #[inline]
182     unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
183         let (prefix, path) = Path::normalize_(path.container_as_str().unwrap());
184         assert!(!path.is_empty());
185         let mut ret = Path{ repr: path, prefix: prefix, sepidx: None };
186         ret.update_sepidx();
187         ret
188     }
189
190     /// See `GenericPathUnsafe::set_filename_unchecekd`.
191     ///
192     /// # Failure
193     ///
194     /// Fails if not valid UTF-8.
195     unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
196         let filename = filename.container_as_str().unwrap();
197         match self.sepidx_or_prefix_len() {
198             None if ".." == self.repr.as_slice() => {
199                 let mut s = StrBuf::with_capacity(3 + filename.len());
200                 s.push_str("..");
201                 s.push_char(SEP);
202                 s.push_str(filename);
203                 self.update_normalized(s);
204             }
205             None => {
206                 self.update_normalized(filename);
207             }
208             Some((_,idxa,end)) if self.repr.as_slice().slice(idxa,end) == ".." => {
209                 let mut s = StrBuf::with_capacity(end + 1 + filename.len());
210                 s.push_str(self.repr.as_slice().slice_to(end));
211                 s.push_char(SEP);
212                 s.push_str(filename);
213                 self.update_normalized(s);
214             }
215             Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => {
216                 let mut s = StrBuf::with_capacity(idxb + filename.len());
217                 s.push_str(self.repr.as_slice().slice_to(idxb));
218                 s.push_str(filename);
219                 self.update_normalized(s);
220             }
221             Some((idxb,_,_)) => {
222                 let mut s = StrBuf::with_capacity(idxb + 1 + filename.len());
223                 s.push_str(self.repr.as_slice().slice_to(idxb));
224                 s.push_char(SEP);
225                 s.push_str(filename);
226                 self.update_normalized(s);
227             }
228         }
229     }
230
231     /// See `GenericPathUnsafe::push_unchecked`.
232     ///
233     /// Concatenating two Windows Paths is rather complicated.
234     /// For the most part, it will behave as expected, except in the case of
235     /// pushing a volume-relative path, e.g. `C:foo.txt`. Because we have no
236     /// concept of per-volume cwds like Windows does, we can't behave exactly
237     /// like Windows will. Instead, if the receiver is an absolute path on
238     /// the same volume as the new path, it will be treated as the cwd that
239     /// the new path is relative to. Otherwise, the new path will be treated
240     /// as if it were absolute and will replace the receiver outright.
241     unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
242         let path = path.container_as_str().unwrap();
243         fn is_vol_abs(path: &str, prefix: Option<PathPrefix>) -> bool {
244             // assume prefix is Some(DiskPrefix)
245             let rest = path.slice_from(prefix_len(prefix));
246             !rest.is_empty() && rest[0].is_ascii() && is_sep(rest[0] as char)
247         }
248         fn shares_volume(me: &Path, path: &str) -> bool {
249             // path is assumed to have a prefix of Some(DiskPrefix)
250             let repr = me.repr.as_slice();
251             match me.prefix {
252                 Some(DiskPrefix) => repr[0] == path[0].to_ascii().to_upper().to_byte(),
253                 Some(VerbatimDiskPrefix) => repr[4] == path[0].to_ascii().to_upper().to_byte(),
254                 _ => false
255             }
256         }
257         fn is_sep_(prefix: Option<PathPrefix>, u: u8) -> bool {
258             if prefix_is_verbatim(prefix) { is_sep_verbatim(u as char) }
259             else { is_sep(u as char) }
260         }
261
262         fn replace_path(me: &mut Path, path: &str, prefix: Option<PathPrefix>) {
263             let newpath = Path::normalize__(path, prefix);
264             me.repr = match newpath {
265                 Some(p) => p,
266                 None => StrBuf::from_str(path)
267             };
268             me.prefix = prefix;
269             me.update_sepidx();
270         }
271         fn append_path(me: &mut Path, path: &str) {
272             // appends a path that has no prefix
273             // if me is verbatim, we need to pre-normalize the new path
274             let path_ = if is_verbatim(me) { Path::normalize__(path, None) }
275                         else { None };
276             let pathlen = path_.as_ref().map_or(path.len(), |p| p.len());
277             let mut s = StrBuf::with_capacity(me.repr.len() + 1 + pathlen);
278             s.push_str(me.repr.as_slice());
279             let plen = me.prefix_len();
280             // if me is "C:" we don't want to add a path separator
281             match me.prefix {
282                 Some(DiskPrefix) if me.repr.len() == plen => (),
283                 _ if !(me.repr.len() > plen && me.repr.as_slice()[me.repr.len()-1] == SEP_BYTE) => {
284                     s.push_char(SEP);
285                 }
286                 _ => ()
287             }
288             match path_ {
289                 None => s.push_str(path),
290                 Some(p) => s.push_str(p.as_slice())
291             };
292             me.update_normalized(s)
293         }
294
295         if !path.is_empty() {
296             let prefix = parse_prefix(path);
297             match prefix {
298                 Some(DiskPrefix) if !is_vol_abs(path, prefix) && shares_volume(self, path) => {
299                     // cwd-relative path, self is on the same volume
300                     append_path(self, path.slice_from(prefix_len(prefix)));
301                 }
302                 Some(_) => {
303                     // absolute path, or cwd-relative and self is not same volume
304                     replace_path(self, path, prefix);
305                 }
306                 None if !path.is_empty() && is_sep_(self.prefix, path[0]) => {
307                     // volume-relative path
308                     if self.prefix.is_some() {
309                         // truncate self down to the prefix, then append
310                         let n = self.prefix_len();
311                         self.repr.truncate(n);
312                         append_path(self, path);
313                     } else {
314                         // we have no prefix, so nothing to be relative to
315                         replace_path(self, path, prefix);
316                     }
317                 }
318                 None => {
319                     // relative path
320                     append_path(self, path);
321                 }
322             }
323         }
324     }
325 }
326
327 impl GenericPath for Path {
328     #[inline]
329     fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
330         match path.container_as_str() {
331             None => None,
332             Some(ref s) => {
333                 if contains_nul(s) {
334                     None
335                 } else {
336                     Some(unsafe { GenericPathUnsafe::new_unchecked(*s) })
337                 }
338             }
339         }
340     }
341
342     /// See `GenericPath::as_str` for info.
343     /// Always returns a `Some` value.
344     #[inline]
345     fn as_str<'a>(&'a self) -> Option<&'a str> {
346         Some(self.repr.as_slice())
347     }
348
349     #[inline]
350     fn as_vec<'a>(&'a self) -> &'a [u8] {
351         self.repr.as_bytes()
352     }
353
354     #[inline]
355     fn into_vec(self) -> Vec<u8> {
356         Vec::from_slice(self.repr.as_bytes())
357     }
358
359     #[inline]
360     fn dirname<'a>(&'a self) -> &'a [u8] {
361         self.dirname_str().unwrap().as_bytes()
362     }
363
364     /// See `GenericPath::dirname_str` for info.
365     /// Always returns a `Some` value.
366     fn dirname_str<'a>(&'a self) -> Option<&'a str> {
367         Some(match self.sepidx_or_prefix_len() {
368             None if ".." == self.repr.as_slice() => self.repr.as_slice(),
369             None => ".",
370             Some((_,idxa,end)) if self.repr.as_slice().slice(idxa, end) == ".." => {
371                 self.repr.as_slice()
372             }
373             Some((idxb,_,end)) if self.repr.as_slice().slice(idxb, end) == "\\" => {
374                 self.repr.as_slice()
375             }
376             Some((0,idxa,_)) => self.repr.as_slice().slice_to(idxa),
377             Some((idxb,idxa,_)) => {
378                 match self.prefix {
379                     Some(DiskPrefix) | Some(VerbatimDiskPrefix) if idxb == self.prefix_len() => {
380                         self.repr.as_slice().slice_to(idxa)
381                     }
382                     _ => self.repr.as_slice().slice_to(idxb)
383                 }
384             }
385         })
386     }
387
388     #[inline]
389     fn filename<'a>(&'a self) -> Option<&'a [u8]> {
390         self.filename_str().map(|x| x.as_bytes())
391     }
392
393     /// See `GenericPath::filename_str` for info.
394     /// Always returns a `Some` value if `filename` returns a `Some` value.
395     fn filename_str<'a>(&'a self) -> Option<&'a str> {
396         let repr = self.repr.as_slice();
397         match self.sepidx_or_prefix_len() {
398             None if "." == repr || ".." == repr => None,
399             None => Some(repr),
400             Some((_,idxa,end)) if repr.slice(idxa, end) == ".." => None,
401             Some((_,idxa,end)) if idxa == end => None,
402             Some((_,idxa,end)) => Some(repr.slice(idxa, end))
403         }
404     }
405
406     /// See `GenericPath::filestem_str` for info.
407     /// Always returns a `Some` value if `filestem` returns a `Some` value.
408     #[inline]
409     fn filestem_str<'a>(&'a self) -> Option<&'a str> {
410         // filestem() returns a byte vector that's guaranteed valid UTF-8
411         self.filestem().map(|t| unsafe { mem::transmute(t) })
412     }
413
414     #[inline]
415     fn extension_str<'a>(&'a self) -> Option<&'a str> {
416         // extension() returns a byte vector that's guaranteed valid UTF-8
417         self.extension().map(|t| unsafe { mem::transmute(t) })
418     }
419
420     fn dir_path(&self) -> Path {
421         unsafe { GenericPathUnsafe::new_unchecked(self.dirname_str().unwrap()) }
422     }
423
424     #[inline]
425     fn pop(&mut self) -> bool {
426         match self.sepidx_or_prefix_len() {
427             None if "." == self.repr.as_slice() => false,
428             None => {
429                 self.repr = StrBuf::from_str(".");
430                 self.sepidx = None;
431                 true
432             }
433             Some((idxb,idxa,end)) if idxb == idxa && idxb == end => false,
434             Some((idxb,_,end)) if self.repr.as_slice().slice(idxb, end) == "\\" => false,
435             Some((idxb,idxa,_)) => {
436                 let trunc = match self.prefix {
437                     Some(DiskPrefix) | Some(VerbatimDiskPrefix) | None => {
438                         let plen = self.prefix_len();
439                         if idxb == plen { idxa } else { idxb }
440                     }
441                     _ => idxb
442                 };
443                 self.repr.truncate(trunc);
444                 self.update_sepidx();
445                 true
446             }
447         }
448     }
449
450     fn root_path(&self) -> Option<Path> {
451         if self.prefix.is_some() {
452             Some(Path::new(match self.prefix {
453                 Some(DiskPrefix) if self.is_absolute() => {
454                     self.repr.as_slice().slice_to(self.prefix_len()+1)
455                 }
456                 Some(VerbatimDiskPrefix) => {
457                     self.repr.as_slice().slice_to(self.prefix_len()+1)
458                 }
459                 _ => self.repr.as_slice().slice_to(self.prefix_len())
460             }))
461         } else if is_vol_relative(self) {
462             Some(Path::new(self.repr.as_slice().slice_to(1)))
463         } else {
464             None
465         }
466     }
467
468     /// See `GenericPath::is_absolute` for info.
469     ///
470     /// A Windows Path is considered absolute only if it has a non-volume prefix,
471     /// or if it has a volume prefix and the path starts with '\'.
472     /// A path of `\foo` is not considered absolute because it's actually
473     /// relative to the "current volume". A separate method `Path::is_vol_relative`
474     /// is provided to indicate this case. Similarly a path of `C:foo` is not
475     /// considered absolute because it's relative to the cwd on volume C:. A
476     /// separate method `Path::is_cwd_relative` is provided to indicate this case.
477     #[inline]
478     fn is_absolute(&self) -> bool {
479         match self.prefix {
480             Some(DiskPrefix) => {
481                 let rest = self.repr.as_slice().slice_from(self.prefix_len());
482                 rest.len() > 0 && rest[0] == SEP_BYTE
483             }
484             Some(_) => true,
485             None => false
486         }
487     }
488
489     #[inline]
490     fn is_relative(&self) -> bool {
491         self.prefix.is_none() && !is_vol_relative(self)
492     }
493
494     fn is_ancestor_of(&self, other: &Path) -> bool {
495         if !self.equiv_prefix(other) {
496             false
497         } else if self.is_absolute() != other.is_absolute() ||
498                   is_vol_relative(self) != is_vol_relative(other) {
499             false
500         } else {
501             let mut ita = self.str_components().map(|x|x.unwrap());
502             let mut itb = other.str_components().map(|x|x.unwrap());
503             if "." == self.repr.as_slice() {
504                 return itb.next() != Some("..");
505             }
506             loop {
507                 match (ita.next(), itb.next()) {
508                     (None, _) => break,
509                     (Some(a), Some(b)) if a == b => { continue },
510                     (Some(a), _) if a == ".." => {
511                         // if ita contains only .. components, it's an ancestor
512                         return ita.all(|x| x == "..");
513                     }
514                     _ => return false
515                 }
516             }
517             true
518         }
519     }
520
521     fn path_relative_from(&self, base: &Path) -> Option<Path> {
522         fn comp_requires_verbatim(s: &str) -> bool {
523             s == "." || s == ".." || s.contains_char(SEP2)
524         }
525
526         if !self.equiv_prefix(base) {
527             // prefixes differ
528             if self.is_absolute() {
529                 Some(self.clone())
530             } else if self.prefix == Some(DiskPrefix) && base.prefix == Some(DiskPrefix) {
531                 // both drives, drive letters must differ or they'd be equiv
532                 Some(self.clone())
533             } else {
534                 None
535             }
536         } else if self.is_absolute() != base.is_absolute() {
537             if self.is_absolute() {
538                 Some(self.clone())
539             } else {
540                 None
541             }
542         } else if is_vol_relative(self) != is_vol_relative(base) {
543             if is_vol_relative(self) {
544                 Some(self.clone())
545             } else {
546                 None
547             }
548         } else {
549             let mut ita = self.str_components().map(|x|x.unwrap());
550             let mut itb = base.str_components().map(|x|x.unwrap());
551             let mut comps = vec![];
552
553             let a_verb = is_verbatim(self);
554             let b_verb = is_verbatim(base);
555             loop {
556                 match (ita.next(), itb.next()) {
557                     (None, None) => break,
558                     (Some(a), None) if a_verb && comp_requires_verbatim(a) => {
559                         return Some(self.clone())
560                     }
561                     (Some(a), None) => {
562                         comps.push(a);
563                         if !a_verb {
564                             comps.extend(ita.by_ref());
565                             break;
566                         }
567                     }
568                     (None, _) => comps.push(".."),
569                     (Some(a), Some(b)) if comps.is_empty() && a == b => (),
570                     (Some(a), Some(b)) if !b_verb && b == "." => {
571                         if a_verb && comp_requires_verbatim(a) {
572                             return Some(self.clone())
573                         } else { comps.push(a) }
574                     }
575                     (Some(_), Some(b)) if !b_verb && b == ".." => return None,
576                     (Some(a), Some(_)) if a_verb && comp_requires_verbatim(a) => {
577                         return Some(self.clone())
578                     }
579                     (Some(a), Some(_)) => {
580                         comps.push("..");
581                         for _ in itb {
582                             comps.push("..");
583                         }
584                         comps.push(a);
585                         if !a_verb {
586                             comps.extend(ita.by_ref());
587                             break;
588                         }
589                     }
590                 }
591             }
592             Some(Path::new(comps.connect("\\")))
593         }
594     }
595
596     fn ends_with_path(&self, child: &Path) -> bool {
597         if !child.is_relative() { return false; }
598         let mut selfit = self.str_components().rev();
599         let mut childit = child.str_components().rev();
600         loop {
601             match (selfit.next(), childit.next()) {
602                 (Some(a), Some(b)) => if a != b { return false; },
603                 (Some(_), None) => break,
604                 (None, Some(_)) => return false,
605                 (None, None) => break
606             }
607         }
608         true
609     }
610 }
611
612 impl Path {
613     /// Returns a new Path from a byte vector or string
614     ///
615     /// # Failure
616     ///
617     /// Fails the task if the vector contains a NUL.
618     /// Fails if invalid UTF-8.
619     #[inline]
620     pub fn new<T: BytesContainer>(path: T) -> Path {
621         GenericPath::new(path)
622     }
623
624     /// Returns a new Path from a byte vector or string, if possible
625     #[inline]
626     pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
627         GenericPath::new_opt(path)
628     }
629
630     /// Returns an iterator that yields each component of the path in turn as a Option<&str>.
631     /// Every component is guaranteed to be Some.
632     /// Does not yield the path prefix (including server/share components in UNC paths).
633     /// Does not distinguish between volume-relative and relative paths, e.g.
634     /// \a\b\c and a\b\c.
635     /// Does not distinguish between absolute and cwd-relative paths, e.g.
636     /// C:\foo and C:foo.
637     pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
638         let repr = self.repr.as_slice();
639         let s = match self.prefix {
640             Some(_) => {
641                 let plen = self.prefix_len();
642                 if repr.len() > plen && repr[plen] == SEP_BYTE {
643                     repr.slice_from(plen+1)
644                 } else { repr.slice_from(plen) }
645             }
646             None if repr[0] == SEP_BYTE => repr.slice_from(1),
647             None => repr
648         };
649         let ret = s.split_terminator(SEP).map(Some);
650         ret
651     }
652
653     /// Returns an iterator that yields each component of the path in reverse as an Option<&str>
654     /// See str_components() for details.
655     #[deprecated = "replaced by .str_components().rev()"]
656     pub fn rev_str_components<'a>(&'a self) -> Rev<StrComponents<'a>> {
657         self.str_components().rev()
658     }
659
660     /// Returns an iterator that yields each component of the path in turn as a &[u8].
661     /// See str_components() for details.
662     pub fn components<'a>(&'a self) -> Components<'a> {
663         fn convert<'a>(x: Option<&'a str>) -> &'a [u8] {
664             #![inline]
665             x.unwrap().as_bytes()
666         }
667         self.str_components().map(convert)
668     }
669
670     /// Returns an iterator that yields each component of the path in reverse as a &[u8].
671     /// See str_components() for details.
672     #[deprecated = "replaced by .components().rev()"]
673     pub fn rev_components<'a>(&'a self) -> Rev<Components<'a>> {
674         self.components().rev()
675     }
676
677     fn equiv_prefix(&self, other: &Path) -> bool {
678         let s_repr = self.repr.as_slice();
679         let o_repr = other.repr.as_slice();
680         match (self.prefix, other.prefix) {
681             (Some(DiskPrefix), Some(VerbatimDiskPrefix)) => {
682                 self.is_absolute() &&
683                     s_repr[0].to_ascii().eq_ignore_case(o_repr[4].to_ascii())
684             }
685             (Some(VerbatimDiskPrefix), Some(DiskPrefix)) => {
686                 other.is_absolute() &&
687                     s_repr[4].to_ascii().eq_ignore_case(o_repr[0].to_ascii())
688             }
689             (Some(VerbatimDiskPrefix), Some(VerbatimDiskPrefix)) => {
690                 s_repr[4].to_ascii().eq_ignore_case(o_repr[4].to_ascii())
691             }
692             (Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => {
693                 s_repr.slice(2, self.prefix_len()) == o_repr.slice(8, other.prefix_len())
694             }
695             (Some(VerbatimUNCPrefix(_,_)), Some(UNCPrefix(_,_))) => {
696                 s_repr.slice(8, self.prefix_len()) == o_repr.slice(2, other.prefix_len())
697             }
698             (None, None) => true,
699             (a, b) if a == b => {
700                 s_repr.slice_to(self.prefix_len()) == o_repr.slice_to(other.prefix_len())
701             }
702             _ => false
703         }
704     }
705
706     fn normalize_<S: StrAllocating>(s: S) -> (Option<PathPrefix>, StrBuf) {
707         // make borrowck happy
708         let (prefix, val) = {
709             let prefix = parse_prefix(s.as_slice());
710             let path = Path::normalize__(s.as_slice(), prefix);
711             (prefix, path)
712         };
713         (prefix, match val {
714             None => s.into_strbuf(),
715             Some(val) => val
716         })
717     }
718
719     fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<StrBuf> {
720         if prefix_is_verbatim(prefix) {
721             // don't do any normalization
722             match prefix {
723                 Some(VerbatimUNCPrefix(x, 0)) if s.len() == 8 + x => {
724                     // the server component has no trailing '\'
725                     let mut s = StrBuf::from_str(s);
726                     s.push_char(SEP);
727                     Some(s)
728                 }
729                 _ => None
730             }
731         } else {
732             let (is_abs, comps) = normalize_helper(s, prefix);
733             let mut comps = comps;
734             match (comps.is_some(),prefix) {
735                 (false, Some(DiskPrefix)) => {
736                     if s[0] >= 'a' as u8 && s[0] <= 'z' as u8 {
737                         comps = Some(vec![]);
738                     }
739                 }
740                 (false, Some(VerbatimDiskPrefix)) => {
741                     if s[4] >= 'a' as u8 && s[0] <= 'z' as u8 {
742                         comps = Some(vec![]);
743                     }
744                 }
745                 _ => ()
746             }
747             match comps {
748                 None => None,
749                 Some(comps) => {
750                     if prefix.is_some() && comps.is_empty() {
751                         match prefix.unwrap() {
752                             DiskPrefix => {
753                                 let len = prefix_len(prefix) + is_abs as uint;
754                                 let mut s = StrBuf::from_str(s.slice_to(len));
755                                 unsafe {
756                                     let v = s.as_mut_vec();
757                                     *v.get_mut(0) = v.get(0).to_ascii().to_upper().to_byte();
758                                 }
759                                 if is_abs {
760                                     // normalize C:/ to C:\
761                                     unsafe {
762                                         *s.as_mut_vec().get_mut(2) = SEP_BYTE;
763                                     }
764                                 }
765                                 Some(s)
766                             }
767                             VerbatimDiskPrefix => {
768                                 let len = prefix_len(prefix) + is_abs as uint;
769                                 let mut s = StrBuf::from_str(s.slice_to(len));
770                                 unsafe {
771                                     let v = s.as_mut_vec();
772                                     *v.get_mut(4) = v.get(4).to_ascii().to_upper().to_byte();
773                                 }
774                                 Some(s)
775                             }
776                             _ => {
777                                 let plen = prefix_len(prefix);
778                                 if s.len() > plen {
779                                     Some(StrBuf::from_str(s.slice_to(plen)))
780                                 } else { None }
781                             }
782                         }
783                     } else if is_abs && comps.is_empty() {
784                         Some(StrBuf::from_char(1, SEP))
785                     } else {
786                         let prefix_ = s.slice_to(prefix_len(prefix));
787                         let n = prefix_.len() +
788                                 if is_abs { comps.len() } else { comps.len() - 1} +
789                                 comps.iter().map(|v| v.len()).sum();
790                         let mut s = StrBuf::with_capacity(n);
791                         match prefix {
792                             Some(DiskPrefix) => {
793                                 s.push_char(prefix_[0].to_ascii().to_upper().to_char());
794                                 s.push_char(':');
795                             }
796                             Some(VerbatimDiskPrefix) => {
797                                 s.push_str(prefix_.slice_to(4));
798                                 s.push_char(prefix_[4].to_ascii().to_upper().to_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_char(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.move_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_char(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_slice()[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_slice()[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 static SEP: char = '\\';
935 /// The standard path separator byte
936 pub static SEP_BYTE: u8 = SEP as u8;
937
938 /// The alternative path separator character
939 pub static SEP2: char = '/';
940 /// The alternative path separator character
941 pub static 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(Eq, Clone)]
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[1] == ':' as u8 {
1007                     let c = path[0];
1008                     if c.is_ascii() && ::char::is_alphabetic(c as char) {
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[1] == ':' as u8 {
1030         // C:
1031         let c = path[0];
1032         if c.is_ascii() && ::char::is_alphabetic(c as char) {
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     macro_rules! b(
1139         ($($arg:expr),+) => (
1140             {
1141                 static the_bytes: &'static [u8] = bytes!($($arg),+);
1142                 the_bytes
1143             }
1144         )
1145     )
1146
1147     #[test]
1148     fn test_parse_prefix() {
1149         macro_rules! t(
1150             ($path:expr, $exp:expr) => (
1151                 {
1152                     let path = $path;
1153                     let exp = $exp;
1154                     let res = parse_prefix(path);
1155                     assert!(res == exp,
1156                             "parse_prefix(\"{}\"): expected {:?}, found {:?}", path, exp, res);
1157                 }
1158             )
1159         )
1160
1161         t!("\\\\SERVER\\share\\foo", Some(UNCPrefix(6,5)));
1162         t!("\\\\", None);
1163         t!("\\\\SERVER", None);
1164         t!("\\\\SERVER\\", None);
1165         t!("\\\\SERVER\\\\", None);
1166         t!("\\\\SERVER\\\\foo", None);
1167         t!("\\\\SERVER\\share", Some(UNCPrefix(6,5)));
1168         t!("\\\\SERVER/share/foo", Some(UNCPrefix(6,5)));
1169         t!("\\\\SERVER\\share/foo", Some(UNCPrefix(6,5)));
1170         t!("//SERVER/share/foo", None);
1171         t!("\\\\\\a\\b\\c", None);
1172         t!("\\\\?\\a\\b\\c", Some(VerbatimPrefix(1)));
1173         t!("\\\\?\\a/b/c", Some(VerbatimPrefix(5)));
1174         t!("//?/a/b/c", None);
1175         t!("\\\\.\\a\\b", Some(DeviceNSPrefix(1)));
1176         t!("\\\\.\\a/b", Some(DeviceNSPrefix(3)));
1177         t!("//./a/b", None);
1178         t!("\\\\?\\UNC\\server\\share\\foo", Some(VerbatimUNCPrefix(6,5)));
1179         t!("\\\\?\\UNC\\\\share\\foo", Some(VerbatimUNCPrefix(0,5)));
1180         t!("\\\\?\\UNC\\", Some(VerbatimUNCPrefix(0,0)));
1181         t!("\\\\?\\UNC\\server/share/foo", Some(VerbatimUNCPrefix(16,0)));
1182         t!("\\\\?\\UNC\\server", Some(VerbatimUNCPrefix(6,0)));
1183         t!("\\\\?\\UNC\\server\\", Some(VerbatimUNCPrefix(6,0)));
1184         t!("\\\\?\\UNC/server/share", Some(VerbatimPrefix(16)));
1185         t!("\\\\?\\UNC", Some(VerbatimPrefix(3)));
1186         t!("\\\\?\\C:\\a\\b.txt", Some(VerbatimDiskPrefix));
1187         t!("\\\\?\\z:\\", Some(VerbatimDiskPrefix));
1188         t!("\\\\?\\C:", Some(VerbatimPrefix(2)));
1189         t!("\\\\?\\C:a.txt", Some(VerbatimPrefix(7)));
1190         t!("\\\\?\\C:a\\b.txt", Some(VerbatimPrefix(3)));
1191         t!("\\\\?\\C:/a", Some(VerbatimPrefix(4)));
1192         t!("C:\\foo", Some(DiskPrefix));
1193         t!("z:/foo", Some(DiskPrefix));
1194         t!("d:", Some(DiskPrefix));
1195         t!("ab:", None);
1196         t!("ü:\\foo", None);
1197         t!("3:\\foo", None);
1198         t!(" :\\foo", None);
1199         t!("::\\foo", None);
1200         t!("\\\\?\\C:", Some(VerbatimPrefix(2)));
1201         t!("\\\\?\\z:\\", Some(VerbatimDiskPrefix));
1202         t!("\\\\?\\ab:\\", Some(VerbatimPrefix(3)));
1203         t!("\\\\?\\C:\\a", Some(VerbatimDiskPrefix));
1204         t!("\\\\?\\C:/a", Some(VerbatimPrefix(4)));
1205         t!("\\\\?\\C:\\a/b", Some(VerbatimDiskPrefix));
1206     }
1207
1208     #[test]
1209     fn test_paths() {
1210         let empty: &[u8] = [];
1211         t!(v: Path::new(empty), b!("."));
1212         t!(v: Path::new(b!("\\")), b!("\\"));
1213         t!(v: Path::new(b!("a\\b\\c")), b!("a\\b\\c"));
1214
1215         t!(s: Path::new(""), ".");
1216         t!(s: Path::new("\\"), "\\");
1217         t!(s: Path::new("hi"), "hi");
1218         t!(s: Path::new("hi\\"), "hi");
1219         t!(s: Path::new("\\lib"), "\\lib");
1220         t!(s: Path::new("\\lib\\"), "\\lib");
1221         t!(s: Path::new("hi\\there"), "hi\\there");
1222         t!(s: Path::new("hi\\there.txt"), "hi\\there.txt");
1223         t!(s: Path::new("/"), "\\");
1224         t!(s: Path::new("hi/"), "hi");
1225         t!(s: Path::new("/lib"), "\\lib");
1226         t!(s: Path::new("/lib/"), "\\lib");
1227         t!(s: Path::new("hi/there"), "hi\\there");
1228
1229         t!(s: Path::new("hi\\there\\"), "hi\\there");
1230         t!(s: Path::new("hi\\..\\there"), "there");
1231         t!(s: Path::new("hi/../there"), "there");
1232         t!(s: Path::new("..\\hi\\there"), "..\\hi\\there");
1233         t!(s: Path::new("\\..\\hi\\there"), "\\hi\\there");
1234         t!(s: Path::new("/../hi/there"), "\\hi\\there");
1235         t!(s: Path::new("foo\\.."), ".");
1236         t!(s: Path::new("\\foo\\.."), "\\");
1237         t!(s: Path::new("\\foo\\..\\.."), "\\");
1238         t!(s: Path::new("\\foo\\..\\..\\bar"), "\\bar");
1239         t!(s: Path::new("\\.\\hi\\.\\there\\."), "\\hi\\there");
1240         t!(s: Path::new("\\.\\hi\\.\\there\\.\\.."), "\\hi");
1241         t!(s: Path::new("foo\\..\\.."), "..");
1242         t!(s: Path::new("foo\\..\\..\\.."), "..\\..");
1243         t!(s: Path::new("foo\\..\\..\\bar"), "..\\bar");
1244
1245         assert_eq!(Path::new(b!("foo\\bar")).into_vec().as_slice(), b!("foo\\bar"));
1246         assert_eq!(Path::new(b!("\\foo\\..\\..\\bar")).into_vec().as_slice(), b!("\\bar"));
1247
1248         t!(s: Path::new("\\\\a"), "\\a");
1249         t!(s: Path::new("\\\\a\\"), "\\a");
1250         t!(s: Path::new("\\\\a\\b"), "\\\\a\\b");
1251         t!(s: Path::new("\\\\a\\b\\"), "\\\\a\\b");
1252         t!(s: Path::new("\\\\a\\b/"), "\\\\a\\b");
1253         t!(s: Path::new("\\\\\\b"), "\\b");
1254         t!(s: Path::new("\\\\a\\\\b"), "\\a\\b");
1255         t!(s: Path::new("\\\\a\\b\\c"), "\\\\a\\b\\c");
1256         t!(s: Path::new("\\\\server\\share/path"), "\\\\server\\share\\path");
1257         t!(s: Path::new("\\\\server/share/path"), "\\\\server\\share\\path");
1258         t!(s: Path::new("C:a\\b.txt"), "C:a\\b.txt");
1259         t!(s: Path::new("C:a/b.txt"), "C:a\\b.txt");
1260         t!(s: Path::new("z:\\a\\b.txt"), "Z:\\a\\b.txt");
1261         t!(s: Path::new("z:/a/b.txt"), "Z:\\a\\b.txt");
1262         t!(s: Path::new("ab:/a/b.txt"), "ab:\\a\\b.txt");
1263         t!(s: Path::new("C:\\"), "C:\\");
1264         t!(s: Path::new("C:"), "C:");
1265         t!(s: Path::new("q:"), "Q:");
1266         t!(s: Path::new("C:/"), "C:\\");
1267         t!(s: Path::new("C:\\foo\\.."), "C:\\");
1268         t!(s: Path::new("C:foo\\.."), "C:");
1269         t!(s: Path::new("C:\\a\\"), "C:\\a");
1270         t!(s: Path::new("C:\\a/"), "C:\\a");
1271         t!(s: Path::new("C:\\a\\b\\"), "C:\\a\\b");
1272         t!(s: Path::new("C:\\a\\b/"), "C:\\a\\b");
1273         t!(s: Path::new("C:a\\"), "C:a");
1274         t!(s: Path::new("C:a/"), "C:a");
1275         t!(s: Path::new("C:a\\b\\"), "C:a\\b");
1276         t!(s: Path::new("C:a\\b/"), "C:a\\b");
1277         t!(s: Path::new("\\\\?\\z:\\a\\b.txt"), "\\\\?\\z:\\a\\b.txt");
1278         t!(s: Path::new("\\\\?\\C:/a/b.txt"), "\\\\?\\C:/a/b.txt");
1279         t!(s: Path::new("\\\\?\\C:\\a/b.txt"), "\\\\?\\C:\\a/b.txt");
1280         t!(s: Path::new("\\\\?\\test\\a\\b.txt"), "\\\\?\\test\\a\\b.txt");
1281         t!(s: Path::new("\\\\?\\foo\\bar\\"), "\\\\?\\foo\\bar\\");
1282         t!(s: Path::new("\\\\.\\foo\\bar"), "\\\\.\\foo\\bar");
1283         t!(s: Path::new("\\\\.\\"), "\\\\.\\");
1284         t!(s: Path::new("\\\\?\\UNC\\server\\share\\foo"), "\\\\?\\UNC\\server\\share\\foo");
1285         t!(s: Path::new("\\\\?\\UNC\\server/share"), "\\\\?\\UNC\\server/share\\");
1286         t!(s: Path::new("\\\\?\\UNC\\server"), "\\\\?\\UNC\\server\\");
1287         t!(s: Path::new("\\\\?\\UNC\\"), "\\\\?\\UNC\\\\");
1288         t!(s: Path::new("\\\\?\\UNC"), "\\\\?\\UNC");
1289
1290         // I'm not sure whether \\.\foo/bar should normalize to \\.\foo\bar
1291         // as information is sparse and this isn't really googleable.
1292         // I'm going to err on the side of not normalizing it, as this skips the filesystem
1293         t!(s: Path::new("\\\\.\\foo/bar"), "\\\\.\\foo/bar");
1294         t!(s: Path::new("\\\\.\\foo\\bar"), "\\\\.\\foo\\bar");
1295     }
1296
1297     #[test]
1298     fn test_opt_paths() {
1299         assert!(Path::new_opt(b!("foo\\bar", 0)) == None);
1300         assert!(Path::new_opt(b!("foo\\bar", 0x80)) == None);
1301         t!(v: Path::new_opt(b!("foo\\bar")).unwrap(), b!("foo\\bar"));
1302         assert!(Path::new_opt("foo\\bar\0") == None);
1303         t!(s: Path::new_opt("foo\\bar").unwrap(), "foo\\bar");
1304     }
1305
1306     #[test]
1307     fn test_null_byte() {
1308         use task;
1309         let result = task::try(proc() {
1310             Path::new(b!("foo/bar", 0))
1311         });
1312         assert!(result.is_err());
1313
1314         let result = task::try(proc() {
1315             Path::new("test").set_filename(b!("f", 0, "o"))
1316         });
1317         assert!(result.is_err());
1318
1319         let result = task::try(proc() {
1320             Path::new("test").push(b!("f", 0, "o"));
1321         });
1322         assert!(result.is_err());
1323     }
1324
1325     #[test]
1326     #[should_fail]
1327     fn test_not_utf8_fail() {
1328         Path::new(b!("hello", 0x80, ".txt"));
1329     }
1330
1331     #[test]
1332     fn test_display_str() {
1333         let path = Path::new("foo");
1334         assert_eq!(path.display().to_str(), "foo".to_owned());
1335         let path = Path::new(b!("\\"));
1336         assert_eq!(path.filename_display().to_str(), "".to_owned());
1337
1338         let path = Path::new("foo");
1339         let mo = path.display().as_maybe_owned();
1340         assert_eq!(mo.as_slice(), "foo");
1341         let path = Path::new(b!("\\"));
1342         let mo = path.filename_display().as_maybe_owned();
1343         assert_eq!(mo.as_slice(), "");
1344     }
1345
1346     #[test]
1347     fn test_display() {
1348         macro_rules! t(
1349             ($path:expr, $exp:expr, $expf:expr) => (
1350                 {
1351                     let path = Path::new($path);
1352                     let f = format!("{}", path.display());
1353                     assert_eq!(f.as_slice(), $exp);
1354                     let f = format!("{}", path.filename_display());
1355                     assert_eq!(f.as_slice(), $expf);
1356                 }
1357             )
1358         )
1359
1360         t!("foo", "foo", "foo");
1361         t!("foo\\bar", "foo\\bar", "bar");
1362         t!("\\", "\\", "");
1363     }
1364
1365     #[test]
1366     fn test_components() {
1367         macro_rules! t(
1368             (s: $path:expr, $op:ident, $exp:expr) => (
1369                 {
1370                     let path = $path;
1371                     let path = Path::new(path);
1372                     assert!(path.$op() == Some($exp));
1373                 }
1374             );
1375             (s: $path:expr, $op:ident, $exp:expr, opt) => (
1376                 {
1377                     let path = $path;
1378                     let path = Path::new(path);
1379                     let left = path.$op();
1380                     assert!(left == $exp);
1381                 }
1382             );
1383             (v: $path:expr, $op:ident, $exp:expr) => (
1384                 {
1385                     let path = $path;
1386                     let path = Path::new(path);
1387                     assert!(path.$op() == $exp);
1388                 }
1389             )
1390         )
1391
1392         t!(v: b!("a\\b\\c"), filename, Some(b!("c")));
1393         t!(s: "a\\b\\c", filename_str, "c");
1394         t!(s: "\\a\\b\\c", filename_str, "c");
1395         t!(s: "a", filename_str, "a");
1396         t!(s: "\\a", filename_str, "a");
1397         t!(s: ".", filename_str, None, opt);
1398         t!(s: "\\", filename_str, None, opt);
1399         t!(s: "..", filename_str, None, opt);
1400         t!(s: "..\\..", filename_str, None, opt);
1401         t!(s: "c:\\foo.txt", filename_str, "foo.txt");
1402         t!(s: "C:\\", filename_str, None, opt);
1403         t!(s: "C:", filename_str, None, opt);
1404         t!(s: "\\\\server\\share\\foo.txt", filename_str, "foo.txt");
1405         t!(s: "\\\\server\\share", filename_str, None, opt);
1406         t!(s: "\\\\server", filename_str, "server");
1407         t!(s: "\\\\?\\bar\\foo.txt", filename_str, "foo.txt");
1408         t!(s: "\\\\?\\bar", filename_str, None, opt);
1409         t!(s: "\\\\?\\", filename_str, None, opt);
1410         t!(s: "\\\\?\\UNC\\server\\share\\foo.txt", filename_str, "foo.txt");
1411         t!(s: "\\\\?\\UNC\\server", filename_str, None, opt);
1412         t!(s: "\\\\?\\UNC\\", filename_str, None, opt);
1413         t!(s: "\\\\?\\C:\\foo.txt", filename_str, "foo.txt");
1414         t!(s: "\\\\?\\C:\\", filename_str, None, opt);
1415         t!(s: "\\\\?\\C:", filename_str, None, opt);
1416         t!(s: "\\\\?\\foo/bar", filename_str, None, opt);
1417         t!(s: "\\\\?\\C:/foo", filename_str, None, opt);
1418         t!(s: "\\\\.\\foo\\bar", filename_str, "bar");
1419         t!(s: "\\\\.\\foo", filename_str, None, opt);
1420         t!(s: "\\\\.\\foo/bar", filename_str, None, opt);
1421         t!(s: "\\\\.\\foo\\bar/baz", filename_str, "bar/baz");
1422         t!(s: "\\\\.\\", filename_str, None, opt);
1423         t!(s: "\\\\?\\a\\b\\", filename_str, "b");
1424
1425         t!(v: b!("a\\b\\c"), dirname, b!("a\\b"));
1426         t!(s: "a\\b\\c", dirname_str, "a\\b");
1427         t!(s: "\\a\\b\\c", dirname_str, "\\a\\b");
1428         t!(s: "a", dirname_str, ".");
1429         t!(s: "\\a", dirname_str, "\\");
1430         t!(s: ".", dirname_str, ".");
1431         t!(s: "\\", dirname_str, "\\");
1432         t!(s: "..", dirname_str, "..");
1433         t!(s: "..\\..", dirname_str, "..\\..");
1434         t!(s: "c:\\foo.txt", dirname_str, "C:\\");
1435         t!(s: "C:\\", dirname_str, "C:\\");
1436         t!(s: "C:", dirname_str, "C:");
1437         t!(s: "C:foo.txt", dirname_str, "C:");
1438         t!(s: "\\\\server\\share\\foo.txt", dirname_str, "\\\\server\\share");
1439         t!(s: "\\\\server\\share", dirname_str, "\\\\server\\share");
1440         t!(s: "\\\\server", dirname_str, "\\");
1441         t!(s: "\\\\?\\bar\\foo.txt", dirname_str, "\\\\?\\bar");
1442         t!(s: "\\\\?\\bar", dirname_str, "\\\\?\\bar");
1443         t!(s: "\\\\?\\", dirname_str, "\\\\?\\");
1444         t!(s: "\\\\?\\UNC\\server\\share\\foo.txt", dirname_str, "\\\\?\\UNC\\server\\share");
1445         t!(s: "\\\\?\\UNC\\server", dirname_str, "\\\\?\\UNC\\server\\");
1446         t!(s: "\\\\?\\UNC\\", dirname_str, "\\\\?\\UNC\\\\");
1447         t!(s: "\\\\?\\C:\\foo.txt", dirname_str, "\\\\?\\C:\\");
1448         t!(s: "\\\\?\\C:\\", dirname_str, "\\\\?\\C:\\");
1449         t!(s: "\\\\?\\C:", dirname_str, "\\\\?\\C:");
1450         t!(s: "\\\\?\\C:/foo/bar", dirname_str, "\\\\?\\C:/foo/bar");
1451         t!(s: "\\\\?\\foo/bar", dirname_str, "\\\\?\\foo/bar");
1452         t!(s: "\\\\.\\foo\\bar", dirname_str, "\\\\.\\foo");
1453         t!(s: "\\\\.\\foo", dirname_str, "\\\\.\\foo");
1454         t!(s: "\\\\?\\a\\b\\", dirname_str, "\\\\?\\a");
1455
1456         t!(v: b!("hi\\there.txt"), filestem, Some(b!("there")));
1457         t!(s: "hi\\there.txt", filestem_str, "there");
1458         t!(s: "hi\\there", filestem_str, "there");
1459         t!(s: "there.txt", filestem_str, "there");
1460         t!(s: "there", filestem_str, "there");
1461         t!(s: ".", filestem_str, None, opt);
1462         t!(s: "\\", filestem_str, None, opt);
1463         t!(s: "foo\\.bar", filestem_str, ".bar");
1464         t!(s: ".bar", filestem_str, ".bar");
1465         t!(s: "..bar", filestem_str, ".");
1466         t!(s: "hi\\there..txt", filestem_str, "there.");
1467         t!(s: "..", filestem_str, None, opt);
1468         t!(s: "..\\..", filestem_str, None, opt);
1469         // filestem is based on filename, so we don't need the full set of prefix tests
1470
1471         t!(v: b!("hi\\there.txt"), extension, Some(b!("txt")));
1472         t!(v: b!("hi\\there"), extension, None);
1473         t!(s: "hi\\there.txt", extension_str, Some("txt"), opt);
1474         t!(s: "hi\\there", extension_str, None, opt);
1475         t!(s: "there.txt", extension_str, Some("txt"), opt);
1476         t!(s: "there", extension_str, None, opt);
1477         t!(s: ".", extension_str, None, opt);
1478         t!(s: "\\", extension_str, None, opt);
1479         t!(s: "foo\\.bar", extension_str, None, opt);
1480         t!(s: ".bar", extension_str, None, opt);
1481         t!(s: "..bar", extension_str, Some("bar"), opt);
1482         t!(s: "hi\\there..txt", extension_str, Some("txt"), opt);
1483         t!(s: "..", extension_str, None, opt);
1484         t!(s: "..\\..", extension_str, None, opt);
1485         // extension is based on filename, so we don't need the full set of prefix tests
1486     }
1487
1488     #[test]
1489     fn test_push() {
1490         macro_rules! t(
1491             (s: $path:expr, $join:expr) => (
1492                 {
1493                     let path = $path;
1494                     let join = $join;
1495                     let mut p1 = Path::new(path);
1496                     let p2 = p1.clone();
1497                     p1.push(join);
1498                     assert!(p1 == p2.join(join));
1499                 }
1500             )
1501         )
1502
1503         t!(s: "a\\b\\c", "..");
1504         t!(s: "\\a\\b\\c", "d");
1505         t!(s: "a\\b", "c\\d");
1506         t!(s: "a\\b", "\\c\\d");
1507         // this is just a sanity-check test. push and join share an implementation,
1508         // so there's no need for the full set of prefix tests
1509
1510         // we do want to check one odd case though to ensure the prefix is re-parsed
1511         let mut p = Path::new("\\\\?\\C:");
1512         assert!(prefix(&p) == Some(VerbatimPrefix(2)));
1513         p.push("foo");
1514         assert!(prefix(&p) == Some(VerbatimDiskPrefix));
1515         assert_eq!(p.as_str(), Some("\\\\?\\C:\\foo"));
1516
1517         // and another with verbatim non-normalized paths
1518         let mut p = Path::new("\\\\?\\C:\\a\\");
1519         p.push("foo");
1520         assert_eq!(p.as_str(), Some("\\\\?\\C:\\a\\foo"));
1521     }
1522
1523     #[test]
1524     fn test_push_path() {
1525         macro_rules! t(
1526             (s: $path:expr, $push:expr, $exp:expr) => (
1527                 {
1528                     let mut p = Path::new($path);
1529                     let push = Path::new($push);
1530                     p.push(&push);
1531                     assert_eq!(p.as_str(), Some($exp));
1532                 }
1533             )
1534         )
1535
1536         t!(s: "a\\b\\c", "d", "a\\b\\c\\d");
1537         t!(s: "\\a\\b\\c", "d", "\\a\\b\\c\\d");
1538         t!(s: "a\\b", "c\\d", "a\\b\\c\\d");
1539         t!(s: "a\\b", "\\c\\d", "\\c\\d");
1540         t!(s: "a\\b", ".", "a\\b");
1541         t!(s: "a\\b", "..\\c", "a\\c");
1542         t!(s: "a\\b", "C:a.txt", "C:a.txt");
1543         t!(s: "a\\b", "..\\..\\..\\c", "..\\c");
1544         t!(s: "a\\b", "C:\\a.txt", "C:\\a.txt");
1545         t!(s: "C:\\a", "C:\\b.txt", "C:\\b.txt");
1546         t!(s: "C:\\a\\b\\c", "C:d", "C:\\a\\b\\c\\d");
1547         t!(s: "C:a\\b\\c", "C:d", "C:a\\b\\c\\d");
1548         t!(s: "C:a\\b", "..\\..\\..\\c", "C:..\\c");
1549         t!(s: "C:\\a\\b", "..\\..\\..\\c", "C:\\c");
1550         t!(s: "C:", r"a\b\c", r"C:a\b\c");
1551         t!(s: "C:", r"..\a", r"C:..\a");
1552         t!(s: "\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
1553         t!(s: "\\\\server\\share\\foo", "..\\..\\bar", "\\\\server\\share\\bar");
1554         t!(s: "\\\\server\\share\\foo", "C:baz", "C:baz");
1555         t!(s: "\\\\?\\C:\\a\\b", "C:c\\d", "\\\\?\\C:\\a\\b\\c\\d");
1556         t!(s: "\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
1557         t!(s: "\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
1558         t!(s: "\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
1559         t!(s: "\\\\?\\C:\\a\\b", "..\\..\\..\\c", "\\\\?\\C:\\a\\b\\..\\..\\..\\c");
1560         t!(s: "\\\\?\\foo\\bar", "..\\..\\c", "\\\\?\\foo\\bar\\..\\..\\c");
1561         t!(s: "\\\\?\\", "foo", "\\\\?\\\\foo");
1562         t!(s: "\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
1563         t!(s: "\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
1564         t!(s: "\\\\?\\UNC\\server\\share", "C:a", "C:a");
1565         t!(s: "\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\\\foo");
1566         t!(s: "C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
1567         t!(s: "\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
1568         t!(s: "\\\\.\\foo\\bar", "C:a", "C:a");
1569         // again, not sure about the following, but I'm assuming \\.\ should be verbatim
1570         t!(s: "\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
1571
1572         t!(s: "\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
1573     }
1574
1575     #[test]
1576     fn test_push_many() {
1577         macro_rules! t(
1578             (s: $path:expr, $push:expr, $exp:expr) => (
1579                 {
1580                     let mut p = Path::new($path);
1581                     p.push_many($push);
1582                     assert_eq!(p.as_str(), Some($exp));
1583                 }
1584             );
1585             (v: $path:expr, $push:expr, $exp:expr) => (
1586                 {
1587                     let mut p = Path::new($path);
1588                     p.push_many($push);
1589                     assert_eq!(p.as_vec(), $exp);
1590                 }
1591             )
1592         )
1593
1594         t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
1595         t!(s: "a\\b\\c", ["d", "\\e"], "\\e");
1596         t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
1597         t!(s: "a\\b\\c", ["d".to_owned(), "e".to_owned()], "a\\b\\c\\d\\e");
1598         t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e"));
1599         t!(v: b!("a\\b\\c"), [b!("d"), b!("\\e"), b!("f")], b!("\\e\\f"));
1600         t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))],
1601            b!("a\\b\\c\\d\\e"));
1602     }
1603
1604     #[test]
1605     fn test_pop() {
1606         macro_rules! t(
1607             (s: $path:expr, $left:expr, $right:expr) => (
1608                 {
1609                     let pstr = $path;
1610                     let mut p = Path::new(pstr);
1611                     let result = p.pop();
1612                     let left = $left;
1613                     assert!(p.as_str() == Some(left),
1614                         "`{}`.pop() failed; expected remainder `{}`, found `{}`",
1615                         pstr, left, p.as_str().unwrap());
1616                     assert!(result == $right);
1617                 }
1618             );
1619             (v: [$($path:expr),+], [$($left:expr),+], $right:expr) => (
1620                 {
1621                     let mut p = Path::new(b!($($path),+));
1622                     let result = p.pop();
1623                     assert_eq!(p.as_vec(), b!($($left),+));
1624                     assert!(result == $right);
1625                 }
1626             )
1627         )
1628
1629         t!(s: "a\\b\\c", "a\\b", true);
1630         t!(s: "a", ".", true);
1631         t!(s: ".", ".", false);
1632         t!(s: "\\a", "\\", true);
1633         t!(s: "\\", "\\", false);
1634         t!(v: ["a\\b\\c"], ["a\\b"], true);
1635         t!(v: ["a"], ["."], true);
1636         t!(v: ["."], ["."], false);
1637         t!(v: ["\\a"], ["\\"], true);
1638         t!(v: ["\\"], ["\\"], false);
1639
1640         t!(s: "C:\\a\\b", "C:\\a", true);
1641         t!(s: "C:\\a", "C:\\", true);
1642         t!(s: "C:\\", "C:\\", 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: "\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
1647         t!(s: "\\\\server\\share\\a", "\\\\server\\share", true);
1648         t!(s: "\\\\server\\share", "\\\\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         t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
1653         t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\", true);
1654         t!(s: "\\\\?\\C:\\", "\\\\?\\C:\\", false);
1655         t!(s: "\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
1656         t!(s: "\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share", true);
1657         t!(s: "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
1658         t!(s: "\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
1659         t!(s: "\\\\.\\a\\b", "\\\\.\\a", true);
1660         t!(s: "\\\\.\\a", "\\\\.\\a", false);
1661
1662         t!(s: "\\\\?\\a\\b\\", "\\\\?\\a", true);
1663     }
1664
1665     #[test]
1666     fn test_root_path() {
1667         assert!(Path::new("a\\b\\c").root_path() == None);
1668         assert!(Path::new("\\a\\b\\c").root_path() == Some(Path::new("\\")));
1669         assert!(Path::new("C:a").root_path() == Some(Path::new("C:")));
1670         assert!(Path::new("C:\\a").root_path() == Some(Path::new("C:\\")));
1671         assert!(Path::new("\\\\a\\b\\c").root_path() == Some(Path::new("\\\\a\\b")));
1672         assert!(Path::new("\\\\?\\a\\b").root_path() == Some(Path::new("\\\\?\\a")));
1673         assert!(Path::new("\\\\?\\C:\\a").root_path() == Some(Path::new("\\\\?\\C:\\")));
1674         assert!(Path::new("\\\\?\\UNC\\a\\b\\c").root_path() ==
1675                 Some(Path::new("\\\\?\\UNC\\a\\b")));
1676         assert!(Path::new("\\\\.\\a\\b").root_path() == Some(Path::new("\\\\.\\a")));
1677     }
1678
1679     #[test]
1680     fn test_join() {
1681         t!(s: Path::new("a\\b\\c").join(".."), "a\\b");
1682         t!(s: Path::new("\\a\\b\\c").join("d"), "\\a\\b\\c\\d");
1683         t!(s: Path::new("a\\b").join("c\\d"), "a\\b\\c\\d");
1684         t!(s: Path::new("a\\b").join("\\c\\d"), "\\c\\d");
1685         t!(s: Path::new(".").join("a\\b"), "a\\b");
1686         t!(s: Path::new("\\").join("a\\b"), "\\a\\b");
1687         t!(v: Path::new(b!("a\\b\\c")).join(b!("..")), b!("a\\b"));
1688         t!(v: Path::new(b!("\\a\\b\\c")).join(b!("d")), b!("\\a\\b\\c\\d"));
1689         // full join testing is covered under test_push_path, so no need for
1690         // the full set of prefix tests
1691     }
1692
1693     #[test]
1694     fn test_join_path() {
1695         macro_rules! t(
1696             (s: $path:expr, $join:expr, $exp:expr) => (
1697                 {
1698                     let path = Path::new($path);
1699                     let join = Path::new($join);
1700                     let res = path.join(&join);
1701                     assert_eq!(res.as_str(), Some($exp));
1702                 }
1703             )
1704         )
1705
1706         t!(s: "a\\b\\c", "..", "a\\b");
1707         t!(s: "\\a\\b\\c", "d", "\\a\\b\\c\\d");
1708         t!(s: "a\\b", "c\\d", "a\\b\\c\\d");
1709         t!(s: "a\\b", "\\c\\d", "\\c\\d");
1710         t!(s: ".", "a\\b", "a\\b");
1711         t!(s: "\\", "a\\b", "\\a\\b");
1712         // join is implemented using push, so there's no need for
1713         // the full set of prefix tests
1714     }
1715
1716     #[test]
1717     fn test_join_many() {
1718         macro_rules! t(
1719             (s: $path:expr, $join:expr, $exp:expr) => (
1720                 {
1721                     let path = Path::new($path);
1722                     let res = path.join_many($join);
1723                     assert_eq!(res.as_str(), Some($exp));
1724                 }
1725             );
1726             (v: $path:expr, $join:expr, $exp:expr) => (
1727                 {
1728                     let path = Path::new($path);
1729                     let res = path.join_many($join);
1730                     assert_eq!(res.as_vec(), $exp);
1731                 }
1732             )
1733         )
1734
1735         t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
1736         t!(s: "a\\b\\c", ["..", "d"], "a\\b\\d");
1737         t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
1738         t!(s: "a\\b\\c", ["d".to_owned(), "e".to_owned()], "a\\b\\c\\d\\e");
1739         t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e"));
1740         t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))],
1741            b!("a\\b\\c\\d\\e"));
1742     }
1743
1744     #[test]
1745     fn test_with_helpers() {
1746         macro_rules! t(
1747             (s: $path:expr, $op:ident, $arg:expr, $res:expr) => (
1748                 {
1749                     let pstr = $path;
1750                     let path = Path::new(pstr);
1751                     let arg = $arg;
1752                     let res = path.$op(arg);
1753                     let exp = $res;
1754                     assert!(res.as_str() == Some(exp),
1755                             "`{}`.{}(\"{}\"): Expected `{}`, found `{}`",
1756                             pstr, stringify!($op), arg, exp, res.as_str().unwrap());
1757                 }
1758             )
1759         )
1760
1761         t!(s: "a\\b\\c", with_filename, "d", "a\\b\\d");
1762         t!(s: ".", with_filename, "foo", "foo");
1763         t!(s: "\\a\\b\\c", with_filename, "d", "\\a\\b\\d");
1764         t!(s: "\\", with_filename, "foo", "\\foo");
1765         t!(s: "\\a", with_filename, "foo", "\\foo");
1766         t!(s: "foo", with_filename, "bar", "bar");
1767         t!(s: "\\", with_filename, "foo\\", "\\foo");
1768         t!(s: "\\a", with_filename, "foo\\", "\\foo");
1769         t!(s: "a\\b\\c", with_filename, "", "a\\b");
1770         t!(s: "a\\b\\c", with_filename, ".", "a\\b");
1771         t!(s: "a\\b\\c", with_filename, "..", "a");
1772         t!(s: "\\a", with_filename, "", "\\");
1773         t!(s: "foo", with_filename, "", ".");
1774         t!(s: "a\\b\\c", with_filename, "d\\e", "a\\b\\d\\e");
1775         t!(s: "a\\b\\c", with_filename, "\\d", "a\\b\\d");
1776         t!(s: "..", with_filename, "foo", "..\\foo");
1777         t!(s: "..\\..", with_filename, "foo", "..\\..\\foo");
1778         t!(s: "..", with_filename, "", "..");
1779         t!(s: "..\\..", with_filename, "", "..\\..");
1780         t!(s: "C:\\foo\\bar", with_filename, "baz", "C:\\foo\\baz");
1781         t!(s: "C:\\foo", with_filename, "bar", "C:\\bar");
1782         t!(s: "C:\\", with_filename, "foo", "C:\\foo");
1783         t!(s: "C:foo\\bar", with_filename, "baz", "C:foo\\baz");
1784         t!(s: "C:foo", with_filename, "bar", "C:bar");
1785         t!(s: "C:", with_filename, "foo", "C:foo");
1786         t!(s: "C:\\foo", with_filename, "", "C:\\");
1787         t!(s: "C:foo", with_filename, "", "C:");
1788         t!(s: "C:\\foo\\bar", with_filename, "..", "C:\\");
1789         t!(s: "C:\\foo", with_filename, "..", "C:\\");
1790         t!(s: "C:\\", with_filename, "..", "C:\\");
1791         t!(s: "C:foo\\bar", with_filename, "..", "C:");
1792         t!(s: "C:foo", with_filename, "..", "C:..");
1793         t!(s: "C:", with_filename, "..", "C:..");
1794         t!(s: "\\\\server\\share\\foo", with_filename, "bar", "\\\\server\\share\\bar");
1795         t!(s: "\\\\server\\share", with_filename, "foo", "\\\\server\\share\\foo");
1796         t!(s: "\\\\server\\share\\foo", with_filename, "", "\\\\server\\share");
1797         t!(s: "\\\\server\\share", with_filename, "", "\\\\server\\share");
1798         t!(s: "\\\\server\\share\\foo", with_filename, "..", "\\\\server\\share");
1799         t!(s: "\\\\server\\share", with_filename, "..", "\\\\server\\share");
1800         t!(s: "\\\\?\\C:\\foo\\bar", with_filename, "baz", "\\\\?\\C:\\foo\\baz");
1801         t!(s: "\\\\?\\C:\\foo", with_filename, "bar", "\\\\?\\C:\\bar");
1802         t!(s: "\\\\?\\C:\\", with_filename, "foo", "\\\\?\\C:\\foo");
1803         t!(s: "\\\\?\\C:\\foo", with_filename, "..", "\\\\?\\C:\\..");
1804         t!(s: "\\\\?\\foo\\bar", with_filename, "baz", "\\\\?\\foo\\baz");
1805         t!(s: "\\\\?\\foo", with_filename, "bar", "\\\\?\\foo\\bar");
1806         t!(s: "\\\\?\\", with_filename, "foo", "\\\\?\\\\foo");
1807         t!(s: "\\\\?\\foo\\bar", with_filename, "..", "\\\\?\\foo\\..");
1808         t!(s: "\\\\.\\foo\\bar", with_filename, "baz", "\\\\.\\foo\\baz");
1809         t!(s: "\\\\.\\foo", with_filename, "bar", "\\\\.\\foo\\bar");
1810         t!(s: "\\\\.\\foo\\bar", with_filename, "..", "\\\\.\\foo\\..");
1811
1812         t!(s: "hi\\there.txt", with_extension, "exe", "hi\\there.exe");
1813         t!(s: "hi\\there.txt", with_extension, "", "hi\\there");
1814         t!(s: "hi\\there.txt", with_extension, ".", "hi\\there..");
1815         t!(s: "hi\\there.txt", with_extension, "..", "hi\\there...");
1816         t!(s: "hi\\there", with_extension, "txt", "hi\\there.txt");
1817         t!(s: "hi\\there", with_extension, ".", "hi\\there..");
1818         t!(s: "hi\\there", with_extension, "..", "hi\\there...");
1819         t!(s: "hi\\there.", with_extension, "txt", "hi\\there.txt");
1820         t!(s: "hi\\.foo", with_extension, "txt", "hi\\.foo.txt");
1821         t!(s: "hi\\there.txt", with_extension, ".foo", "hi\\there..foo");
1822         t!(s: "\\", with_extension, "txt", "\\");
1823         t!(s: "\\", with_extension, ".", "\\");
1824         t!(s: "\\", with_extension, "..", "\\");
1825         t!(s: ".", with_extension, "txt", ".");
1826         // extension setter calls filename setter internally, no need for extended tests
1827     }
1828
1829     #[test]
1830     fn test_setters() {
1831         macro_rules! t(
1832             (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
1833                 {
1834                     let path = $path;
1835                     let arg = $arg;
1836                     let mut p1 = Path::new(path);
1837                     p1.$set(arg);
1838                     let p2 = Path::new(path);
1839                     assert!(p1 == p2.$with(arg));
1840                 }
1841             );
1842             (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
1843                 {
1844                     let path = $path;
1845                     let arg = $arg;
1846                     let mut p1 = Path::new(path);
1847                     p1.$set(arg);
1848                     let p2 = Path::new(path);
1849                     assert!(p1 == p2.$with(arg));
1850                 }
1851             )
1852         )
1853
1854         t!(v: b!("a\\b\\c"), set_filename, with_filename, b!("d"));
1855         t!(v: b!("\\"), set_filename, with_filename, b!("foo"));
1856         t!(s: "a\\b\\c", set_filename, with_filename, "d");
1857         t!(s: "\\", set_filename, with_filename, "foo");
1858         t!(s: ".", set_filename, with_filename, "foo");
1859         t!(s: "a\\b", set_filename, with_filename, "");
1860         t!(s: "a", set_filename, with_filename, "");
1861
1862         t!(v: b!("hi\\there.txt"), set_extension, with_extension, b!("exe"));
1863         t!(s: "hi\\there.txt", set_extension, with_extension, "exe");
1864         t!(s: "hi\\there.", set_extension, with_extension, "txt");
1865         t!(s: "hi\\there", set_extension, with_extension, "txt");
1866         t!(s: "hi\\there.txt", set_extension, with_extension, "");
1867         t!(s: "hi\\there", set_extension, with_extension, "");
1868         t!(s: ".", set_extension, with_extension, "txt");
1869
1870         // with_ helpers use the setter internally, so the tests for the with_ helpers
1871         // will suffice. No need for the full set of prefix tests.
1872     }
1873
1874     #[test]
1875     fn test_getters() {
1876         macro_rules! t(
1877             (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
1878                 {
1879                     let path = $path;
1880                     let filename = $filename;
1881                     assert!(path.filename_str() == filename,
1882                             "`{}`.filename_str(): Expected `{:?}`, found `{:?}`",
1883                             path.as_str().unwrap(), filename, path.filename_str());
1884                     let dirname = $dirname;
1885                     assert!(path.dirname_str() == dirname,
1886                             "`{}`.dirname_str(): Expected `{:?}`, found `{:?}`",
1887                             path.as_str().unwrap(), dirname, path.dirname_str());
1888                     let filestem = $filestem;
1889                     assert!(path.filestem_str() == filestem,
1890                             "`{}`.filestem_str(): Expected `{:?}`, found `{:?}`",
1891                             path.as_str().unwrap(), filestem, path.filestem_str());
1892                     let ext = $ext;
1893                     assert!(path.extension_str() == ext,
1894                             "`{}`.extension_str(): Expected `{:?}`, found `{:?}`",
1895                             path.as_str().unwrap(), ext, path.extension_str());
1896                 }
1897             );
1898             (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
1899                 {
1900                     let path = $path;
1901                     assert!(path.filename() == $filename);
1902                     assert!(path.dirname() == $dirname);
1903                     assert!(path.filestem() == $filestem);
1904                     assert!(path.extension() == $ext);
1905                 }
1906             )
1907         )
1908
1909         t!(v: Path::new(b!("a\\b\\c")), Some(b!("c")), b!("a\\b"), Some(b!("c")), None);
1910         t!(s: Path::new("a\\b\\c"), Some("c"), Some("a\\b"), Some("c"), None);
1911         t!(s: Path::new("."), None, Some("."), None, None);
1912         t!(s: Path::new("\\"), None, Some("\\"), None, None);
1913         t!(s: Path::new(".."), None, Some(".."), None, None);
1914         t!(s: Path::new("..\\.."), None, Some("..\\.."), None, None);
1915         t!(s: Path::new("hi\\there.txt"), Some("there.txt"), Some("hi"),
1916               Some("there"), Some("txt"));
1917         t!(s: Path::new("hi\\there"), Some("there"), Some("hi"), Some("there"), None);
1918         t!(s: Path::new("hi\\there."), Some("there."), Some("hi"),
1919               Some("there"), Some(""));
1920         t!(s: Path::new("hi\\.there"), Some(".there"), Some("hi"), Some(".there"), None);
1921         t!(s: Path::new("hi\\..there"), Some("..there"), Some("hi"),
1922               Some("."), Some("there"));
1923
1924         // these are already tested in test_components, so no need for extended tests
1925     }
1926
1927     #[test]
1928     fn test_dir_path() {
1929         t!(s: Path::new("hi\\there").dir_path(), "hi");
1930         t!(s: Path::new("hi").dir_path(), ".");
1931         t!(s: Path::new("\\hi").dir_path(), "\\");
1932         t!(s: Path::new("\\").dir_path(), "\\");
1933         t!(s: Path::new("..").dir_path(), "..");
1934         t!(s: Path::new("..\\..").dir_path(), "..\\..");
1935
1936         // dir_path is just dirname interpreted as a path.
1937         // No need for extended tests
1938     }
1939
1940     #[test]
1941     fn test_is_absolute() {
1942         macro_rules! t(
1943             ($path:expr, $abs:expr, $vol:expr, $cwd:expr, $rel:expr) => (
1944                 {
1945                     let path = Path::new($path);
1946                     let (abs, vol, cwd, rel) = ($abs, $vol, $cwd, $rel);
1947                     let b = path.is_absolute();
1948                     assert!(b == abs, "Path '{}'.is_absolute(): expected {:?}, found {:?}",
1949                             path.as_str().unwrap(), abs, b);
1950                     let b = is_vol_relative(&path);
1951                     assert!(b == vol, "is_vol_relative('{}'): expected {:?}, found {:?}",
1952                             path.as_str().unwrap(), vol, b);
1953                     let b = is_cwd_relative(&path);
1954                     assert!(b == cwd, "is_cwd_relative('{}'): expected {:?}, found {:?}",
1955                             path.as_str().unwrap(), cwd, b);
1956                     let b = path.is_relative();
1957                     assert!(b == rel, "Path '{}'.is_relativf(): expected {:?}, found {:?}",
1958                             path.as_str().unwrap(), rel, b);
1959                 }
1960             )
1961         )
1962         t!("a\\b\\c", false, false, false, true);
1963         t!("\\a\\b\\c", false, true, false, false);
1964         t!("a", false, false, false, true);
1965         t!("\\a", false, true, false, false);
1966         t!(".", false, false, false, true);
1967         t!("\\", false, true, false, false);
1968         t!("..", false, false, false, true);
1969         t!("..\\..", false, false, false, true);
1970         t!("C:a\\b.txt", false, false, true, false);
1971         t!("C:\\a\\b.txt", true, false, false, false);
1972         t!("\\\\server\\share\\a\\b.txt", true, false, false, false);
1973         t!("\\\\?\\a\\b\\c.txt", true, false, false, false);
1974         t!("\\\\?\\C:\\a\\b.txt", true, false, false, false);
1975         t!("\\\\?\\C:a\\b.txt", true, false, false, false); // NB: not equivalent to C:a\b.txt
1976         t!("\\\\?\\UNC\\server\\share\\a\\b.txt", true, false, false, false);
1977         t!("\\\\.\\a\\b", true, false, false, false);
1978     }
1979
1980     #[test]
1981     fn test_is_ancestor_of() {
1982         macro_rules! t(
1983             (s: $path:expr, $dest:expr, $exp:expr) => (
1984                 {
1985                     let path = Path::new($path);
1986                     let dest = Path::new($dest);
1987                     let exp = $exp;
1988                     let res = path.is_ancestor_of(&dest);
1989                     assert!(res == exp,
1990                             "`{}`.is_ancestor_of(`{}`): Expected {:?}, found {:?}",
1991                             path.as_str().unwrap(), dest.as_str().unwrap(), exp, res);
1992                 }
1993             )
1994         )
1995
1996         t!(s: "a\\b\\c", "a\\b\\c\\d", true);
1997         t!(s: "a\\b\\c", "a\\b\\c", true);
1998         t!(s: "a\\b\\c", "a\\b", false);
1999         t!(s: "\\a\\b\\c", "\\a\\b\\c", true);
2000         t!(s: "\\a\\b", "\\a\\b\\c", true);
2001         t!(s: "\\a\\b\\c\\d", "\\a\\b\\c", false);
2002         t!(s: "\\a\\b", "a\\b\\c", false);
2003         t!(s: "a\\b", "\\a\\b\\c", false);
2004         t!(s: "a\\b\\c", "a\\b\\d", false);
2005         t!(s: "..\\a\\b\\c", "a\\b\\c", false);
2006         t!(s: "a\\b\\c", "..\\a\\b\\c", false);
2007         t!(s: "a\\b\\c", "a\\b\\cd", false);
2008         t!(s: "a\\b\\cd", "a\\b\\c", false);
2009         t!(s: "..\\a\\b", "..\\a\\b\\c", true);
2010         t!(s: ".", "a\\b", true);
2011         t!(s: ".", ".", true);
2012         t!(s: "\\", "\\", true);
2013         t!(s: "\\", "\\a\\b", true);
2014         t!(s: "..", "a\\b", true);
2015         t!(s: "..\\..", "a\\b", true);
2016         t!(s: "foo\\bar", "foobar", false);
2017         t!(s: "foobar", "foo\\bar", false);
2018
2019         t!(s: "foo", "C:foo", false);
2020         t!(s: "C:foo", "foo", false);
2021         t!(s: "C:foo", "C:foo\\bar", true);
2022         t!(s: "C:foo\\bar", "C:foo", false);
2023         t!(s: "C:\\foo", "C:\\foo\\bar", true);
2024         t!(s: "C:", "C:", true);
2025         t!(s: "C:", "C:\\", false);
2026         t!(s: "C:\\", "C:", false);
2027         t!(s: "C:\\", "C:\\", true);
2028         t!(s: "C:\\foo\\bar", "C:\\foo", false);
2029         t!(s: "C:foo\\bar", "C:foo", false);
2030         t!(s: "C:\\foo", "\\foo", false);
2031         t!(s: "\\foo", "C:\\foo", false);
2032         t!(s: "\\\\server\\share\\foo", "\\\\server\\share\\foo\\bar", true);
2033         t!(s: "\\\\server\\share", "\\\\server\\share\\foo", true);
2034         t!(s: "\\\\server\\share\\foo", "\\\\server\\share", false);
2035         t!(s: "C:\\foo", "\\\\server\\share\\foo", false);
2036         t!(s: "\\\\server\\share\\foo", "C:\\foo", false);
2037         t!(s: "\\\\?\\foo\\bar", "\\\\?\\foo\\bar\\baz", true);
2038         t!(s: "\\\\?\\foo\\bar\\baz", "\\\\?\\foo\\bar", false);
2039         t!(s: "\\\\?\\foo\\bar", "\\foo\\bar\\baz", false);
2040         t!(s: "\\foo\\bar", "\\\\?\\foo\\bar\\baz", false);
2041         t!(s: "\\\\?\\C:\\foo\\bar", "\\\\?\\C:\\foo\\bar\\baz", true);
2042         t!(s: "\\\\?\\C:\\foo\\bar\\baz", "\\\\?\\C:\\foo\\bar", false);
2043         t!(s: "\\\\?\\C:\\", "\\\\?\\C:\\foo", true);
2044         t!(s: "\\\\?\\C:", "\\\\?\\C:\\", false); // this is a weird one
2045         t!(s: "\\\\?\\C:\\", "\\\\?\\C:", false);
2046         t!(s: "\\\\?\\C:\\a", "\\\\?\\c:\\a\\b", true);
2047         t!(s: "\\\\?\\c:\\a", "\\\\?\\C:\\a\\b", true);
2048         t!(s: "\\\\?\\C:\\a", "\\\\?\\D:\\a\\b", false);
2049         t!(s: "\\\\?\\foo", "\\\\?\\foobar", false);
2050         t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\c", true);
2051         t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\", true);
2052         t!(s: "\\\\?\\a\\b\\", "\\\\?\\a\\b", true);
2053         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", false);
2054         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b\\", false);
2055         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\b\\c\\d", true);
2056         t!(s: "\\\\?\\UNC\\a\\b\\c\\d", "\\\\?\\UNC\\a\\b\\c", false);
2057         t!(s: "\\\\?\\UNC\\a\\b", "\\\\?\\UNC\\a\\b\\c", true);
2058         t!(s: "\\\\.\\foo\\bar", "\\\\.\\foo\\bar\\baz", true);
2059         t!(s: "\\\\.\\foo\\bar\\baz", "\\\\.\\foo\\bar", false);
2060         t!(s: "\\\\.\\foo", "\\\\.\\foo\\bar", true);
2061         t!(s: "\\\\.\\foo", "\\\\.\\foobar", false);
2062
2063         t!(s: "\\a\\b", "\\\\?\\a\\b", false);
2064         t!(s: "\\\\?\\a\\b", "\\a\\b", false);
2065         t!(s: "\\a\\b", "\\\\?\\C:\\a\\b", false);
2066         t!(s: "\\\\?\\C:\\a\\b", "\\a\\b", false);
2067         t!(s: "Z:\\a\\b", "\\\\?\\z:\\a\\b", true);
2068         t!(s: "C:\\a\\b", "\\\\?\\D:\\a\\b", false);
2069         t!(s: "a\\b", "\\\\?\\a\\b", false);
2070         t!(s: "\\\\?\\a\\b", "a\\b", false);
2071         t!(s: "C:\\a\\b", "\\\\?\\C:\\a\\b", true);
2072         t!(s: "\\\\?\\C:\\a\\b", "C:\\a\\b", true);
2073         t!(s: "C:a\\b", "\\\\?\\C:\\a\\b", false);
2074         t!(s: "C:a\\b", "\\\\?\\C:a\\b", false);
2075         t!(s: "\\\\?\\C:\\a\\b", "C:a\\b", false);
2076         t!(s: "\\\\?\\C:a\\b", "C:a\\b", false);
2077         t!(s: "C:\\a\\b", "\\\\?\\C:\\a\\b\\", true);
2078         t!(s: "\\\\?\\C:\\a\\b\\", "C:\\a\\b", true);
2079         t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\b\\c", true);
2080         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\b\\c", true);
2081     }
2082
2083     #[test]
2084     fn test_ends_with_path() {
2085         macro_rules! t(
2086             (s: $path:expr, $child:expr, $exp:expr) => (
2087                 {
2088                     let path = Path::new($path);
2089                     let child = Path::new($child);
2090                     assert_eq!(path.ends_with_path(&child), $exp);
2091                 }
2092             );
2093         )
2094
2095         t!(s: "a\\b\\c", "c", true);
2096         t!(s: "a\\b\\c", "d", false);
2097         t!(s: "foo\\bar\\quux", "bar", false);
2098         t!(s: "foo\\bar\\quux", "barquux", false);
2099         t!(s: "a\\b\\c", "b\\c", true);
2100         t!(s: "a\\b\\c", "a\\b\\c", true);
2101         t!(s: "a\\b\\c", "foo\\a\\b\\c", false);
2102         t!(s: "\\a\\b\\c", "a\\b\\c", true);
2103         t!(s: "\\a\\b\\c", "\\a\\b\\c", false); // child must be relative
2104         t!(s: "\\a\\b\\c", "foo\\a\\b\\c", false);
2105         t!(s: "a\\b\\c", "", false);
2106         t!(s: "", "", true);
2107         t!(s: "\\a\\b\\c", "d\\e\\f", false);
2108         t!(s: "a\\b\\c", "a\\b", false);
2109         t!(s: "a\\b\\c", "b", false);
2110         t!(s: "C:\\a\\b", "b", true);
2111         t!(s: "C:\\a\\b", "C:b", false);
2112         t!(s: "C:\\a\\b", "C:a\\b", false);
2113     }
2114
2115     #[test]
2116     fn test_path_relative_from() {
2117         macro_rules! t(
2118             (s: $path:expr, $other:expr, $exp:expr) => (
2119                 {
2120                     let path = Path::new($path);
2121                     let other = Path::new($other);
2122                     let res = path.path_relative_from(&other);
2123                     let exp = $exp;
2124                     assert!(res.as_ref().and_then(|x| x.as_str()) == exp,
2125                             "`{}`.path_relative_from(`{}`): Expected {:?}, got {:?}",
2126                             path.as_str().unwrap(), other.as_str().unwrap(), exp,
2127                             res.as_ref().and_then(|x| x.as_str()));
2128                 }
2129             )
2130         )
2131
2132         t!(s: "a\\b\\c", "a\\b", Some("c"));
2133         t!(s: "a\\b\\c", "a\\b\\d", Some("..\\c"));
2134         t!(s: "a\\b\\c", "a\\b\\c\\d", Some(".."));
2135         t!(s: "a\\b\\c", "a\\b\\c", Some("."));
2136         t!(s: "a\\b\\c", "a\\b\\c\\d\\e", Some("..\\.."));
2137         t!(s: "a\\b\\c", "a\\d\\e", Some("..\\..\\b\\c"));
2138         t!(s: "a\\b\\c", "d\\e\\f", Some("..\\..\\..\\a\\b\\c"));
2139         t!(s: "a\\b\\c", "\\a\\b\\c", None);
2140         t!(s: "\\a\\b\\c", "a\\b\\c", Some("\\a\\b\\c"));
2141         t!(s: "\\a\\b\\c", "\\a\\b\\c\\d", Some(".."));
2142         t!(s: "\\a\\b\\c", "\\a\\b", Some("c"));
2143         t!(s: "\\a\\b\\c", "\\a\\b\\c\\d\\e", Some("..\\.."));
2144         t!(s: "\\a\\b\\c", "\\a\\d\\e", Some("..\\..\\b\\c"));
2145         t!(s: "\\a\\b\\c", "\\d\\e\\f", Some("..\\..\\..\\a\\b\\c"));
2146         t!(s: "hi\\there.txt", "hi\\there", Some("..\\there.txt"));
2147         t!(s: ".", "a", Some(".."));
2148         t!(s: ".", "a\\b", Some("..\\.."));
2149         t!(s: ".", ".", Some("."));
2150         t!(s: "a", ".", Some("a"));
2151         t!(s: "a\\b", ".", Some("a\\b"));
2152         t!(s: "..", ".", Some(".."));
2153         t!(s: "a\\b\\c", "a\\b\\c", Some("."));
2154         t!(s: "\\a\\b\\c", "\\a\\b\\c", Some("."));
2155         t!(s: "\\", "\\", Some("."));
2156         t!(s: "\\", ".", Some("\\"));
2157         t!(s: "..\\..\\a", "b", Some("..\\..\\..\\a"));
2158         t!(s: "a", "..\\..\\b", None);
2159         t!(s: "..\\..\\a", "..\\..\\b", Some("..\\a"));
2160         t!(s: "..\\..\\a", "..\\..\\a\\b", Some(".."));
2161         t!(s: "..\\..\\a\\b", "..\\..\\a", Some("b"));
2162
2163         t!(s: "C:a\\b\\c", "C:a\\b", Some("c"));
2164         t!(s: "C:a\\b", "C:a\\b\\c", Some(".."));
2165         t!(s: "C:" ,"C:a\\b", Some("..\\.."));
2166         t!(s: "C:a\\b", "C:c\\d", Some("..\\..\\a\\b"));
2167         t!(s: "C:a\\b", "D:c\\d", Some("C:a\\b"));
2168         t!(s: "C:a\\b", "C:..\\c", None);
2169         t!(s: "C:..\\a", "C:b\\c", Some("..\\..\\..\\a"));
2170         t!(s: "C:\\a\\b\\c", "C:\\a\\b", Some("c"));
2171         t!(s: "C:\\a\\b", "C:\\a\\b\\c", Some(".."));
2172         t!(s: "C:\\", "C:\\a\\b", Some("..\\.."));
2173         t!(s: "C:\\a\\b", "C:\\c\\d", Some("..\\..\\a\\b"));
2174         t!(s: "C:\\a\\b", "C:a\\b", Some("C:\\a\\b"));
2175         t!(s: "C:a\\b", "C:\\a\\b", None);
2176         t!(s: "\\a\\b", "C:\\a\\b", None);
2177         t!(s: "\\a\\b", "C:a\\b", None);
2178         t!(s: "a\\b", "C:\\a\\b", None);
2179         t!(s: "a\\b", "C:a\\b", None);
2180
2181         t!(s: "\\\\a\\b\\c", "\\\\a\\b", Some("c"));
2182         t!(s: "\\\\a\\b", "\\\\a\\b\\c", Some(".."));
2183         t!(s: "\\\\a\\b\\c\\e", "\\\\a\\b\\c\\d", Some("..\\e"));
2184         t!(s: "\\\\a\\c\\d", "\\\\a\\b\\d", Some("\\\\a\\c\\d"));
2185         t!(s: "\\\\b\\c\\d", "\\\\a\\c\\d", Some("\\\\b\\c\\d"));
2186         t!(s: "\\\\a\\b\\c", "\\d\\e", Some("\\\\a\\b\\c"));
2187         t!(s: "\\d\\e", "\\\\a\\b\\c", None);
2188         t!(s: "d\\e", "\\\\a\\b\\c", None);
2189         t!(s: "C:\\a\\b\\c", "\\\\a\\b\\c", Some("C:\\a\\b\\c"));
2190         t!(s: "C:\\c", "\\\\a\\b\\c", Some("C:\\c"));
2191
2192         t!(s: "\\\\?\\a\\b", "\\a\\b", Some("\\\\?\\a\\b"));
2193         t!(s: "\\\\?\\a\\b", "a\\b", Some("\\\\?\\a\\b"));
2194         t!(s: "\\\\?\\a\\b", "\\b", Some("\\\\?\\a\\b"));
2195         t!(s: "\\\\?\\a\\b", "b", Some("\\\\?\\a\\b"));
2196         t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\c", Some(".."));
2197         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", Some("c"));
2198         t!(s: "\\\\?\\a\\b", "\\\\?\\c\\d", Some("\\\\?\\a\\b"));
2199         t!(s: "\\\\?\\a", "\\\\?\\b", Some("\\\\?\\a"));
2200
2201         t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", Some("b"));
2202         t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\a\\b", Some(".."));
2203         t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\b", Some("..\\a"));
2204         t!(s: "\\\\?\\C:\\a", "\\\\?\\D:\\a", Some("\\\\?\\C:\\a"));
2205         t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\c:\\a", Some("b"));
2206         t!(s: "\\\\?\\C:\\a\\b", "C:\\a", Some("b"));
2207         t!(s: "\\\\?\\C:\\a", "C:\\a\\b", Some(".."));
2208         t!(s: "C:\\a\\b", "\\\\?\\C:\\a", Some("b"));
2209         t!(s: "C:\\a", "\\\\?\\C:\\a\\b", Some(".."));
2210         t!(s: "\\\\?\\C:\\a", "D:\\a", Some("\\\\?\\C:\\a"));
2211         t!(s: "\\\\?\\c:\\a\\b", "C:\\a", Some("b"));
2212         t!(s: "\\\\?\\C:\\a\\b", "C:a\\b", Some("\\\\?\\C:\\a\\b"));
2213         t!(s: "\\\\?\\C:\\a\\.\\b", "C:\\a", Some("\\\\?\\C:\\a\\.\\b"));
2214         t!(s: "\\\\?\\C:\\a\\b/c", "C:\\a", Some("\\\\?\\C:\\a\\b/c"));
2215         t!(s: "\\\\?\\C:\\a\\..\\b", "C:\\a", Some("\\\\?\\C:\\a\\..\\b"));
2216         t!(s: "C:a\\b", "\\\\?\\C:\\a\\b", None);
2217         t!(s: "\\\\?\\C:\\a\\.\\b", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\.\\b"));
2218         t!(s: "\\\\?\\C:\\a\\b/c", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\b/c"));
2219         t!(s: "\\\\?\\C:\\a\\..\\b", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\..\\b"));
2220         t!(s: "\\\\?\\C:\\a\\b\\", "\\\\?\\C:\\a", Some("b"));
2221         t!(s: "\\\\?\\C:\\.\\b", "\\\\?\\C:\\.", Some("b"));
2222         t!(s: "C:\\b", "\\\\?\\C:\\.", Some("..\\b"));
2223         t!(s: "\\\\?\\a\\.\\b\\c", "\\\\?\\a\\.\\b", Some("c"));
2224         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\.\\d", Some("..\\..\\b\\c"));
2225         t!(s: "\\\\?\\a\\..\\b", "\\\\?\\a\\..", Some("b"));
2226         t!(s: "\\\\?\\a\\b\\..", "\\\\?\\a\\b", Some("\\\\?\\a\\b\\.."));
2227         t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\..\\b", Some("..\\..\\b\\c"));
2228
2229         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\b", Some("c"));
2230         t!(s: "\\\\?\\UNC\\a\\b", "\\\\?\\UNC\\a\\b\\c", Some(".."));
2231         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\c\\d", Some("\\\\?\\UNC\\a\\b\\c"));
2232         t!(s: "\\\\?\\UNC\\b\\c\\d", "\\\\?\\UNC\\a\\c\\d", Some("\\\\?\\UNC\\b\\c\\d"));
2233         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\a\\b\\c", Some("\\\\?\\UNC\\a\\b\\c"));
2234         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\C:\\a\\b\\c", Some("\\\\?\\UNC\\a\\b\\c"));
2235         t!(s: "\\\\?\\UNC\\a\\b\\c/d", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\c/d"));
2236         t!(s: "\\\\?\\UNC\\a\\b\\.", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\."));
2237         t!(s: "\\\\?\\UNC\\a\\b\\..", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\.."));
2238         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\b", Some("c"));
2239         t!(s: "\\\\?\\UNC\\a\\b", "\\\\a\\b\\c", Some(".."));
2240         t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\c\\d", Some("\\\\?\\UNC\\a\\b\\c"));
2241         t!(s: "\\\\?\\UNC\\b\\c\\d", "\\\\a\\c\\d", Some("\\\\?\\UNC\\b\\c\\d"));
2242         t!(s: "\\\\?\\UNC\\a\\b\\.", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\."));
2243         t!(s: "\\\\?\\UNC\\a\\b\\c/d", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\c/d"));
2244         t!(s: "\\\\?\\UNC\\a\\b\\..", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\.."));
2245         t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\b", Some("c"));
2246         t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\c\\d", Some("\\\\a\\b\\c"));
2247     }
2248
2249     #[test]
2250     fn test_str_components() {
2251         macro_rules! t(
2252             (s: $path:expr, $exp:expr) => (
2253                 {
2254                     let path = Path::new($path);
2255                     let comps = path.str_components().map(|x|x.unwrap())
2256                                 .collect::<Vec<&str>>();
2257                     let exp: &[&str] = $exp;
2258                     assert_eq!(comps.as_slice(), exp);
2259                     let comps = path.str_components().rev().map(|x|x.unwrap())
2260                                 .collect::<Vec<&str>>();
2261                     let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&str>>();
2262                     assert_eq!(comps, exp);
2263                 }
2264             );
2265             (v: [$($arg:expr),+], $exp:expr) => (
2266                 {
2267                     let path = Path::new(b!($($arg),+));
2268                     let comps = path.str_components().map(|x|x.unwrap()).collect::<Vec<&str>>();
2269                     let exp: &[&str] = $exp;
2270                     assert_eq!(comps.as_slice(), exp);
2271                     let comps = path.str_components().rev().map(|x|x.unwrap())
2272                                 .collect::<Vec<&str>>();
2273                     let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&str>>();
2274                     assert_eq!(comps, exp);
2275                 }
2276             )
2277         )
2278
2279         t!(v: ["a\\b\\c"], ["a", "b", "c"]);
2280         t!(s: "a\\b\\c", ["a", "b", "c"]);
2281         t!(s: "a\\b\\d", ["a", "b", "d"]);
2282         t!(s: "a\\b\\cd", ["a", "b", "cd"]);
2283         t!(s: "\\a\\b\\c", ["a", "b", "c"]);
2284         t!(s: "a", ["a"]);
2285         t!(s: "\\a", ["a"]);
2286         t!(s: "\\", []);
2287         t!(s: ".", ["."]);
2288         t!(s: "..", [".."]);
2289         t!(s: "..\\..", ["..", ".."]);
2290         t!(s: "..\\..\\foo", ["..", "..", "foo"]);
2291         t!(s: "C:foo\\bar", ["foo", "bar"]);
2292         t!(s: "C:foo", ["foo"]);
2293         t!(s: "C:", []);
2294         t!(s: "C:\\foo\\bar", ["foo", "bar"]);
2295         t!(s: "C:\\foo", ["foo"]);
2296         t!(s: "C:\\", []);
2297         t!(s: "\\\\server\\share\\foo\\bar", ["foo", "bar"]);
2298         t!(s: "\\\\server\\share\\foo", ["foo"]);
2299         t!(s: "\\\\server\\share", []);
2300         t!(s: "\\\\?\\foo\\bar\\baz", ["bar", "baz"]);
2301         t!(s: "\\\\?\\foo\\bar", ["bar"]);
2302         t!(s: "\\\\?\\foo", []);
2303         t!(s: "\\\\?\\", []);
2304         t!(s: "\\\\?\\a\\b", ["b"]);
2305         t!(s: "\\\\?\\a\\b\\", ["b"]);
2306         t!(s: "\\\\?\\foo\\bar\\\\baz", ["bar", "", "baz"]);
2307         t!(s: "\\\\?\\C:\\foo\\bar", ["foo", "bar"]);
2308         t!(s: "\\\\?\\C:\\foo", ["foo"]);
2309         t!(s: "\\\\?\\C:\\", []);
2310         t!(s: "\\\\?\\C:\\foo\\", ["foo"]);
2311         t!(s: "\\\\?\\UNC\\server\\share\\foo\\bar", ["foo", "bar"]);
2312         t!(s: "\\\\?\\UNC\\server\\share\\foo", ["foo"]);
2313         t!(s: "\\\\?\\UNC\\server\\share", []);
2314         t!(s: "\\\\.\\foo\\bar\\baz", ["bar", "baz"]);
2315         t!(s: "\\\\.\\foo\\bar", ["bar"]);
2316         t!(s: "\\\\.\\foo", []);
2317     }
2318
2319     #[test]
2320     fn test_components_iter() {
2321         macro_rules! t(
2322             (s: $path:expr, $exp:expr) => (
2323                 {
2324                     let path = Path::new($path);
2325                     let comps = path.components().collect::<Vec<&[u8]>>();
2326                     let exp: &[&[u8]] = $exp;
2327                     assert_eq!(comps.as_slice(), exp);
2328                     let comps = path.components().rev().collect::<Vec<&[u8]>>();
2329                     let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
2330                     assert_eq!(comps, exp);
2331                 }
2332             )
2333         )
2334
2335         t!(s: "a\\b\\c", [b!("a"), b!("b"), b!("c")]);
2336         t!(s: ".", [b!(".")]);
2337         // since this is really a wrapper around str_components, those tests suffice
2338     }
2339
2340     #[test]
2341     fn test_make_non_verbatim() {
2342         macro_rules! t(
2343             ($path:expr, $exp:expr) => (
2344                 {
2345                     let path = Path::new($path);
2346                     let exp: Option<&str> = $exp;
2347                     let exp = exp.map(|s| Path::new(s));
2348                     assert!(make_non_verbatim(&path) == exp);
2349                 }
2350             )
2351         )
2352
2353         t!(r"\a\b\c", Some(r"\a\b\c"));
2354         t!(r"a\b\c", Some(r"a\b\c"));
2355         t!(r"C:\a\b\c", Some(r"C:\a\b\c"));
2356         t!(r"C:a\b\c", Some(r"C:a\b\c"));
2357         t!(r"\\server\share\foo", Some(r"\\server\share\foo"));
2358         t!(r"\\.\foo", None);
2359         t!(r"\\?\foo", None);
2360         t!(r"\\?\C:", None);
2361         t!(r"\\?\C:foo", None);
2362         t!(r"\\?\C:\", Some(r"C:\"));
2363         t!(r"\\?\C:\foo", Some(r"C:\foo"));
2364         t!(r"\\?\C:\foo\bar\baz", Some(r"C:\foo\bar\baz"));
2365         t!(r"\\?\C:\foo\.\bar\baz", None);
2366         t!(r"\\?\C:\foo\bar\..\baz", None);
2367         t!(r"\\?\C:\foo\bar\..", None);
2368         t!(r"\\?\UNC\server\share\foo", Some(r"\\server\share\foo"));
2369         t!(r"\\?\UNC\server\share", Some(r"\\server\share"));
2370         t!(r"\\?\UNC\server", None);
2371         t!(r"\\?\UNC\server\", None);
2372     }
2373 }