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