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