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