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