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