]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / libstd / path.rs
1 // Copyright 2015 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 //! Cross-platform path manipulation.
12 //!
13 //! This module provides two types, `PathBuf` and `Path` (akin to `String` and
14 //! `str`), for working with paths abstractly. These types are thin wrappers
15 //! around `OsString` and `OsStr` respectively, meaning that they work directly
16 //! on strings according to the local platform's path syntax.
17 //!
18 //! ## Simple usage
19 //!
20 //! Path manipulation involves both parsing components from slices and building
21 //! new owned paths.
22 //!
23 //! To parse a path, you can create a `Path` slice from a `str`
24 //! slice and start asking questions:
25 //!
26 //! ```rust
27 //! use std::path::Path;
28 //!
29 //! let path = Path::new("/tmp/foo/bar.txt");
30 //! let file = path.file_name();
31 //! let extension = path.extension();
32 //! let parent_dir = path.parent();
33 //! ```
34 //!
35 //! To build or modify paths, use `PathBuf`:
36 //!
37 //! ```rust
38 //! use std::path::PathBuf;
39 //!
40 //! let mut path = PathBuf::new("c:\\");
41 //! path.push("windows");
42 //! path.push("system32");
43 //! path.set_extension("dll");
44 //! ```
45 //!
46 //! ## Path components and normalization
47 //!
48 //! The path APIs are built around the notion of "components", which roughly
49 //! correspond to the substrings between path separators (`/` and, on Windows,
50 //! `\`). The APIs for path parsing are largely specified in terms of the path's
51 //! components, so it's important to clearly understand how those are determined.
52 //!
53 //! A path can always be reconstructed into an equivalent path by putting
54 //! together its components via `push`. Syntactically, the paths may differ by
55 //! the normalization described below.
56 //!
57 //! ### Component types
58 //!
59 //! Components come in several types:
60 //!
61 //! * Normal components are the default: standard references to files or
62 //! directories. The path `a/b` has two normal components, `a` and `b`.
63 //!
64 //! * Current directory components represent the `.` character. For example,
65 //! `a/.` has a normal component `a` and a current directory component.
66 //!
67 //! * The root directory component represents a separator that designates
68 //!   starting from root. For example, `/a/b` has a root directory component
69 //!   followed by normal components `a` and `b`.
70 //!
71 //! On Windows, two additional component types come into play:
72 //!
73 //! * Prefix components, of which there is a large variety. For example, `C:`
74 //! and `\\server\share` are prefixes. The path `C:windows` has a prefix
75 //! component `C:` and a normal component `windows`; the path `C:\windows` has a
76 //! prefix component `C:`, a root directory component, and a normal component
77 //! `windows`.
78 //!
79 //! * Empty components, a special case for so-called "verbatim" paths where very
80 //! little normalization is allowed. For example, `\\?\C:\` has a "verbatim"
81 //! prefix `\\?\C:`, a root component, and an empty component (as a way of
82 //! representing the trailing `\`. Such a trailing `\` is in fact the only
83 //! situation in which an empty component is produced.
84 //!
85 //! ### Normalization
86 //!
87 //! Aside from splitting on the separator(s), there is a small amount of
88 //! "normalization":
89 //!
90 //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
91 //!   and `b`.
92 //!
93 //! * Paths ending in a separator are treated as if they has a current directory
94 //!   component at the end (or, in verbatim paths, an empty component).  For
95 //!   example, while `a/b` has components `a` and `b`, the paths `a/b/` and
96 //!   `a/b/.` both have components `a`, `b`, and `.` (current directory).  The
97 //!   reason for this normalization is that `a/b` and `a/b/` are treated
98 //!   differently in some contexts, but `a/b/` and `a/b/.` are always treated
99 //!   the same.
100 //!
101 //! No other normalization takes place by default. In particular, `a/./b/` and
102 //! `a/b` are treated distinctly in terms of components, as are `a/c` and
103 //! `a/b/../c`. Further normalization is possible to build on top of the
104 //! components APIs, and will be included in this library very soon.
105
106 #![unstable(feature = "path")]
107
108 use core::prelude::*;
109
110 use ascii::*;
111 use borrow::{Borrow, ToOwned, Cow};
112 use cmp;
113 use iter::{self, IntoIterator};
114 use mem;
115 use ops::{self, Deref};
116 use vec::Vec;
117 use fmt;
118
119 use ffi::{OsStr, OsString, AsOsStr};
120
121 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
122
123 ////////////////////////////////////////////////////////////////////////////////
124 // GENERAL NOTES
125 ////////////////////////////////////////////////////////////////////////////////
126 //
127 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
128 // taking advantage of the fact that OsStr always encodes ASCII characters
129 // as-is.  Eventually, this transmutation should be replaced by direct uses of
130 // OsStr APIs for parsing, but it will take a while for those to become
131 // available.
132
133 ////////////////////////////////////////////////////////////////////////////////
134 // Platform-specific definitions
135 ////////////////////////////////////////////////////////////////////////////////
136
137 // The following modules give the most basic tools for parsing paths on various
138 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
139
140 #[cfg(unix)]
141 mod platform {
142     use super::Prefix;
143     use core::prelude::*;
144     use ffi::OsStr;
145
146     #[inline]
147     pub fn is_sep_byte(b: u8) -> bool {
148         b == b'/'
149     }
150
151     #[inline]
152     pub fn is_verbatim_sep(b: u8) -> bool {
153         b == b'/'
154     }
155
156     pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
157         None
158     }
159
160     pub const MAIN_SEP_STR: &'static str = "/";
161     pub const MAIN_SEP: char = '/';
162 }
163
164 #[cfg(windows)]
165 mod platform {
166     use core::prelude::*;
167     use ascii::*;
168
169     use char::CharExt as UnicodeCharExt;
170     use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
171     use ffi::OsStr;
172
173     #[inline]
174     pub fn is_sep_byte(b: u8) -> bool {
175         b == b'/' || b == b'\\'
176     }
177
178     #[inline]
179     pub fn is_verbatim_sep(b: u8) -> bool {
180         b == b'\\'
181     }
182
183     pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
184         use super::Prefix::*;
185         unsafe {
186             // The unsafety here stems from converting between &OsStr and &[u8]
187             // and back. This is safe to do because (1) we only look at ASCII
188             // contents of the encoding and (2) new &OsStr values are produced
189             // only from ASCII-bounded slices of existing &OsStr values.
190             let mut path = os_str_as_u8_slice(path);
191
192             if path.starts_with(br"\\") {
193                 // \\
194                 path = &path[2..];
195                 if path.starts_with(br"?\") {
196                     // \\?\
197                     path = &path[2..];
198                     if path.starts_with(br"UNC\") {
199                         // \\?\UNC\server\share
200                         path = &path[4..];
201                         let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
202                             Some((server, share)) => (u8_slice_as_os_str(server),
203                                                       u8_slice_as_os_str(share)),
204                             None => (u8_slice_as_os_str(path),
205                                      u8_slice_as_os_str(&[])),
206                         };
207                         return Some(VerbatimUNC(server, share));
208                     } else {
209                         // \\?\path
210                         let idx = path.position_elem(&b'\\');
211                         if idx == Some(2) && path[1] == b':' {
212                             let c = path[0];
213                             if c.is_ascii() && (c as char).is_alphabetic() {
214                                 // \\?\C:\ path
215                                 return Some(VerbatimDisk(c.to_ascii_uppercase()));
216                             }
217                         }
218                         let slice = &path[.. idx.unwrap_or(path.len())];
219                         return Some(Verbatim(u8_slice_as_os_str(slice)));
220                     }
221                 } else if path.starts_with(b".\\") {
222                     // \\.\path
223                     path = &path[2..];
224                     let slice = &path[.. path.position_elem(&b'\\').unwrap_or(path.len())];
225                     return Some(DeviceNS(u8_slice_as_os_str(slice)));
226                 }
227                 match parse_two_comps(path, is_sep_byte) {
228                     Some((server, share)) if server.len() > 0 && share.len() > 0 => {
229                         // \\server\share
230                         return Some(UNC(u8_slice_as_os_str(server),
231                                         u8_slice_as_os_str(share)));
232                     }
233                     _ => ()
234                 }
235             } else if path.len() > 1 && path[1] == b':' {
236                 // C:
237                 let c = path[0];
238                 if c.is_ascii() && (c as char).is_alphabetic() {
239                     return Some(Disk(c.to_ascii_uppercase()));
240                 }
241             }
242             return None;
243         }
244
245         fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
246             let first = match path.iter().position(|x| f(*x)) {
247                 None => return None,
248                 Some(x) => &path[.. x]
249             };
250             path = &path[(first.len()+1)..];
251             let idx = path.iter().position(|x| f(*x));
252             let second = &path[.. idx.unwrap_or(path.len())];
253             Some((first, second))
254         }
255     }
256
257     pub const MAIN_SEP_STR: &'static str = "\\";
258     pub const MAIN_SEP: char = '\\';
259 }
260
261 ////////////////////////////////////////////////////////////////////////////////
262 // Windows Prefixes
263 ////////////////////////////////////////////////////////////////////////////////
264
265 /// Path prefixes (Windows only).
266 ///
267 /// Windows uses a variety of path styles, including references to drive
268 /// volumes (like `C:`), network shared (like `\\server\share`) and
269 /// others. In addition, some path prefixes are "verbatim", in which case
270 /// `/` is *not* treated as a separator and essentially no normalization is
271 /// performed.
272 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
273 pub enum Prefix<'a> {
274     /// Prefix `\\?\`, together with the given component immediately following it.
275     Verbatim(&'a OsStr),
276
277     /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
278     VerbatimUNC(&'a OsStr, &'a OsStr),
279
280     /// Prefix like `\\?\C:\`, for the given drive letter
281     VerbatimDisk(u8),
282
283     /// Prefix `\\.\`, together with the given component immediately following it.
284     DeviceNS(&'a OsStr),
285
286     /// Prefix `\\server\share`, with the given "server" and "share" components.
287     UNC(&'a OsStr, &'a OsStr),
288
289     /// Prefix `C:` for the given disk drive.
290     Disk(u8),
291 }
292
293 impl<'a> Prefix<'a> {
294     #[inline]
295     fn len(&self) -> usize {
296         use self::Prefix::*;
297         fn os_str_len(s: &OsStr) -> usize {
298             os_str_as_u8_slice(s).len()
299         }
300         match *self {
301             Verbatim(x) => 4 + os_str_len(x),
302             VerbatimUNC(x,y) => 8 + os_str_len(x) +
303                 if os_str_len(y) > 0 { 1 + os_str_len(y) }
304                 else { 0 },
305             VerbatimDisk(_) => 6,
306             UNC(x,y) => 2 + os_str_len(x) +
307                 if os_str_len(y) > 0 { 1 + os_str_len(y) }
308                 else { 0 },
309             DeviceNS(x) => 4 + os_str_len(x),
310             Disk(_) => 2
311         }
312
313     }
314
315     /// Determine if the prefix is verbatim, i.e. begins `\\?\`.
316     #[inline]
317     pub fn is_verbatim(&self) -> bool {
318         use self::Prefix::*;
319         match *self {
320             Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
321             _ => false
322         }
323     }
324
325     #[inline]
326     fn is_drive(&self) -> bool {
327         match *self {
328             Prefix::Disk(_) => true,
329             _ => false,
330         }
331     }
332
333     #[inline]
334     fn has_implicit_root(&self) -> bool {
335         !self.is_drive()
336     }
337 }
338
339 ////////////////////////////////////////////////////////////////////////////////
340 // Exposed parsing helpers
341 ////////////////////////////////////////////////////////////////////////////////
342
343 /// Determine whether the character is one of the permitted path
344 /// separators for the current platform.
345 pub fn is_separator(c: char) -> bool {
346     use ascii::*;
347     c.is_ascii() && is_sep_byte(c as u8)
348 }
349
350 /// The primary sperator for the current platform
351 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
352
353 ////////////////////////////////////////////////////////////////////////////////
354 // Misc helpers
355 ////////////////////////////////////////////////////////////////////////////////
356
357 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
358 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
359 // `iter` after having exhausted `prefix`.
360 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where
361     I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq
362 {
363     loop {
364         let mut iter_next = iter.clone();
365         match (iter_next.next(), prefix.next()) {
366             (Some(x), Some(y)) => {
367                 if x != y { return None }
368             }
369             (Some(_), None) => return Some(iter),
370             (None, None) => return Some(iter),
371             (None, Some(_)) => return None,
372         }
373         iter = iter_next;
374     }
375 }
376
377 // See note at the top of this module to understand why these are used:
378 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
379     unsafe { mem::transmute(s) }
380 }
381 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
382     mem::transmute(s)
383 }
384
385 ////////////////////////////////////////////////////////////////////////////////
386 // Cross-platform parsing
387 ////////////////////////////////////////////////////////////////////////////////
388
389 /// Says whether the path ends in a separator character and therefore needs to
390 /// be treated as if it ended with an additional `.`
391 fn has_suffix(s: &[u8], prefix: Option<Prefix>) -> bool {
392     let (prefix_len, verbatim) = if let Some(p) = prefix {
393         (p.len(), p.is_verbatim())
394     } else { (0, false) };
395     if prefix_len > 0 && prefix_len == s.len() && !verbatim { return true; }
396     let mut splits = s[prefix_len..].split(|b| is_sep_byte(*b));
397     let last = splits.next_back().unwrap();
398     let more = splits.next_back().is_some();
399     more && last == b""
400 }
401
402 /// Says whether the first byte after the prefix is a separator.
403 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
404     let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
405     path.len() > 0 && is_sep_byte(path[0])
406 }
407
408 fn parse_single_component(comp: &[u8]) -> Option<Component> {
409     match comp {
410         b"." => Some(Component::CurDir),
411         b".." => Some(Component::ParentDir),
412         b"" => None,
413         _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) }))
414     }
415 }
416
417 // basic workhorse for splitting stem and extension
418 #[allow(unused_unsafe)] // FIXME
419 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
420     unsafe {
421         if os_str_as_u8_slice(file) == b".." { return (Some(file), None) }
422
423         // The unsafety here stems from converting between &OsStr and &[u8]
424         // and back. This is safe to do because (1) we only look at ASCII
425         // contents of the encoding and (2) new &OsStr values are produced
426         // only from ASCII-bounded slices of existing &OsStr values.
427
428         let mut iter = os_str_as_u8_slice(file).rsplitn(1, |b| *b == b'.');
429         let after = iter.next();
430         let before = iter.next();
431         if before == Some(b"") {
432             (Some(file), None)
433         } else {
434             (before.map(|s| u8_slice_as_os_str(s)),
435              after.map(|s| u8_slice_as_os_str(s)))
436         }
437     }
438 }
439
440 ////////////////////////////////////////////////////////////////////////////////
441 // The core iterators
442 ////////////////////////////////////////////////////////////////////////////////
443
444 /// Component parsing works by a double-ended state machine; the cursors at the
445 /// front and back of the path each keep track of what parts of the path have
446 /// been consumed so far.
447 ///
448 /// Going front to back, a path is made up of a prefix, a root component, a body
449 /// (of normal components), and a suffix/emptycomponent (normalized `.` or ``
450 /// for a path ending with the separator)
451 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
452 enum State {
453     Prefix = 0,         // c:
454     Root = 1,           // /
455     Body = 2,           // foo/bar/baz
456     Suffix = 3,         // .
457     Done = 4,
458 }
459
460 /// A single component of a path.
461 ///
462 /// See the module documentation for an in-depth explanation of components and
463 /// their role in the API.
464 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
465 pub enum Component<'a> {
466     /// A Windows path prefix, e.g. `C:` or `\server\share`.
467     ///
468     /// Does not occur on Unix.
469     Prefix {
470         /// The prefix as an unparsed `OsStr` slice.
471         raw: &'a OsStr,
472
473         /// The parsed prefix data.
474         parsed: Prefix<'a>
475     },
476
477     /// An empty component. Only used on Windows for the last component of
478     /// verbatim paths ending with a separator (e.g. the last component of
479     /// `\\?\C:\windows\` but not `\\?\C:\windows` or `C:\windows`).
480     Empty,
481
482     /// The root directory component, appears after any prefix and before anything else
483     RootDir,
484
485     /// A reference to the current directory, i.e. `.`
486     CurDir,
487
488     /// A reference to the parent directory, i.e. `..`
489     ParentDir,
490
491     /// A normal component, i.e. `a` and `b` in `a/b`
492     Normal(&'a OsStr),
493 }
494
495 impl<'a> Component<'a> {
496     /// Extract the underlying `OsStr` slice
497     pub fn as_os_str(self) -> &'a OsStr {
498         match self {
499             Component::Prefix { raw, .. } => &raw,
500             Component::Empty => OsStr::from_str(""),
501             Component::RootDir => OsStr::from_str(MAIN_SEP_STR),
502             Component::CurDir => OsStr::from_str("."),
503             Component::ParentDir => OsStr::from_str(".."),
504             Component::Normal(path) => path,
505         }
506     }
507 }
508
509 /// The core iterator giving the components of a path.
510 ///
511 /// See the module documentation for an in-depth explanation of components and
512 /// their role in the API.
513 #[derive(Clone)]
514 pub struct Components<'a> {
515     // The path left to parse components from
516     path: &'a [u8],
517
518     // The prefix as it was originally parsed, if any
519     prefix: Option<Prefix<'a>>,
520
521     // true if path *physically* has a root separator; for most Windows
522     // prefixes, it may have a "logical" rootseparator for the purposes of
523     // normalization, e.g.  \\server\share == \\server\share\.
524     has_physical_root: bool,
525
526     // The iterator is double-ended, and these two states keep track of what has
527     // been produced from either end
528     front: State,
529     back: State,
530 }
531
532 /// An iterator over the components of a path, as `OsStr` slices.
533 #[derive(Clone)]
534 pub struct Iter<'a> {
535     inner: Components<'a>
536 }
537
538 impl<'a> Components<'a> {
539     // how long is the prefix, if any?
540     #[inline]
541     fn prefix_len(&self) -> usize {
542         self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
543     }
544
545     #[inline]
546     fn prefix_verbatim(&self) -> bool {
547         self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
548     }
549
550     /// how much of the prefix is left from the point of view of iteration?
551     #[inline]
552     fn prefix_remaining(&self) -> usize {
553         if self.front == State::Prefix { self.prefix_len() }
554         else { 0 }
555     }
556
557     fn prefix_and_root(&self) -> usize {
558         let root = if self.front <= State::Root && self.has_physical_root { 1 } else { 0 };
559         self.prefix_remaining() + root
560     }
561
562     // is the iteration complete?
563     #[inline]
564     fn finished(&self) -> bool {
565         self.front == State::Done || self.back == State::Done || self.front > self.back
566     }
567
568     #[inline]
569     fn is_sep_byte(&self, b: u8) -> bool {
570         if self.prefix_verbatim() {
571             is_verbatim_sep(b)
572         } else {
573             is_sep_byte(b)
574         }
575     }
576
577     /// Extract a slice corresponding to the portion of the path remaining for iteration.
578     pub fn as_path(&self) -> &'a Path {
579         let mut comps = self.clone();
580         if comps.front == State::Body { comps.trim_left(); }
581         if comps.back == State::Body { comps.trim_right(); }
582         if comps.path.is_empty() && comps.front < comps.back && comps.back == State::Suffix {
583             Path::new(".")
584         } else {
585             unsafe { Path::from_u8_slice(comps.path) }
586         }
587     }
588
589     /// Is the *original* path rooted?
590     fn has_root(&self) -> bool {
591         if self.has_physical_root { return true }
592         if let Some(p) = self.prefix {
593             if p.has_implicit_root() { return true }
594         }
595         false
596     }
597
598     // parse a component from the left, saying how many bytes to consume to
599     // remove the component
600     fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
601         debug_assert!(self.front == State::Body);
602         let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
603             None => (0, self.path),
604             Some(i) => (1, &self.path[.. i]),
605         };
606         (comp.len() + extra, parse_single_component(comp))
607     }
608
609     // parse a component from the right, saying how many bytes to consume to
610     // remove the component
611     fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
612         debug_assert!(self.back == State::Body);
613         let start = self.prefix_and_root();
614         let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
615             None => (0, &self.path[start ..]),
616             Some(i) => (1, &self.path[start + i + 1 ..]),
617         };
618         (comp.len() + extra, parse_single_component(comp))
619     }
620
621     // trim away repeated separators (i.e. emtpy components) on the left
622     fn trim_left(&mut self) {
623         while !self.path.is_empty() {
624             let (size, comp) = self.parse_next_component();
625             if comp.is_some() {
626                 return;
627             } else {
628                 self.path = &self.path[size ..];
629             }
630         }
631     }
632
633     // trim away repeated separators (i.e. emtpy components) on the right
634     fn trim_right(&mut self) {
635         while self.path.len() > self.prefix_and_root() {
636             let (size, comp) = self.parse_next_component_back();
637             if comp.is_some() {
638                 return;
639             } else {
640                 self.path = &self.path[.. self.path.len() - size];
641             }
642         }
643     }
644
645     /// Examine the next component without consuming it.
646     pub fn peek(&self) -> Option<Component<'a>> {
647         self.clone().next()
648     }
649 }
650
651 impl<'a> Iter<'a> {
652     /// Extract a slice corresponding to the portion of the path remaining for iteration.
653     pub fn as_path(&self) -> &'a Path {
654         self.inner.as_path()
655     }
656 }
657
658 impl<'a> Iterator for Iter<'a> {
659     type Item = &'a OsStr;
660
661     fn next(&mut self) -> Option<&'a OsStr> {
662         self.inner.next().map(Component::as_os_str)
663     }
664 }
665
666 impl<'a> DoubleEndedIterator for Iter<'a> {
667     fn next_back(&mut self) -> Option<&'a OsStr> {
668         self.inner.next_back().map(Component::as_os_str)
669     }
670 }
671
672 impl<'a> Iterator for Components<'a> {
673     type Item = Component<'a>;
674
675     fn next(&mut self) -> Option<Component<'a>> {
676         while !self.finished() {
677             match self.front {
678                 State::Prefix if self.prefix_len() > 0 => {
679                     self.front = State::Root;
680                     debug_assert!(self.prefix_len() <= self.path.len());
681                     let raw = &self.path[.. self.prefix_len()];
682                     self.path = &self.path[self.prefix_len() .. ];
683                     return Some(Component::Prefix {
684                         raw: unsafe { u8_slice_as_os_str(raw) },
685                         parsed: self.prefix.unwrap()
686                     })
687                 }
688                 State::Prefix => {
689                     self.front = State::Root;
690                 }
691                 State::Root => {
692                     self.front = State::Body;
693                     if self.has_physical_root {
694                         debug_assert!(self.path.len() > 0);
695                         self.path = &self.path[1..];
696                         return Some(Component::RootDir)
697                     } else if let Some(p) = self.prefix {
698                         if p.has_implicit_root() && !p.is_verbatim() {
699                             return Some(Component::RootDir)
700                         }
701                     }
702                 }
703                 State::Body if !self.path.is_empty() => {
704                     let (size, comp) = self.parse_next_component();
705                     self.path = &self.path[size ..];
706                     if comp.is_some() { return comp }
707                 }
708                 State::Body => {
709                     self.front = State::Suffix;
710                 }
711                 State::Suffix => {
712                     self.front = State::Done;
713                     if self.prefix_verbatim() {
714                         return Some(Component::Empty)
715                     } else {
716                         return Some(Component::CurDir)
717                     }
718                 }
719                 State::Done => unreachable!()
720             }
721         }
722         None
723     }
724 }
725
726 impl<'a> DoubleEndedIterator for Components<'a> {
727     fn next_back(&mut self) -> Option<Component<'a>> {
728         while !self.finished() {
729             match self.back {
730                 State::Suffix => {
731                     self.back = State::Body;
732                     if self.prefix_verbatim() {
733                         return Some(Component::Empty)
734                     } else {
735                         return Some(Component::CurDir)
736                     }
737                 }
738                 State::Body if self.path.len() > self.prefix_and_root() => {
739                     let (size, comp) = self.parse_next_component_back();
740                     self.path = &self.path[.. self.path.len() - size];
741                     if comp.is_some() { return comp }
742                 }
743                 State::Body => {
744                     self.back = State::Root;
745                 }
746                 State::Root => {
747                     self.back = State::Prefix;
748                     if self.has_physical_root {
749                         self.path = &self.path[.. self.path.len() - 1];
750                         return Some(Component::RootDir)
751                     } else if let Some(p) = self.prefix {
752                         if p.has_implicit_root() && !p.is_verbatim() {
753                             return Some(Component::RootDir)
754                         }
755                     }
756                 }
757                 State::Prefix if self.prefix_len() > 0 => {
758                     self.back = State::Done;
759                     return Some(Component::Prefix {
760                         raw: unsafe { u8_slice_as_os_str(self.path) },
761                         parsed: self.prefix.unwrap()
762                     })
763                 }
764                 State::Prefix => {
765                     self.back = State::Done;
766                     return None
767                 }
768                 State::Done => unreachable!()
769             }
770         }
771         None
772     }
773 }
774
775 fn optional_path(path: &Path) -> Option<&Path> {
776     if path.as_u8_slice().is_empty() { None } else { Some(path) }
777 }
778
779 impl<'a> cmp::PartialEq for Components<'a> {
780     fn eq(&self, other: &Components<'a>) -> bool {
781         iter::order::eq(self.clone(), other.clone())
782     }
783 }
784
785 impl<'a> cmp::Eq for Components<'a> {}
786
787 impl<'a> cmp::PartialOrd for Components<'a> {
788     fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
789         iter::order::partial_cmp(self.clone(), other.clone())
790     }
791 }
792
793 impl<'a> cmp::Ord for Components<'a> {
794     fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
795         iter::order::cmp(self.clone(), other.clone())
796     }
797 }
798
799 ////////////////////////////////////////////////////////////////////////////////
800 // Basic types and traits
801 ////////////////////////////////////////////////////////////////////////////////
802
803 /// An owned, mutable path (akin to `String`).
804 ///
805 /// This type provides methods like `push` and `set_extension` that mutate the
806 /// path in place. It also implements `Deref` to `Path`, meaning that all
807 /// methods on `Path` slices are available on `PathBuf` values as well.
808 ///
809 /// More details about the overall approach can be found in
810 /// the module documentation.
811 ///
812 /// # Example
813 ///
814 /// ```rust
815 /// use std::path::PathBuf;
816 ///
817 /// let mut path = PathBuf::new("c:\\");
818 /// path.push("windows");
819 /// path.push("system32");
820 /// path.set_extension("dll");
821 /// ```
822 #[derive(Clone, Hash)]
823 pub struct PathBuf {
824     inner: OsString
825 }
826
827 impl PathBuf {
828     fn as_mut_vec(&mut self) -> &mut Vec<u8> {
829         unsafe { mem::transmute(self) }
830     }
831
832     /// Allocate a `PathBuf` with initial contents given by the
833     /// argument.
834     pub fn new<S: ?Sized + AsOsStr>(s: &S) -> PathBuf {
835         PathBuf { inner: s.as_os_str().to_os_string() }
836     }
837
838     /// Extend `self` with `path`.
839     ///
840     /// If `path` is absolute, it replaces the current path.
841     ///
842     /// On Windows:
843     ///
844     /// * if `path` has a root but no prefix (e.g. `\windows`), it
845     ///   replaces everything except for the prefix (if any) of `self`.
846     /// * if `path` has a prefix but no root, it replaces `self.
847     pub fn push<P: ?Sized>(&mut self, path: &P) where P: AsPath {
848         // in general, a separator is needed if the rightmost byte is not a separator
849         let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
850
851         // in the special case of `C:` on Windows, do *not* add a separator
852         {
853             let comps = self.components();
854             if comps.prefix_len() > 0 &&
855                 comps.prefix_len() == comps.path.len() &&
856                 comps.prefix.unwrap().is_drive()
857             {
858                 need_sep = false
859             }
860         }
861
862         let path = path.as_path();
863
864         // absolute `path` replaces `self`
865         if path.is_absolute() || path.prefix().is_some() {
866             self.as_mut_vec().truncate(0);
867
868         // `path` has a root but no prefix, e.g. `\windows` (Windows only)
869         } else if path.has_root() {
870             let prefix_len = self.components().prefix_remaining();
871             self.as_mut_vec().truncate(prefix_len);
872
873         // `path` is a pure relative path
874         } else if need_sep {
875             self.inner.push_os_str(OsStr::from_str(MAIN_SEP_STR));
876         }
877
878         self.inner.push_os_str(path.as_os_str());
879     }
880
881     /// Truncate `self` to `self.parent()`.
882     ///
883     /// Returns `false` and does nothing if `self.parent()` is `None`.
884     /// Otherwise, returns `true`.
885     pub fn pop(&mut self) -> bool {
886         match self.parent().map(|p| p.as_u8_slice().len()) {
887             Some(len) => {
888                 self.as_mut_vec().truncate(len);
889                 true
890             }
891             None => false
892         }
893     }
894
895     /// Updates `self.file_name()` to `file_name`.
896     ///
897     /// If `self.file_name()` was `None`, this is equivalent to pushing
898     /// `file_name`.
899     ///
900     /// # Examples
901     ///
902     /// ```rust
903     /// use std::path::{Path, PathBuf};
904     ///
905     /// let mut buf = PathBuf::new("/foo/");
906     /// assert!(buf.file_name() == None);
907     /// buf.set_file_name("bar");
908     /// assert!(buf == PathBuf::new("/foo/bar"));
909     /// assert!(buf.file_name().is_some());
910     /// buf.set_file_name("baz.txt");
911     /// assert!(buf == PathBuf::new("/foo/baz.txt"));
912     /// ```
913     pub fn set_file_name<S: ?Sized>(&mut self, file_name: &S) where S: AsOsStr {
914         if self.file_name().is_some() && !self.pop() {
915             // Given that there is a file name, this is reachable only for
916             // Windows paths like c:file or paths like `foo`, but not `c:\` or
917             // `/`.
918             let prefix_len = self.components().prefix_remaining();
919             self.as_mut_vec().truncate(prefix_len);
920         }
921         self.push(file_name.as_os_str());
922     }
923
924     /// Updates `self.extension()` to `extension`.
925     ///
926     /// If `self.file_name()` is `None`, does nothing and returns `false`.
927     ///
928     /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
929     /// is added; otherwise it is replaced.
930     pub fn set_extension<S: ?Sized + AsOsStr>(&mut self, extension: &S) -> bool {
931         if self.file_name().is_none() { return false; }
932
933         let mut stem = match self.file_stem() {
934             Some(stem) => stem.to_os_string(),
935             None => OsString::from_str(""),
936         };
937
938         let extension = extension.as_os_str();
939         if os_str_as_u8_slice(extension).len() > 0 {
940             stem.push_os_str(OsStr::from_str("."));
941             stem.push_os_str(extension.as_os_str());
942         }
943         self.set_file_name(&stem);
944
945         true
946     }
947
948     /// Consume the `PathBuf`, yielding its internal `OsString` storage
949     pub fn into_os_string(self) -> OsString {
950         self.inner
951     }
952 }
953
954 impl<'a, P: ?Sized + 'a> iter::FromIterator<&'a P> for PathBuf where P: AsPath {
955     fn from_iter<I: IntoIterator<Item = &'a P>>(iter: I) -> PathBuf {
956         let mut buf = PathBuf::new("");
957         buf.extend(iter);
958         buf
959     }
960 }
961
962 impl<'a, P: ?Sized + 'a> iter::Extend<&'a P> for PathBuf where P: AsPath {
963     fn extend<I: IntoIterator<Item = &'a P>>(&mut self, iter: I) {
964         for p in iter {
965             self.push(p)
966         }
967     }
968 }
969
970 impl fmt::Debug for PathBuf {
971     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
972         fmt::Debug::fmt(&**self, formatter)
973     }
974 }
975
976 impl ops::Deref for PathBuf {
977     type Target = Path;
978
979     fn deref(&self) -> &Path {
980         unsafe { mem::transmute(&self.inner[..]) }
981     }
982 }
983
984 impl Borrow<Path> for PathBuf {
985     fn borrow(&self) -> &Path {
986         self.deref()
987     }
988 }
989
990 impl ToOwned for Path {
991     type Owned = PathBuf;
992     fn to_owned(&self) -> PathBuf { self.to_path_buf() }
993 }
994
995 impl cmp::PartialEq for PathBuf {
996     fn eq(&self, other: &PathBuf) -> bool {
997         self.components() == other.components()
998     }
999 }
1000
1001 impl cmp::Eq for PathBuf {}
1002
1003 impl cmp::PartialOrd for PathBuf {
1004     fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1005         self.components().partial_cmp(&other.components())
1006     }
1007 }
1008
1009 impl cmp::Ord for PathBuf {
1010     fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1011         self.components().cmp(&other.components())
1012     }
1013 }
1014
1015 impl AsOsStr for PathBuf {
1016     fn as_os_str(&self) -> &OsStr {
1017         &self.inner[..]
1018     }
1019 }
1020
1021 /// A slice of a path (akin to `str`).
1022 ///
1023 /// This type supports a number of operations for inspecting a path, including
1024 /// breaking the path into its components (separated by `/` or `\`, depending on
1025 /// the platform), extracting the file name, determining whether the path is
1026 /// absolute, and so on. More details about the overall approach can be found in
1027 /// the module documentation.
1028 ///
1029 /// This is an *unsized* type, meaning that it must always be used with behind a
1030 /// pointer like `&` or `Box`.
1031 ///
1032 /// # Example
1033 ///
1034 /// ```rust
1035 /// use std::path::Path;
1036 ///
1037 /// let path = Path::new("/tmp/foo/bar.txt");
1038 /// let file = path.file_name();
1039 /// let extension = path.extension();
1040 /// let parent_dir = path.parent();
1041 /// ```
1042 ///
1043 #[derive(Hash)]
1044 pub struct Path {
1045     inner: OsStr
1046 }
1047
1048 impl Path {
1049     // The following (private!) function allows construction of a path from a u8
1050     // slice, which is only safe when it is known to follow the OsStr encoding.
1051     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1052         mem::transmute(s)
1053     }
1054     // The following (private!) function reveals the byte encoding used for OsStr.
1055     fn as_u8_slice(&self) -> &[u8] {
1056         unsafe { mem::transmute(self) }
1057     }
1058
1059     /// Directly wrap a string slice as a `Path` slice.
1060     ///
1061     /// This is a cost-free conversion.
1062     pub fn new<S: ?Sized + AsOsStr>(s: &S) -> &Path {
1063         unsafe { mem::transmute(s.as_os_str()) }
1064     }
1065
1066     /// Yield a `&str` slice if the `Path` is valid unicode.
1067     ///
1068     /// This conversion may entail doing a check for UTF-8 validity.
1069     pub fn to_str(&self) -> Option<&str> {
1070         self.inner.to_str()
1071     }
1072
1073     /// Convert a `Path` to a `Cow<str>`.
1074     ///
1075     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1076     pub fn to_string_lossy(&self) -> Cow<str> {
1077         self.inner.to_string_lossy()
1078     }
1079
1080     /// Convert a `Path` to an owned `PathBuf`.
1081     pub fn to_path_buf(&self) -> PathBuf {
1082         PathBuf::new(self)
1083     }
1084
1085     /// A path is *absolute* if it is independent of the current directory.
1086     ///
1087     /// * On Unix, a path is absolute if it starts with the root, so
1088     /// `is_absolute` and `has_root` are equivalent.
1089     ///
1090     /// * On Windows, a path is absolute if it has a prefix and starts with the
1091     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1092     /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1093     pub fn is_absolute(&self) -> bool {
1094         self.has_root() &&
1095             (cfg!(unix) || self.prefix().is_some())
1096     }
1097
1098     /// A path is *relative* if it is not absolute.
1099     pub fn is_relative(&self) -> bool {
1100         !self.is_absolute()
1101     }
1102
1103     /// Returns the *prefix* of a path, if any.
1104     ///
1105     /// Prefixes are relevant only for Windows paths, and consist of volumes
1106     /// like `C:`, UNC prefixes like `\\server`, and others described in more
1107     /// detail in `std::os::windows::PathExt`.
1108     pub fn prefix(&self) -> Option<&Path> {
1109         let iter = self.components();
1110         optional_path(unsafe {
1111             Path::from_u8_slice(
1112                 &self.as_u8_slice()[.. iter.prefix_remaining()])
1113         })
1114     }
1115
1116     /// A path has a root if the body of the path begins with the directory separator.
1117     ///
1118     /// * On Unix, a path has a root if it begins with `/`.
1119     ///
1120     /// * On Windows, a path has a root if it:
1121     ///     * has no prefix and begins with a separator, e.g. `\\windows`
1122     ///     * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1123     ///     * has any non-disk prefix, e.g. `\\server\share`
1124     pub fn has_root(&self) -> bool {
1125          self.components().has_root()
1126     }
1127
1128     /// The path without its final component.
1129     ///
1130     /// Does nothing, returning `None` if the path consists of just a prefix
1131     /// and/or root directory reference.
1132     ///
1133     /// # Examples
1134     ///
1135     /// ```rust
1136     /// use std::path::Path;
1137     ///
1138     /// let path = Path::new("/foo/bar");
1139     /// let foo = path.parent().unwrap();
1140     /// assert!(foo == Path::new("/foo"));
1141     /// let root = foo.parent().unwrap();
1142     /// assert!(root == Path::new("/"));
1143     /// assert!(root.parent() == None);
1144     /// ```
1145     pub fn parent(&self) -> Option<&Path> {
1146         let mut comps = self.components();
1147         let comp = comps.next_back();
1148         let rest = optional_path(comps.as_path());
1149
1150         match (comp, comps.next_back()) {
1151             (Some(Component::CurDir), Some(Component::RootDir)) => None,
1152             (Some(Component::CurDir), Some(Component::Prefix { .. })) => None,
1153             (Some(Component::Empty), Some(Component::RootDir)) => None,
1154             (Some(Component::Empty), Some(Component::Prefix { .. })) => None,
1155             (Some(Component::Prefix { .. }), None) => None,
1156             (Some(Component::RootDir), Some(Component::Prefix { .. })) => None,
1157             _ => rest
1158         }
1159     }
1160
1161     /// The final component of the path, if it is a normal file.
1162     ///
1163     /// If the path terminates in `.`, `..`, or consists solely or a root of
1164     /// prefix, `file` will return `None`.
1165     pub fn file_name(&self) -> Option<&OsStr> {
1166         self.components().next_back().and_then(|p| match p {
1167             Component::Normal(p) => Some(p.as_os_str()),
1168             _ => None
1169         })
1170     }
1171
1172     /// Returns a path that, when joined onto `base`, yields `self`.
1173     pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where
1174         P: AsPath
1175     {
1176         iter_after(self.components(), base.as_path().components()).map(|c| c.as_path())
1177     }
1178
1179     /// Determines whether `base` is a prefix of `self`.
1180     pub fn starts_with<P: ?Sized>(&self, base: &P) -> bool where P: AsPath {
1181         iter_after(self.components(), base.as_path().components()).is_some()
1182     }
1183
1184     /// Determines whether `base` is a suffix of `self`.
1185     pub fn ends_with<P: ?Sized>(&self, child: &P) -> bool where P: AsPath {
1186         iter_after(self.components().rev(), child.as_path().components().rev()).is_some()
1187     }
1188
1189     /// Extract the stem (non-extension) portion of `self.file()`.
1190     ///
1191     /// The stem is:
1192     ///
1193     /// * None, if there is no file name;
1194     /// * The entire file name if there is no embedded `.`;
1195     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1196     /// * Otherwise, the portion of the file name before the final `.`
1197     pub fn file_stem(&self) -> Option<&OsStr> {
1198         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1199     }
1200
1201     /// Extract the extension of `self.file()`, if possible.
1202     ///
1203     /// The extension is:
1204     ///
1205     /// * None, if there is no file name;
1206     /// * None, if there is no embedded `.`;
1207     /// * None, if the file name begins with `.` and has no other `.`s within;
1208     /// * Otherwise, the portion of the file name after the final `.`
1209     pub fn extension(&self) -> Option<&OsStr> {
1210         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1211     }
1212
1213     /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1214     ///
1215     /// See `PathBuf::push` for more details on what it means to adjoin a path.
1216     pub fn join<P: ?Sized>(&self, path: &P) -> PathBuf where P: AsPath {
1217         let mut buf = self.to_path_buf();
1218         buf.push(path);
1219         buf
1220     }
1221
1222     /// Creates an owned `PathBuf` like `self` but with the given file name.
1223     ///
1224     /// See `PathBuf::set_file_name` for more details.
1225     pub fn with_file_name<S: ?Sized>(&self, file_name: &S) -> PathBuf where S: AsOsStr {
1226         let mut buf = self.to_path_buf();
1227         buf.set_file_name(file_name);
1228         buf
1229     }
1230
1231     /// Creates an owned `PathBuf` like `self` but with the given extension.
1232     ///
1233     /// See `PathBuf::set_extension` for more details.
1234     pub fn with_extension<S: ?Sized>(&self, extension: &S) -> PathBuf where S: AsOsStr {
1235         let mut buf = self.to_path_buf();
1236         buf.set_extension(extension);
1237         buf
1238     }
1239
1240     /// Produce an iterator over the components of the path.
1241     pub fn components(&self) -> Components {
1242         let prefix = parse_prefix(self.as_os_str());
1243         Components {
1244             path: self.as_u8_slice(),
1245             prefix: prefix,
1246             has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1247             front: State::Prefix,
1248             back: if has_suffix(self.as_u8_slice(), prefix) { State::Suffix }
1249                   else { State::Body },
1250         }
1251     }
1252
1253     /// Produce an iterator over the path's components viewed as `OsStr` slices.
1254     pub fn iter(&self) -> Iter {
1255         Iter { inner: self.components() }
1256     }
1257
1258     /// Returns an object that implements `Display` for safely printing paths
1259     /// that may contain non-Unicode data.
1260     pub fn display(&self) -> Display {
1261         Display { path: self }
1262     }
1263 }
1264
1265 impl AsOsStr for Path {
1266     fn as_os_str(&self) -> &OsStr {
1267         &self.inner
1268     }
1269 }
1270
1271 impl fmt::Debug for Path {
1272     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1273         self.inner.fmt(formatter)
1274     }
1275 }
1276
1277 /// Helper struct for safely printing paths with `format!()` and `{}`
1278 pub struct Display<'a> {
1279     path: &'a Path
1280 }
1281
1282 impl<'a> fmt::Debug for Display<'a> {
1283     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1284         fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1285     }
1286 }
1287
1288 impl<'a> fmt::Display for Display<'a> {
1289     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1290         fmt::Display::fmt(&self.path.to_string_lossy(), f)
1291     }
1292 }
1293
1294 impl cmp::PartialEq for Path {
1295     fn eq(&self, other: &Path) -> bool {
1296         iter::order::eq(self.components(), other.components())
1297     }
1298 }
1299
1300 impl cmp::Eq for Path {}
1301
1302 impl cmp::PartialOrd for Path {
1303     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1304         self.components().partial_cmp(&other.components())
1305     }
1306 }
1307
1308 impl cmp::Ord for Path {
1309     fn cmp(&self, other: &Path) -> cmp::Ordering {
1310         self.components().cmp(&other.components())
1311     }
1312 }
1313
1314 /// Freely convertible to a `Path`.
1315 pub trait AsPath {
1316     /// Convert to a `Path`.
1317     fn as_path(&self) -> &Path;
1318 }
1319
1320 impl<T: AsOsStr + ?Sized> AsPath for T {
1321     fn as_path(&self) -> &Path { Path::new(self.as_os_str()) }
1322 }
1323
1324 #[cfg(test)]
1325 mod tests {
1326     use super::*;
1327     use ffi::OsStr;
1328     use core::prelude::*;
1329     use string::{ToString, String};
1330     use vec::Vec;
1331
1332     macro_rules! t(
1333         ($path:expr, iter: $iter:expr) => (
1334             {
1335                 let path = Path::new($path);
1336
1337                 // Forward iteration
1338                 let comps = path.iter()
1339                     .map(|p| p.to_string_lossy().into_owned())
1340                     .collect::<Vec<String>>();
1341                 let exp: &[&str] = &$iter;
1342                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
1343                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
1344                         exps, comps);
1345
1346                 // Reverse iteration
1347                 let comps = Path::new($path).iter().rev()
1348                     .map(|p| p.to_string_lossy().into_owned())
1349                     .collect::<Vec<String>>();
1350                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
1351                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
1352                         exps, comps);
1353             }
1354         );
1355
1356         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
1357             {
1358                 let path = Path::new($path);
1359
1360                 let act_root = path.has_root();
1361                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
1362                         $has_root, act_root);
1363
1364                 let act_abs = path.is_absolute();
1365                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
1366                         $is_absolute, act_abs);
1367             }
1368         );
1369
1370         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
1371             {
1372                 let path = Path::new($path);
1373
1374                 let parent = path.parent().map(|p| p.to_str().unwrap());
1375                 let exp_parent: Option<&str> = $parent;
1376                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
1377                         exp_parent, parent);
1378
1379                 let file = path.file_name().map(|p| p.to_str().unwrap());
1380                 let exp_file: Option<&str> = $file;
1381                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
1382                         exp_file, file);
1383             }
1384         );
1385
1386         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
1387             {
1388                 let path = Path::new($path);
1389
1390                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
1391                 let exp_stem: Option<&str> = $file_stem;
1392                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
1393                         exp_stem, stem);
1394
1395                 let ext = path.extension().map(|p| p.to_str().unwrap());
1396                 let exp_ext: Option<&str> = $extension;
1397                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
1398                         exp_ext, ext);
1399             }
1400         );
1401
1402         ($path:expr, iter: $iter:expr,
1403                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
1404                      parent: $parent:expr, file_name: $file:expr,
1405                      file_stem: $file_stem:expr, extension: $extension:expr) => (
1406             {
1407                 t!($path, iter: $iter);
1408                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
1409                 t!($path, parent: $parent, file_name: $file);
1410                 t!($path, file_stem: $file_stem, extension: $extension);
1411             }
1412         );
1413     );
1414
1415     #[test]
1416     #[cfg(unix)]
1417     pub fn test_decompositions_unix() {
1418         t!("",
1419            iter: [],
1420            has_root: false,
1421            is_absolute: false,
1422            parent: None,
1423            file_name: None,
1424            file_stem: None,
1425            extension: None
1426            );
1427
1428         t!("foo",
1429            iter: ["foo"],
1430            has_root: false,
1431            is_absolute: false,
1432            parent: None,
1433            file_name: Some("foo"),
1434            file_stem: Some("foo"),
1435            extension: None
1436            );
1437
1438         t!("/",
1439            iter: ["/", "."],
1440            has_root: true,
1441            is_absolute: true,
1442            parent: None,
1443            file_name: None,
1444            file_stem: None,
1445            extension: None
1446            );
1447
1448         t!("/foo",
1449            iter: ["/", "foo"],
1450            has_root: true,
1451            is_absolute: true,
1452            parent: Some("/"),
1453            file_name: Some("foo"),
1454            file_stem: Some("foo"),
1455            extension: None
1456            );
1457
1458         t!("foo/",
1459            iter: ["foo", "."],
1460            has_root: false,
1461            is_absolute: false,
1462            parent: Some("foo"),
1463            file_name: None,
1464            file_stem: None,
1465            extension: None
1466            );
1467
1468         t!("/foo/",
1469            iter: ["/", "foo", "."],
1470            has_root: true,
1471            is_absolute: true,
1472            parent: Some("/foo"),
1473            file_name: None,
1474            file_stem: None,
1475            extension: None
1476            );
1477
1478         t!("foo/bar",
1479            iter: ["foo", "bar"],
1480            has_root: false,
1481            is_absolute: false,
1482            parent: Some("foo"),
1483            file_name: Some("bar"),
1484            file_stem: Some("bar"),
1485            extension: None
1486            );
1487
1488         t!("/foo/bar",
1489            iter: ["/", "foo", "bar"],
1490            has_root: true,
1491            is_absolute: true,
1492            parent: Some("/foo"),
1493            file_name: Some("bar"),
1494            file_stem: Some("bar"),
1495            extension: None
1496            );
1497
1498         t!("///foo///",
1499            iter: ["/", "foo", "."],
1500            has_root: true,
1501            is_absolute: true,
1502            parent: Some("///foo"),
1503            file_name: None,
1504            file_stem: None,
1505            extension: None
1506            );
1507
1508         t!("///foo///bar",
1509            iter: ["/", "foo", "bar"],
1510            has_root: true,
1511            is_absolute: true,
1512            parent: Some("///foo"),
1513            file_name: Some("bar"),
1514            file_stem: Some("bar"),
1515            extension: None
1516            );
1517
1518         t!("./.",
1519            iter: [".", "."],
1520            has_root: false,
1521            is_absolute: false,
1522            parent: Some("."),
1523            file_name: None,
1524            file_stem: None,
1525            extension: None
1526            );
1527
1528         t!("./.",
1529            iter: [".", "."],
1530            has_root: false,
1531            is_absolute: false,
1532            parent: Some("."),
1533            file_name: None,
1534            file_stem: None,
1535            extension: None
1536            );
1537
1538         t!("/..",
1539            iter: ["/", ".."],
1540            has_root: true,
1541            is_absolute: true,
1542            parent: Some("/"),
1543            file_name: None,
1544            file_stem: None,
1545            extension: None
1546            );
1547
1548         t!("../",
1549            iter: ["..", "."],
1550            has_root: false,
1551            is_absolute: false,
1552            parent: Some(".."),
1553            file_name: None,
1554            file_stem: None,
1555            extension: None
1556            );
1557
1558         t!("foo/.",
1559            iter: ["foo", "."],
1560            has_root: false,
1561            is_absolute: false,
1562            parent: Some("foo"),
1563            file_name: None,
1564            file_stem: None,
1565            extension: None
1566            );
1567
1568         t!("foo/..",
1569            iter: ["foo", ".."],
1570            has_root: false,
1571            is_absolute: false,
1572            parent: Some("foo"),
1573            file_name: None,
1574            file_stem: None,
1575            extension: None
1576            );
1577
1578         t!("foo/./",
1579            iter: ["foo", ".", "."],
1580            has_root: false,
1581            is_absolute: false,
1582            parent: Some("foo/."),
1583            file_name: None,
1584            file_stem: None,
1585            extension: None
1586            );
1587
1588         t!("foo/./bar",
1589            iter: ["foo", ".", "bar"],
1590            has_root: false,
1591            is_absolute: false,
1592            parent: Some("foo/."),
1593            file_name: Some("bar"),
1594            file_stem: Some("bar"),
1595            extension: None
1596            );
1597
1598         t!("foo/../",
1599            iter: ["foo", "..", "."],
1600            has_root: false,
1601            is_absolute: false,
1602            parent: Some("foo/.."),
1603            file_name: None,
1604            file_stem: None,
1605            extension: None
1606            );
1607
1608         t!("foo/../bar",
1609            iter: ["foo", "..", "bar"],
1610            has_root: false,
1611            is_absolute: false,
1612            parent: Some("foo/.."),
1613            file_name: Some("bar"),
1614            file_stem: Some("bar"),
1615            extension: None
1616            );
1617
1618         t!("./a",
1619            iter: [".", "a"],
1620            has_root: false,
1621            is_absolute: false,
1622            parent: Some("."),
1623            file_name: Some("a"),
1624            file_stem: Some("a"),
1625            extension: None
1626            );
1627
1628         t!(".",
1629            iter: ["."],
1630            has_root: false,
1631            is_absolute: false,
1632            parent: None,
1633            file_name: None,
1634            file_stem: None,
1635            extension: None
1636            );
1637
1638         t!("./",
1639            iter: [".", "."],
1640            has_root: false,
1641            is_absolute: false,
1642            parent: Some("."),
1643            file_name: None,
1644            file_stem: None,
1645            extension: None
1646            );
1647
1648         t!("a/b",
1649            iter: ["a", "b"],
1650            has_root: false,
1651            is_absolute: false,
1652            parent: Some("a"),
1653            file_name: Some("b"),
1654            file_stem: Some("b"),
1655            extension: None
1656            );
1657
1658         t!("a//b",
1659            iter: ["a", "b"],
1660            has_root: false,
1661            is_absolute: false,
1662            parent: Some("a"),
1663            file_name: Some("b"),
1664            file_stem: Some("b"),
1665            extension: None
1666            );
1667
1668         t!("a/./b",
1669            iter: ["a", ".", "b"],
1670            has_root: false,
1671            is_absolute: false,
1672            parent: Some("a/."),
1673            file_name: Some("b"),
1674            file_stem: Some("b"),
1675            extension: None
1676            );
1677
1678         t!("a/b/c",
1679            iter: ["a", "b", "c"],
1680            has_root: false,
1681            is_absolute: false,
1682            parent: Some("a/b"),
1683            file_name: Some("c"),
1684            file_stem: Some("c"),
1685            extension: None
1686            );
1687     }
1688
1689     #[test]
1690     #[cfg(windows)]
1691     pub fn test_decompositions_windows() {
1692         t!("",
1693            iter: [],
1694            has_root: false,
1695            is_absolute: false,
1696            parent: None,
1697            file_name: None,
1698            file_stem: None,
1699            extension: None
1700            );
1701
1702         t!("foo",
1703            iter: ["foo"],
1704            has_root: false,
1705            is_absolute: false,
1706            parent: None,
1707            file_name: Some("foo"),
1708            file_stem: Some("foo"),
1709            extension: None
1710            );
1711
1712         t!("/",
1713            iter: ["\\", "."],
1714            has_root: true,
1715            is_absolute: false,
1716            parent: None,
1717            file_name: None,
1718            file_stem: None,
1719            extension: None
1720            );
1721
1722         t!("\\",
1723            iter: ["\\", "."],
1724            has_root: true,
1725            is_absolute: false,
1726            parent: None,
1727            file_name: None,
1728            file_stem: None,
1729            extension: None
1730            );
1731
1732         t!("c:",
1733            iter: ["c:", "."],
1734            has_root: false,
1735            is_absolute: false,
1736            parent: None,
1737            file_name: None,
1738            file_stem: None,
1739            extension: None
1740            );
1741
1742         t!("c:\\",
1743            iter: ["c:", "\\", "."],
1744            has_root: true,
1745            is_absolute: true,
1746            parent: None,
1747            file_name: None,
1748            file_stem: None,
1749            extension: None
1750            );
1751
1752         t!("c:\\",
1753            iter: ["c:", "\\", "."],
1754            has_root: true,
1755            is_absolute: true,
1756            parent: None,
1757            file_name: None,
1758            file_stem: None,
1759            extension: None
1760            );
1761
1762         t!("c:/",
1763            iter: ["c:", "\\", "."],
1764            has_root: true,
1765            is_absolute: true,
1766            parent: None,
1767            file_name: None,
1768            file_stem: None,
1769            extension: None
1770            );
1771
1772         t!("/foo",
1773            iter: ["\\", "foo"],
1774            has_root: true,
1775            is_absolute: false,
1776            parent: Some("/"),
1777            file_name: Some("foo"),
1778            file_stem: Some("foo"),
1779            extension: None
1780            );
1781
1782         t!("foo/",
1783            iter: ["foo", "."],
1784            has_root: false,
1785            is_absolute: false,
1786            parent: Some("foo"),
1787            file_name: None,
1788            file_stem: None,
1789            extension: None
1790            );
1791
1792         t!("/foo/",
1793            iter: ["\\", "foo", "."],
1794            has_root: true,
1795            is_absolute: false,
1796            parent: Some("/foo"),
1797            file_name: None,
1798            file_stem: None,
1799            extension: None
1800            );
1801
1802         t!("foo/bar",
1803            iter: ["foo", "bar"],
1804            has_root: false,
1805            is_absolute: false,
1806            parent: Some("foo"),
1807            file_name: Some("bar"),
1808            file_stem: Some("bar"),
1809            extension: None
1810            );
1811
1812         t!("/foo/bar",
1813            iter: ["\\", "foo", "bar"],
1814            has_root: true,
1815            is_absolute: false,
1816            parent: Some("/foo"),
1817            file_name: Some("bar"),
1818            file_stem: Some("bar"),
1819            extension: None
1820            );
1821
1822         t!("///foo///",
1823            iter: ["\\", "foo", "."],
1824            has_root: true,
1825            is_absolute: false,
1826            parent: Some("///foo"),
1827            file_name: None,
1828            file_stem: None,
1829            extension: None
1830            );
1831
1832         t!("///foo///bar",
1833            iter: ["\\", "foo", "bar"],
1834            has_root: true,
1835            is_absolute: false,
1836            parent: Some("///foo"),
1837            file_name: Some("bar"),
1838            file_stem: Some("bar"),
1839            extension: None
1840            );
1841
1842         t!("./.",
1843            iter: [".", "."],
1844            has_root: false,
1845            is_absolute: false,
1846            parent: Some("."),
1847            file_name: None,
1848            file_stem: None,
1849            extension: None
1850            );
1851
1852         t!("./.",
1853            iter: [".", "."],
1854            has_root: false,
1855            is_absolute: false,
1856            parent: Some("."),
1857            file_name: None,
1858            file_stem: None,
1859            extension: None
1860            );
1861
1862         t!("/..",
1863            iter: ["\\", ".."],
1864            has_root: true,
1865            is_absolute: false,
1866            parent: Some("/"),
1867            file_name: None,
1868            file_stem: None,
1869            extension: None
1870            );
1871
1872         t!("../",
1873            iter: ["..", "."],
1874            has_root: false,
1875            is_absolute: false,
1876            parent: Some(".."),
1877            file_name: None,
1878            file_stem: None,
1879            extension: None
1880            );
1881
1882         t!("foo/.",
1883            iter: ["foo", "."],
1884            has_root: false,
1885            is_absolute: false,
1886            parent: Some("foo"),
1887            file_name: None,
1888            file_stem: None,
1889            extension: None
1890            );
1891
1892         t!("foo/..",
1893            iter: ["foo", ".."],
1894            has_root: false,
1895            is_absolute: false,
1896            parent: Some("foo"),
1897            file_name: None,
1898            file_stem: None,
1899            extension: None
1900            );
1901
1902         t!("foo/./",
1903            iter: ["foo", ".", "."],
1904            has_root: false,
1905            is_absolute: false,
1906            parent: Some("foo/."),
1907            file_name: None,
1908            file_stem: None,
1909            extension: None
1910            );
1911
1912         t!("foo/./bar",
1913            iter: ["foo", ".", "bar"],
1914            has_root: false,
1915            is_absolute: false,
1916            parent: Some("foo/."),
1917            file_name: Some("bar"),
1918            file_stem: Some("bar"),
1919            extension: None
1920            );
1921
1922         t!("foo/../",
1923            iter: ["foo", "..", "."],
1924            has_root: false,
1925            is_absolute: false,
1926            parent: Some("foo/.."),
1927            file_name: None,
1928            file_stem: None,
1929            extension: None
1930            );
1931
1932         t!("foo/../bar",
1933            iter: ["foo", "..", "bar"],
1934            has_root: false,
1935            is_absolute: false,
1936            parent: Some("foo/.."),
1937            file_name: Some("bar"),
1938            file_stem: Some("bar"),
1939            extension: None
1940            );
1941
1942         t!("./a",
1943            iter: [".", "a"],
1944            has_root: false,
1945            is_absolute: false,
1946            parent: Some("."),
1947            file_name: Some("a"),
1948            file_stem: Some("a"),
1949            extension: None
1950            );
1951
1952         t!(".",
1953            iter: ["."],
1954            has_root: false,
1955            is_absolute: false,
1956            parent: None,
1957            file_name: None,
1958            file_stem: None,
1959            extension: None
1960            );
1961
1962         t!("./",
1963            iter: [".", "."],
1964            has_root: false,
1965            is_absolute: false,
1966            parent: Some("."),
1967            file_name: None,
1968            file_stem: None,
1969            extension: None
1970            );
1971
1972         t!("a/b",
1973            iter: ["a", "b"],
1974            has_root: false,
1975            is_absolute: false,
1976            parent: Some("a"),
1977            file_name: Some("b"),
1978            file_stem: Some("b"),
1979            extension: None
1980            );
1981
1982         t!("a//b",
1983            iter: ["a", "b"],
1984            has_root: false,
1985            is_absolute: false,
1986            parent: Some("a"),
1987            file_name: Some("b"),
1988            file_stem: Some("b"),
1989            extension: None
1990            );
1991
1992         t!("a/./b",
1993            iter: ["a", ".", "b"],
1994            has_root: false,
1995            is_absolute: false,
1996            parent: Some("a/."),
1997            file_name: Some("b"),
1998            file_stem: Some("b"),
1999            extension: None
2000            );
2001
2002         t!("a/b/c",
2003            iter: ["a", "b", "c"],
2004            has_root: false,
2005            is_absolute: false,
2006            parent: Some("a/b"),
2007            file_name: Some("c"),
2008            file_stem: Some("c"),
2009            extension: None);
2010
2011         t!("a\\b\\c",
2012            iter: ["a", "b", "c"],
2013            has_root: false,
2014            is_absolute: false,
2015            parent: Some("a\\b"),
2016            file_name: Some("c"),
2017            file_stem: Some("c"),
2018            extension: None
2019            );
2020
2021         t!("\\a",
2022            iter: ["\\", "a"],
2023            has_root: true,
2024            is_absolute: false,
2025            parent: Some("\\"),
2026            file_name: Some("a"),
2027            file_stem: Some("a"),
2028            extension: None
2029            );
2030
2031         t!("c:\\foo.txt",
2032            iter: ["c:", "\\", "foo.txt"],
2033            has_root: true,
2034            is_absolute: true,
2035            parent: Some("c:\\"),
2036            file_name: Some("foo.txt"),
2037            file_stem: Some("foo"),
2038            extension: Some("txt")
2039            );
2040
2041         t!("\\\\server\\share\\foo.txt",
2042            iter: ["\\\\server\\share", "\\", "foo.txt"],
2043            has_root: true,
2044            is_absolute: true,
2045            parent: Some("\\\\server\\share\\"),
2046            file_name: Some("foo.txt"),
2047            file_stem: Some("foo"),
2048            extension: Some("txt")
2049            );
2050
2051         t!("\\\\server\\share",
2052            iter: ["\\\\server\\share", "\\", "."],
2053            has_root: true,
2054            is_absolute: true,
2055            parent: None,
2056            file_name: None,
2057            file_stem: None,
2058            extension: None
2059            );
2060
2061         t!("\\\\server",
2062            iter: ["\\", "server"],
2063            has_root: true,
2064            is_absolute: false,
2065            parent: Some("\\"),
2066            file_name: Some("server"),
2067            file_stem: Some("server"),
2068            extension: None
2069            );
2070
2071         t!("\\\\?\\bar\\foo.txt",
2072            iter: ["\\\\?\\bar", "\\", "foo.txt"],
2073            has_root: true,
2074            is_absolute: true,
2075            parent: Some("\\\\?\\bar\\"),
2076            file_name: Some("foo.txt"),
2077            file_stem: Some("foo"),
2078            extension: Some("txt")
2079            );
2080
2081         t!("\\\\?\\bar",
2082            iter: ["\\\\?\\bar"],
2083            has_root: true,
2084            is_absolute: true,
2085            parent: None,
2086            file_name: None,
2087            file_stem: None,
2088            extension: None
2089            );
2090
2091         t!("\\\\?\\",
2092            iter: ["\\\\?\\"],
2093            has_root: true,
2094            is_absolute: true,
2095            parent: None,
2096            file_name: None,
2097            file_stem: None,
2098            extension: None
2099            );
2100
2101         t!("\\\\?\\UNC\\server\\share\\foo.txt",
2102            iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2103            has_root: true,
2104            is_absolute: true,
2105            parent: Some("\\\\?\\UNC\\server\\share\\"),
2106            file_name: Some("foo.txt"),
2107            file_stem: Some("foo"),
2108            extension: Some("txt")
2109            );
2110
2111         t!("\\\\?\\UNC\\server",
2112            iter: ["\\\\?\\UNC\\server"],
2113            has_root: true,
2114            is_absolute: true,
2115            parent: None,
2116            file_name: None,
2117            file_stem: None,
2118            extension: None
2119            );
2120
2121         t!("\\\\?\\UNC\\",
2122            iter: ["\\\\?\\UNC\\"],
2123            has_root: true,
2124            is_absolute: true,
2125            parent: None,
2126            file_name: None,
2127            file_stem: None,
2128            extension: None
2129            );
2130
2131         t!("\\\\?\\C:\\foo.txt",
2132            iter: ["\\\\?\\C:", "\\", "foo.txt"],
2133            has_root: true,
2134            is_absolute: true,
2135            parent: Some("\\\\?\\C:\\"),
2136            file_name: Some("foo.txt"),
2137            file_stem: Some("foo"),
2138            extension: Some("txt")
2139            );
2140
2141
2142         t!("\\\\?\\C:\\",
2143            iter: ["\\\\?\\C:", "\\", ""],
2144            has_root: true,
2145            is_absolute: true,
2146            parent: None,
2147            file_name: None,
2148            file_stem: None,
2149            extension: None
2150            );
2151
2152
2153         t!("\\\\?\\C:",
2154            iter: ["\\\\?\\C:"],
2155            has_root: true,
2156            is_absolute: true,
2157            parent: None,
2158            file_name: None,
2159            file_stem: None,
2160            extension: None
2161            );
2162
2163
2164         t!("\\\\?\\foo/bar",
2165            iter: ["\\\\?\\foo/bar"],
2166            has_root: true,
2167            is_absolute: true,
2168            parent: None,
2169            file_name: None,
2170            file_stem: None,
2171            extension: None
2172            );
2173
2174
2175         t!("\\\\?\\C:/foo",
2176            iter: ["\\\\?\\C:/foo"],
2177            has_root: true,
2178            is_absolute: true,
2179            parent: None,
2180            file_name: None,
2181            file_stem: None,
2182            extension: None
2183            );
2184
2185
2186         t!("\\\\.\\foo\\bar",
2187            iter: ["\\\\.\\foo", "\\", "bar"],
2188            has_root: true,
2189            is_absolute: true,
2190            parent: Some("\\\\.\\foo\\"),
2191            file_name: Some("bar"),
2192            file_stem: Some("bar"),
2193            extension: None
2194            );
2195
2196
2197         t!("\\\\.\\foo",
2198            iter: ["\\\\.\\foo", "\\", "."],
2199            has_root: true,
2200            is_absolute: true,
2201            parent: None,
2202            file_name: None,
2203            file_stem: None,
2204            extension: None
2205            );
2206
2207
2208         t!("\\\\.\\foo/bar",
2209            iter: ["\\\\.\\foo/bar", "\\", "."],
2210            has_root: true,
2211            is_absolute: true,
2212            parent: None,
2213            file_name: None,
2214            file_stem: None,
2215            extension: None
2216            );
2217
2218
2219         t!("\\\\.\\foo\\bar/baz",
2220            iter: ["\\\\.\\foo", "\\", "bar", "baz"],
2221            has_root: true,
2222            is_absolute: true,
2223            parent: Some("\\\\.\\foo\\bar"),
2224            file_name: Some("baz"),
2225            file_stem: Some("baz"),
2226            extension: None
2227            );
2228
2229
2230         t!("\\\\.\\",
2231            iter: ["\\\\.\\", "\\", "."],
2232            has_root: true,
2233            is_absolute: true,
2234            parent: None,
2235            file_name: None,
2236            file_stem: None,
2237            extension: None
2238            );
2239
2240         t!("\\\\?\\a\\b\\",
2241            iter: ["\\\\?\\a", "\\", "b", ""],
2242            has_root: true,
2243            is_absolute: true,
2244            parent: Some("\\\\?\\a\\b"),
2245            file_name: None,
2246            file_stem: None,
2247            extension: None
2248            );
2249     }
2250
2251     #[test]
2252     pub fn test_stem_ext() {
2253         t!("foo",
2254            file_stem: Some("foo"),
2255            extension: None
2256            );
2257
2258         t!("foo.",
2259            file_stem: Some("foo"),
2260            extension: Some("")
2261            );
2262
2263         t!(".foo",
2264            file_stem: Some(".foo"),
2265            extension: None
2266            );
2267
2268         t!("foo.txt",
2269            file_stem: Some("foo"),
2270            extension: Some("txt")
2271            );
2272
2273         t!("foo.bar.txt",
2274            file_stem: Some("foo.bar"),
2275            extension: Some("txt")
2276            );
2277
2278         t!("foo.bar.",
2279            file_stem: Some("foo.bar"),
2280            extension: Some("")
2281            );
2282
2283         t!(".",
2284            file_stem: None,
2285            extension: None
2286            );
2287
2288         t!("..",
2289            file_stem: None,
2290            extension: None
2291            );
2292
2293         t!("",
2294            file_stem: None,
2295            extension: None
2296            );
2297     }
2298
2299     #[test]
2300     pub fn test_push() {
2301         macro_rules! tp(
2302             ($path:expr, $push:expr, $expected:expr) => ( {
2303                 let mut actual = PathBuf::new($path);
2304                 actual.push($push);
2305                 assert!(actual.to_str() == Some($expected),
2306                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
2307                         $push, $path, $expected, actual.to_str().unwrap());
2308             });
2309         );
2310
2311         if cfg!(unix) {
2312             tp!("", "foo", "foo");
2313             tp!("foo", "bar", "foo/bar");
2314             tp!("foo/", "bar", "foo/bar");
2315             tp!("foo//", "bar", "foo//bar");
2316             tp!("foo/.", "bar", "foo/./bar");
2317             tp!("foo./.", "bar", "foo././bar");
2318             tp!("foo", "", "foo/");
2319             tp!("foo", ".", "foo/.");
2320             tp!("foo", "..", "foo/..");
2321             tp!("foo", "/", "/");
2322             tp!("/foo/bar", "/", "/");
2323             tp!("/foo/bar", "/baz", "/baz");
2324             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
2325         } else {
2326             tp!("", "foo", "foo");
2327             tp!("foo", "bar", r"foo\bar");
2328             tp!("foo/", "bar", r"foo/bar");
2329             tp!(r"foo\", "bar", r"foo\bar");
2330             tp!("foo//", "bar", r"foo//bar");
2331             tp!(r"foo\\", "bar", r"foo\\bar");
2332             tp!("foo/.", "bar", r"foo/.\bar");
2333             tp!("foo./.", "bar", r"foo./.\bar");
2334             tp!(r"foo\.", "bar", r"foo\.\bar");
2335             tp!(r"foo.\.", "bar", r"foo.\.\bar");
2336             tp!("foo", "", "foo\\");
2337             tp!("foo", ".", r"foo\.");
2338             tp!("foo", "..", r"foo\..");
2339             tp!("foo", "/", "/");
2340             tp!("foo", r"\", r"\");
2341             tp!("/foo/bar", "/", "/");
2342             tp!(r"\foo\bar", r"\", r"\");
2343             tp!("/foo/bar", "/baz", "/baz");
2344             tp!("/foo/bar", r"\baz", r"\baz");
2345             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
2346             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
2347
2348             tp!("c:\\", "windows", "c:\\windows");
2349             tp!("c:", "windows", "c:windows");
2350
2351             tp!("a\\b\\c", "d", "a\\b\\c\\d");
2352             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
2353             tp!("a\\b", "c\\d", "a\\b\\c\\d");
2354             tp!("a\\b", "\\c\\d", "\\c\\d");
2355             tp!("a\\b", ".", "a\\b\\.");
2356             tp!("a\\b", "..\\c", "a\\b\\..\\c");
2357             tp!("a\\b", "C:a.txt", "C:a.txt");
2358             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
2359             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
2360             tp!("C:\\a\\b\\c", "C:d", "C:d");
2361             tp!("C:a\\b\\c", "C:d", "C:d");
2362             tp!("C:", r"a\b\c", r"C:a\b\c");
2363             tp!("C:", r"..\a", r"C:..\a");
2364             tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
2365             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
2366             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
2367             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
2368             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
2369             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
2370             tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
2371             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
2372             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
2373
2374             // Note: modified from old path API
2375             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
2376
2377             tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
2378             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
2379             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
2380             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
2381             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
2382
2383             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
2384         }
2385     }
2386
2387     #[test]
2388     pub fn test_pop() {
2389         macro_rules! tp(
2390             ($path:expr, $expected:expr, $output:expr) => ( {
2391                 let mut actual = PathBuf::new($path);
2392                 let output = actual.pop();
2393                 assert!(actual.to_str() == Some($expected) && output == $output,
2394                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2395                         $path, $expected, $output,
2396                         actual.to_str().unwrap(), output);
2397             });
2398         );
2399
2400         tp!("", "", false);
2401         tp!("/", "/", false);
2402         tp!("foo", "foo", false);
2403         tp!(".", ".", false);
2404         tp!("/foo", "/", true);
2405         tp!("/foo/bar", "/foo", true);
2406         tp!("foo/bar", "foo", true);
2407         tp!("foo/.", "foo", true);
2408         tp!("foo//bar", "foo", true);
2409
2410         if cfg!(windows) {
2411             tp!("a\\b\\c", "a\\b", true);
2412             tp!("\\a", "\\", true);
2413             tp!("\\", "\\", false);
2414
2415             tp!("C:\\a\\b", "C:\\a", true);
2416             tp!("C:\\a", "C:\\", true);
2417             tp!("C:\\", "C:\\", false);
2418             tp!("C:a\\b", "C:a", true);
2419             tp!("C:a", "C:", true);
2420             tp!("C:", "C:", false);
2421             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
2422             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
2423             tp!("\\\\server\\share", "\\\\server\\share", false);
2424             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
2425             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
2426             tp!("\\\\?\\a", "\\\\?\\a", false);
2427             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
2428             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
2429             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
2430             tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
2431             tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
2432             tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
2433             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
2434             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
2435             tp!("\\\\.\\a", "\\\\.\\a", false);
2436
2437             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\b", true);
2438         }
2439     }
2440
2441     #[test]
2442     pub fn test_set_file_name() {
2443         macro_rules! tfn(
2444                 ($path:expr, $file:expr, $expected:expr) => ( {
2445                 let mut p = PathBuf::new($path);
2446                 p.set_file_name($file);
2447                 assert!(p.to_str() == Some($expected),
2448                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
2449                         $path, $file, $expected,
2450                         p.to_str().unwrap());
2451             });
2452         );
2453
2454         tfn!("foo", "foo", "foo");
2455         tfn!("foo", "bar", "bar");
2456         tfn!("foo", "", "");
2457         tfn!("", "foo", "foo");
2458         if cfg!(unix) {
2459             tfn!(".", "foo", "./foo");
2460             tfn!("foo/", "bar", "foo/bar");
2461             tfn!("foo/.", "bar", "foo/./bar");
2462             tfn!("..", "foo", "../foo");
2463             tfn!("foo/..", "bar", "foo/../bar");
2464             tfn!("/", "foo", "/foo");
2465         } else {
2466             tfn!(".", "foo", r".\foo");
2467             tfn!(r"foo\", "bar", r"foo\bar");
2468             tfn!(r"foo\.", "bar", r"foo\.\bar");
2469             tfn!("..", "foo", r"..\foo");
2470             tfn!(r"foo\..", "bar", r"foo\..\bar");
2471             tfn!(r"\", "foo", r"\foo");
2472         }
2473     }
2474
2475     #[test]
2476     pub fn test_set_extension() {
2477         macro_rules! tfe(
2478                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
2479                 let mut p = PathBuf::new($path);
2480                 let output = p.set_extension($ext);
2481                 assert!(p.to_str() == Some($expected) && output == $output,
2482                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2483                         $path, $ext, $expected, $output,
2484                         p.to_str().unwrap(), output);
2485             });
2486         );
2487
2488         tfe!("foo", "txt", "foo.txt", true);
2489         tfe!("foo.bar", "txt", "foo.txt", true);
2490         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
2491         tfe!(".test", "txt", ".test.txt", true);
2492         tfe!("foo.txt", "", "foo", true);
2493         tfe!("foo", "", "foo", true);
2494         tfe!("", "foo", "", false);
2495         tfe!(".", "foo", ".", false);
2496         tfe!("foo/", "bar", "foo/", false);
2497         tfe!("foo/.", "bar", "foo/.", false);
2498         tfe!("..", "foo", "..",  false);
2499         tfe!("foo/..", "bar", "foo/..", false);
2500         tfe!("/", "foo", "/", false);
2501     }
2502
2503     #[test]
2504     pub fn test_compare() {
2505         macro_rules! tc(
2506             ($path1:expr, $path2:expr, eq: $eq:expr,
2507              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
2508              relative_from: $relative_from:expr) => ({
2509                  let path1 = Path::new($path1);
2510                  let path2 = Path::new($path2);
2511
2512                  let eq = path1 == path2;
2513                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
2514                          $path1, $path2, $eq, eq);
2515
2516                  let starts_with = path1.starts_with(path2);
2517                  assert!(starts_with == $starts_with,
2518                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2519                          $starts_with, starts_with);
2520
2521                  let ends_with = path1.ends_with(path2);
2522                  assert!(ends_with == $ends_with,
2523                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2524                          $ends_with, ends_with);
2525
2526                  let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
2527                  let exp: Option<&str> = $relative_from;
2528                  assert!(relative_from == exp,
2529                          "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
2530                          exp, relative_from);
2531             });
2532         );
2533
2534         tc!("", "",
2535             eq: true,
2536             starts_with: true,
2537             ends_with: true,
2538             relative_from: Some("")
2539             );
2540
2541         tc!("foo", "",
2542             eq: false,
2543             starts_with: true,
2544             ends_with: true,
2545             relative_from: Some("foo")
2546             );
2547
2548         tc!("", "foo",
2549             eq: false,
2550             starts_with: false,
2551             ends_with: false,
2552             relative_from: None
2553             );
2554
2555         tc!("foo", "foo",
2556             eq: true,
2557             starts_with: true,
2558             ends_with: true,
2559             relative_from: Some("")
2560             );
2561
2562         tc!("foo/", "foo",
2563             eq: false,
2564             starts_with: true,
2565             ends_with: false,
2566             relative_from: Some(".")
2567             );
2568
2569         tc!("foo/bar", "foo",
2570             eq: false,
2571             starts_with: true,
2572             ends_with: false,
2573             relative_from: Some("bar")
2574             );
2575
2576         tc!("foo/bar/baz", "foo/bar",
2577             eq: false,
2578             starts_with: true,
2579             ends_with: false,
2580             relative_from: Some("baz")
2581             );
2582
2583         tc!("foo/bar", "foo/bar/baz",
2584             eq: false,
2585             starts_with: false,
2586             ends_with: false,
2587             relative_from: None
2588             );
2589
2590         tc!("./foo/bar/", ".",
2591             eq: false,
2592             starts_with: true,
2593             ends_with: true,
2594             relative_from: Some("foo/bar/")
2595             );
2596     }
2597 }