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