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