]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
a744407903b1ee9ad09abecf754e3710ca09a716
[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     /// Converts this `PathBuf` into a boxed `Path`.
1199     #[unstable(feature = "into_boxed_path", issue = "40380")]
1200     pub fn into_boxed_path(self) -> Box<Path> {
1201         unsafe { mem::transmute(self.inner.into_boxed_os_str()) }
1202     }
1203 }
1204
1205 #[stable(feature = "box_from_path", since = "1.17.0")]
1206 impl<'a> From<&'a Path> for Box<Path> {
1207     fn from(path: &'a Path) -> Box<Path> {
1208         let boxed: Box<OsStr> = path.inner.into();
1209         unsafe { mem::transmute(boxed) }
1210     }
1211 }
1212
1213 #[stable(feature = "path_buf_from_box", since = "1.17.0")]
1214 impl<'a> From<Box<Path>> for PathBuf {
1215     fn from(boxed: Box<Path>) -> PathBuf {
1216         boxed.into_path_buf()
1217     }
1218 }
1219
1220 #[stable(feature = "box_from_path_buf", since = "1.17.0")]
1221 impl Into<Box<Path>> for PathBuf {
1222     fn into(self) -> Box<Path> {
1223         self.into_boxed_path()
1224     }
1225 }
1226
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1229     fn from(s: &'a T) -> PathBuf {
1230         PathBuf::from(s.as_ref().to_os_string())
1231     }
1232 }
1233
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl From<OsString> for PathBuf {
1236     fn from(s: OsString) -> PathBuf {
1237         PathBuf { inner: s }
1238     }
1239 }
1240
1241 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1242 impl From<PathBuf> for OsString {
1243     fn from(path_buf : PathBuf) -> OsString {
1244         path_buf.inner
1245     }
1246 }
1247
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 impl From<String> for PathBuf {
1250     fn from(s: String) -> PathBuf {
1251         PathBuf::from(OsString::from(s))
1252     }
1253 }
1254
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1257     fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1258         let mut buf = PathBuf::new();
1259         buf.extend(iter);
1260         buf
1261     }
1262 }
1263
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1266     fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1267         for p in iter {
1268             self.push(p.as_ref())
1269         }
1270     }
1271 }
1272
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 impl fmt::Debug for PathBuf {
1275     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1276         fmt::Debug::fmt(&**self, formatter)
1277     }
1278 }
1279
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 impl ops::Deref for PathBuf {
1282     type Target = Path;
1283
1284     fn deref(&self) -> &Path {
1285         Path::new(&self.inner)
1286     }
1287 }
1288
1289 #[stable(feature = "rust1", since = "1.0.0")]
1290 impl Borrow<Path> for PathBuf {
1291     fn borrow(&self) -> &Path {
1292         self.deref()
1293     }
1294 }
1295
1296 #[stable(feature = "default_for_pathbuf", since = "1.16.0")]
1297 impl Default for PathBuf {
1298     fn default() -> Self {
1299         PathBuf::new()
1300     }
1301 }
1302
1303 #[stable(feature = "cow_from_path", since = "1.6.0")]
1304 impl<'a> From<&'a Path> for Cow<'a, Path> {
1305     #[inline]
1306     fn from(s: &'a Path) -> Cow<'a, Path> {
1307         Cow::Borrowed(s)
1308     }
1309 }
1310
1311 #[stable(feature = "cow_from_path", since = "1.6.0")]
1312 impl<'a> From<PathBuf> for Cow<'a, Path> {
1313     #[inline]
1314     fn from(s: PathBuf) -> Cow<'a, Path> {
1315         Cow::Owned(s)
1316     }
1317 }
1318
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl ToOwned for Path {
1321     type Owned = PathBuf;
1322     fn to_owned(&self) -> PathBuf {
1323         self.to_path_buf()
1324     }
1325 }
1326
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 impl cmp::PartialEq for PathBuf {
1329     fn eq(&self, other: &PathBuf) -> bool {
1330         self.components() == other.components()
1331     }
1332 }
1333
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl Hash for PathBuf {
1336     fn hash<H: Hasher>(&self, h: &mut H) {
1337         self.as_path().hash(h)
1338     }
1339 }
1340
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl cmp::Eq for PathBuf {}
1343
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 impl cmp::PartialOrd for PathBuf {
1346     fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1347         self.components().partial_cmp(other.components())
1348     }
1349 }
1350
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl cmp::Ord for PathBuf {
1353     fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1354         self.components().cmp(other.components())
1355     }
1356 }
1357
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl AsRef<OsStr> for PathBuf {
1360     fn as_ref(&self) -> &OsStr {
1361         &self.inner[..]
1362     }
1363 }
1364
1365 /// A slice of a path (akin to [`str`]).
1366 ///
1367 /// This type supports a number of operations for inspecting a path, including
1368 /// breaking the path into its components (separated by `/` or `\`, depending on
1369 /// the platform), extracting the file name, determining whether the path is
1370 /// absolute, and so on.
1371 ///
1372 /// This is an *unsized* type, meaning that it must always be used behind a
1373 /// pointer like `&` or [`Box`]. For an owned version of this type,
1374 /// see [`PathBuf`].
1375 ///
1376 /// [`str`]: ../primitive.str.html
1377 /// [`Box`]: ../boxed/struct.Box.html
1378 /// [`PathBuf`]: struct.PathBuf.html
1379 ///
1380 /// More details about the overall approach can be found in
1381 /// the module documentation.
1382 ///
1383 /// # Examples
1384 ///
1385 /// ```
1386 /// use std::path::Path;
1387 /// use std::ffi::OsStr;
1388 ///
1389 /// let path = Path::new("/tmp/foo/bar.txt");
1390 ///
1391 /// let parent = path.parent();
1392 /// assert_eq!(parent, Some(Path::new("/tmp/foo")));
1393 ///
1394 /// let file_stem = path.file_stem();
1395 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1396 ///
1397 /// let extension = path.extension();
1398 /// assert_eq!(extension, Some(OsStr::new("txt")));
1399 /// ```
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 pub struct Path {
1402     inner: OsStr,
1403 }
1404
1405 /// An error returned from the [`Path::strip_prefix`] method indicating that the
1406 /// prefix was not found in `self`.
1407 ///
1408 /// [`Path::strip_prefix`]: struct.Path.html#method.strip_prefix
1409 #[derive(Debug, Clone, PartialEq, Eq)]
1410 #[stable(since = "1.7.0", feature = "strip_prefix")]
1411 pub struct StripPrefixError(());
1412
1413 impl Path {
1414     // The following (private!) function allows construction of a path from a u8
1415     // slice, which is only safe when it is known to follow the OsStr encoding.
1416     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1417         Path::new(u8_slice_as_os_str(s))
1418     }
1419     // The following (private!) function reveals the byte encoding used for OsStr.
1420     fn as_u8_slice(&self) -> &[u8] {
1421         os_str_as_u8_slice(&self.inner)
1422     }
1423
1424     /// Directly wrap a string slice as a `Path` slice.
1425     ///
1426     /// This is a cost-free conversion.
1427     ///
1428     /// # Examples
1429     ///
1430     /// ```
1431     /// use std::path::Path;
1432     ///
1433     /// Path::new("foo.txt");
1434     /// ```
1435     ///
1436     /// You can create `Path`s from `String`s, or even other `Path`s:
1437     ///
1438     /// ```
1439     /// use std::path::Path;
1440     ///
1441     /// let string = String::from("foo.txt");
1442     /// let from_string = Path::new(&string);
1443     /// let from_path = Path::new(&from_string);
1444     /// assert_eq!(from_string, from_path);
1445     /// ```
1446     #[stable(feature = "rust1", since = "1.0.0")]
1447     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1448         unsafe { mem::transmute(s.as_ref()) }
1449     }
1450
1451     /// Yields the underlying [`OsStr`] slice.
1452     ///
1453     /// [`OsStr`]: ../ffi/struct.OsStr.html
1454     ///
1455     /// # Examples
1456     ///
1457     /// ```
1458     /// use std::path::Path;
1459     ///
1460     /// let os_str = Path::new("foo.txt").as_os_str();
1461     /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1462     /// ```
1463     #[stable(feature = "rust1", since = "1.0.0")]
1464     pub fn as_os_str(&self) -> &OsStr {
1465         &self.inner
1466     }
1467
1468     /// Yields a [`&str`] slice if the `Path` is valid unicode.
1469     ///
1470     /// This conversion may entail doing a check for UTF-8 validity.
1471     ///
1472     /// [`&str`]: ../primitive.str.html
1473     ///
1474     /// # Examples
1475     ///
1476     /// ```
1477     /// use std::path::Path;
1478     ///
1479     /// let path = Path::new("foo.txt");
1480     /// assert_eq!(path.to_str(), Some("foo.txt"));
1481     /// ```
1482     #[stable(feature = "rust1", since = "1.0.0")]
1483     pub fn to_str(&self) -> Option<&str> {
1484         self.inner.to_str()
1485     }
1486
1487     /// Converts a `Path` to a [`Cow<str>`].
1488     ///
1489     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1490     ///
1491     /// [`Cow<str>`]: ../borrow/enum.Cow.html
1492     ///
1493     /// # Examples
1494     ///
1495     /// Calling `to_string_lossy` on a `Path` with valid unicode:
1496     ///
1497     /// ```
1498     /// use std::path::Path;
1499     ///
1500     /// let path = Path::new("foo.txt");
1501     /// assert_eq!(path.to_string_lossy(), "foo.txt");
1502     /// ```
1503     ///
1504     /// Had `os_str` contained invalid unicode, the `to_string_lossy` call might
1505     /// have returned `"fo�.txt"`.
1506     #[stable(feature = "rust1", since = "1.0.0")]
1507     pub fn to_string_lossy(&self) -> Cow<str> {
1508         self.inner.to_string_lossy()
1509     }
1510
1511     /// Converts a `Path` to an owned [`PathBuf`].
1512     ///
1513     /// [`PathBuf`]: struct.PathBuf.html
1514     ///
1515     /// # Examples
1516     ///
1517     /// ```
1518     /// use std::path::Path;
1519     ///
1520     /// let path_buf = Path::new("foo.txt").to_path_buf();
1521     /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1522     /// ```
1523     #[stable(feature = "rust1", since = "1.0.0")]
1524     pub fn to_path_buf(&self) -> PathBuf {
1525         PathBuf::from(self.inner.to_os_string())
1526     }
1527
1528     /// A path is *absolute* if it is independent of the current directory.
1529     ///
1530     /// * On Unix, a path is absolute if it starts with the root, so
1531     /// `is_absolute` and `has_root` are equivalent.
1532     ///
1533     /// * On Windows, a path is absolute if it has a prefix and starts with the
1534     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1535     ///
1536     /// # Examples
1537     ///
1538     /// ```
1539     /// use std::path::Path;
1540     ///
1541     /// assert!(!Path::new("foo.txt").is_absolute());
1542     /// ```
1543     #[stable(feature = "rust1", since = "1.0.0")]
1544     #[allow(deprecated)]
1545     pub fn is_absolute(&self) -> bool {
1546         // FIXME: Remove target_os = "redox" and allow Redox prefixes
1547         self.has_root() && (cfg!(unix) || cfg!(target_os = "redox") || self.prefix().is_some())
1548     }
1549
1550     /// A path is *relative* if it is not absolute.
1551     ///
1552     /// # Examples
1553     ///
1554     /// ```
1555     /// use std::path::Path;
1556     ///
1557     /// assert!(Path::new("foo.txt").is_relative());
1558     /// ```
1559     #[stable(feature = "rust1", since = "1.0.0")]
1560     pub fn is_relative(&self) -> bool {
1561         !self.is_absolute()
1562     }
1563
1564     fn prefix(&self) -> Option<Prefix> {
1565         self.components().prefix
1566     }
1567
1568     /// A path has a root if the body of the path begins with the directory separator.
1569     ///
1570     /// * On Unix, a path has a root if it begins with `/`.
1571     ///
1572     /// * On Windows, a path has a root if it:
1573     ///     * has no prefix and begins with a separator, e.g. `\\windows`
1574     ///     * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1575     ///     * has any non-disk prefix, e.g. `\\server\share`
1576     ///
1577     /// # Examples
1578     ///
1579     /// ```
1580     /// use std::path::Path;
1581     ///
1582     /// assert!(Path::new("/etc/passwd").has_root());
1583     /// ```
1584     #[stable(feature = "rust1", since = "1.0.0")]
1585     pub fn has_root(&self) -> bool {
1586         self.components().has_root()
1587     }
1588
1589     /// The path without its final component, if any.
1590     ///
1591     /// Returns [`None`] if the path terminates in a root or prefix.
1592     ///
1593     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1594     ///
1595     /// # Examples
1596     ///
1597     /// ```
1598     /// use std::path::Path;
1599     ///
1600     /// let path = Path::new("/foo/bar");
1601     /// let parent = path.parent().unwrap();
1602     /// assert_eq!(parent, Path::new("/foo"));
1603     ///
1604     /// let grand_parent = parent.parent().unwrap();
1605     /// assert_eq!(grand_parent, Path::new("/"));
1606     /// assert_eq!(grand_parent.parent(), None);
1607     /// ```
1608     #[stable(feature = "rust1", since = "1.0.0")]
1609     pub fn parent(&self) -> Option<&Path> {
1610         let mut comps = self.components();
1611         let comp = comps.next_back();
1612         comp.and_then(|p| {
1613             match p {
1614                 Component::Normal(_) |
1615                 Component::CurDir |
1616                 Component::ParentDir => Some(comps.as_path()),
1617                 _ => None,
1618             }
1619         })
1620     }
1621
1622     /// The final component of the path, if it is a normal file.
1623     ///
1624     /// If the path terminates in `..`, `file_name` will return [`None`].
1625     ///
1626     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1627     ///
1628     /// # Examples
1629     ///
1630     /// ```
1631     /// use std::path::Path;
1632     /// use std::ffi::OsStr;
1633     ///
1634     /// let path = Path::new("foo.txt");
1635     /// let os_str = OsStr::new("foo.txt");
1636     ///
1637     /// assert_eq!(Some(os_str), path.file_name());
1638     /// ```
1639     ///
1640     /// # Other examples
1641     ///
1642     /// ```
1643     /// use std::path::Path;
1644     /// use std::ffi::OsStr;
1645     ///
1646     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1647     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1648     /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1649     /// ```
1650     #[stable(feature = "rust1", since = "1.0.0")]
1651     pub fn file_name(&self) -> Option<&OsStr> {
1652         self.components().next_back().and_then(|p| {
1653             match p {
1654                 Component::Normal(p) => Some(p.as_ref()),
1655                 _ => None,
1656             }
1657         })
1658     }
1659
1660     /// Returns a path that, when joined onto `base`, yields `self`.
1661     ///
1662     /// # Errors
1663     ///
1664     /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1665     /// returns `false`), returns [`Err`].
1666     ///
1667     /// [`starts_with`]: #method.starts_with
1668     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1669     ///
1670     /// # Examples
1671     ///
1672     /// ```
1673     /// use std::path::Path;
1674     ///
1675     /// let path = Path::new("/test/haha/foo.txt");
1676     ///
1677     /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1678     /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1679     /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1680     /// ```
1681     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1682     pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1683                                        -> Result<&'a Path, StripPrefixError>
1684         where P: AsRef<Path>
1685     {
1686         self._strip_prefix(base.as_ref())
1687     }
1688
1689     fn _strip_prefix<'a>(&'a self, base: &'a Path)
1690                          -> Result<&'a Path, StripPrefixError> {
1691         iter_after(self.components(), base.components())
1692             .map(|c| c.as_path())
1693             .ok_or(StripPrefixError(()))
1694     }
1695
1696     /// Determines whether `base` is a prefix of `self`.
1697     ///
1698     /// Only considers whole path components to match.
1699     ///
1700     /// # Examples
1701     ///
1702     /// ```
1703     /// use std::path::Path;
1704     ///
1705     /// let path = Path::new("/etc/passwd");
1706     ///
1707     /// assert!(path.starts_with("/etc"));
1708     ///
1709     /// assert!(!path.starts_with("/e"));
1710     /// ```
1711     #[stable(feature = "rust1", since = "1.0.0")]
1712     pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1713         self._starts_with(base.as_ref())
1714     }
1715
1716     fn _starts_with(&self, base: &Path) -> bool {
1717         iter_after(self.components(), base.components()).is_some()
1718     }
1719
1720     /// Determines whether `child` is a suffix of `self`.
1721     ///
1722     /// Only considers whole path components to match.
1723     ///
1724     /// # Examples
1725     ///
1726     /// ```
1727     /// use std::path::Path;
1728     ///
1729     /// let path = Path::new("/etc/passwd");
1730     ///
1731     /// assert!(path.ends_with("passwd"));
1732     /// ```
1733     #[stable(feature = "rust1", since = "1.0.0")]
1734     pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1735         self._ends_with(child.as_ref())
1736     }
1737
1738     fn _ends_with(&self, child: &Path) -> bool {
1739         iter_after(self.components().rev(), child.components().rev()).is_some()
1740     }
1741
1742     /// Extracts the stem (non-extension) portion of [`self.file_name`].
1743     ///
1744     /// [`self.file_name`]: struct.Path.html#method.file_name
1745     ///
1746     /// The stem is:
1747     ///
1748     /// * [`None`], if there is no file name;
1749     /// * The entire file name if there is no embedded `.`;
1750     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1751     /// * Otherwise, the portion of the file name before the final `.`
1752     ///
1753     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1754     ///
1755     /// # Examples
1756     ///
1757     /// ```
1758     /// use std::path::Path;
1759     ///
1760     /// let path = Path::new("foo.rs");
1761     ///
1762     /// assert_eq!("foo", path.file_stem().unwrap());
1763     /// ```
1764     #[stable(feature = "rust1", since = "1.0.0")]
1765     pub fn file_stem(&self) -> Option<&OsStr> {
1766         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1767     }
1768
1769     /// Extracts the extension of [`self.file_name`], if possible.
1770     ///
1771     /// The extension is:
1772     ///
1773     /// * [`None`], if there is no file name;
1774     /// * [`None`], if there is no embedded `.`;
1775     /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1776     /// * Otherwise, the portion of the file name after the final `.`
1777     ///
1778     /// [`self.file_name`]: struct.Path.html#method.file_name
1779     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1780     ///
1781     /// # Examples
1782     ///
1783     /// ```
1784     /// use std::path::Path;
1785     ///
1786     /// let path = Path::new("foo.rs");
1787     ///
1788     /// assert_eq!("rs", path.extension().unwrap());
1789     /// ```
1790     #[stable(feature = "rust1", since = "1.0.0")]
1791     pub fn extension(&self) -> Option<&OsStr> {
1792         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1793     }
1794
1795     /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1796     ///
1797     /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1798     ///
1799     /// [`PathBuf`]: struct.PathBuf.html
1800     /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1801     ///
1802     /// # Examples
1803     ///
1804     /// ```
1805     /// use std::path::{Path, PathBuf};
1806     ///
1807     /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1808     /// ```
1809     #[stable(feature = "rust1", since = "1.0.0")]
1810     pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1811         self._join(path.as_ref())
1812     }
1813
1814     fn _join(&self, path: &Path) -> PathBuf {
1815         let mut buf = self.to_path_buf();
1816         buf.push(path);
1817         buf
1818     }
1819
1820     /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1821     ///
1822     /// See [`PathBuf::set_file_name`] for more details.
1823     ///
1824     /// [`PathBuf`]: struct.PathBuf.html
1825     /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1826     ///
1827     /// # Examples
1828     ///
1829     /// ```
1830     /// use std::path::{Path, PathBuf};
1831     ///
1832     /// let path = Path::new("/tmp/foo.txt");
1833     /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1834     /// ```
1835     #[stable(feature = "rust1", since = "1.0.0")]
1836     pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1837         self._with_file_name(file_name.as_ref())
1838     }
1839
1840     fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1841         let mut buf = self.to_path_buf();
1842         buf.set_file_name(file_name);
1843         buf
1844     }
1845
1846     /// Creates an owned [`PathBuf`] like `self` but with the given extension.
1847     ///
1848     /// See [`PathBuf::set_extension`] for more details.
1849     ///
1850     /// [`PathBuf`]: struct.PathBuf.html
1851     /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
1852     ///
1853     /// # Examples
1854     ///
1855     /// ```
1856     /// use std::path::{Path, PathBuf};
1857     ///
1858     /// let path = Path::new("foo.rs");
1859     /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1860     /// ```
1861     #[stable(feature = "rust1", since = "1.0.0")]
1862     pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1863         self._with_extension(extension.as_ref())
1864     }
1865
1866     fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1867         let mut buf = self.to_path_buf();
1868         buf.set_extension(extension);
1869         buf
1870     }
1871
1872     /// Produce an iterator over the components of the path.
1873     ///
1874     /// # Examples
1875     ///
1876     /// ```
1877     /// use std::path::{Path, Component};
1878     /// use std::ffi::OsStr;
1879     ///
1880     /// let mut components = Path::new("/tmp/foo.txt").components();
1881     ///
1882     /// assert_eq!(components.next(), Some(Component::RootDir));
1883     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1884     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1885     /// assert_eq!(components.next(), None)
1886     /// ```
1887     #[stable(feature = "rust1", since = "1.0.0")]
1888     pub fn components(&self) -> Components {
1889         let prefix = parse_prefix(self.as_os_str());
1890         Components {
1891             path: self.as_u8_slice(),
1892             prefix: prefix,
1893             has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1894             front: State::Prefix,
1895             back: State::Body,
1896         }
1897     }
1898
1899     /// Produce an iterator over the path's components viewed as [`OsStr`] slices.
1900     ///
1901     /// [`OsStr`]: ../ffi/struct.OsStr.html
1902     ///
1903     /// # Examples
1904     ///
1905     /// ```
1906     /// use std::path::{self, Path};
1907     /// use std::ffi::OsStr;
1908     ///
1909     /// let mut it = Path::new("/tmp/foo.txt").iter();
1910     /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1911     /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1912     /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1913     /// assert_eq!(it.next(), None)
1914     /// ```
1915     #[stable(feature = "rust1", since = "1.0.0")]
1916     pub fn iter(&self) -> Iter {
1917         Iter { inner: self.components() }
1918     }
1919
1920     /// Returns an object that implements [`Display`] for safely printing paths
1921     /// that may contain non-Unicode data.
1922     ///
1923     /// [`Display`]: ../fmt/trait.Display.html
1924     ///
1925     /// # Examples
1926     ///
1927     /// ```
1928     /// use std::path::Path;
1929     ///
1930     /// let path = Path::new("/tmp/foo.rs");
1931     ///
1932     /// println!("{}", path.display());
1933     /// ```
1934     #[stable(feature = "rust1", since = "1.0.0")]
1935     pub fn display(&self) -> Display {
1936         Display { path: self }
1937     }
1938
1939     /// Query the file system to get information about a file, directory, etc.
1940     ///
1941     /// This function will traverse symbolic links to query information about the
1942     /// destination file.
1943     ///
1944     /// This is an alias to [`fs::metadata`].
1945     ///
1946     /// [`fs::metadata`]: ../fs/fn.metadata.html
1947     ///
1948     /// # Examples
1949     ///
1950     /// ```no_run
1951     /// use std::path::Path;
1952     ///
1953     /// let path = Path::new("/Minas/tirith");
1954     /// let metadata = path.metadata().expect("metadata call failed");
1955     /// println!("{:?}", metadata.file_type());
1956     /// ```
1957     #[stable(feature = "path_ext", since = "1.5.0")]
1958     pub fn metadata(&self) -> io::Result<fs::Metadata> {
1959         fs::metadata(self)
1960     }
1961
1962     /// Query the metadata about a file without following symlinks.
1963     ///
1964     /// This is an alias to [`fs::symlink_metadata`].
1965     ///
1966     /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
1967     ///
1968     /// # Examples
1969     ///
1970     /// ```no_run
1971     /// use std::path::Path;
1972     ///
1973     /// let path = Path::new("/Minas/tirith");
1974     /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
1975     /// println!("{:?}", metadata.file_type());
1976     /// ```
1977     #[stable(feature = "path_ext", since = "1.5.0")]
1978     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1979         fs::symlink_metadata(self)
1980     }
1981
1982     /// Returns the canonical form of the path with all intermediate components
1983     /// normalized and symbolic links resolved.
1984     ///
1985     /// This is an alias to [`fs::canonicalize`].
1986     ///
1987     /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
1988     ///
1989     /// # Examples
1990     ///
1991     /// ```no_run
1992     /// use std::path::{Path, PathBuf};
1993     ///
1994     /// let path = Path::new("/foo/test/../test/bar.rs");
1995     /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
1996     /// ```
1997     #[stable(feature = "path_ext", since = "1.5.0")]
1998     pub fn canonicalize(&self) -> io::Result<PathBuf> {
1999         fs::canonicalize(self)
2000     }
2001
2002     /// Reads a symbolic link, returning the file that the link points to.
2003     ///
2004     /// This is an alias to [`fs::read_link`].
2005     ///
2006     /// [`fs::read_link`]: ../fs/fn.read_link.html
2007     ///
2008     /// # Examples
2009     ///
2010     /// ```no_run
2011     /// use std::path::Path;
2012     ///
2013     /// let path = Path::new("/laputa/sky_castle.rs");
2014     /// let path_link = path.read_link().expect("read_link call failed");
2015     /// ```
2016     #[stable(feature = "path_ext", since = "1.5.0")]
2017     pub fn read_link(&self) -> io::Result<PathBuf> {
2018         fs::read_link(self)
2019     }
2020
2021     /// Returns an iterator over the entries within a directory.
2022     ///
2023     /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2024     /// errors may be encountered after an iterator is initially constructed.
2025     ///
2026     /// This is an alias to [`fs::read_dir`].
2027     ///
2028     /// [`io::Result`]: ../io/type.Result.html
2029     /// [`DirEntry`]: ../fs/struct.DirEntry.html
2030     /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2031     ///
2032     /// # Examples
2033     ///
2034     /// ```no_run
2035     /// use std::path::Path;
2036     ///
2037     /// let path = Path::new("/laputa");
2038     /// for entry in path.read_dir().expect("read_dir call failed") {
2039     ///     if let Ok(entry) = entry {
2040     ///         println!("{:?}", entry.path());
2041     ///     }
2042     /// }
2043     /// ```
2044     #[stable(feature = "path_ext", since = "1.5.0")]
2045     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2046         fs::read_dir(self)
2047     }
2048
2049     /// Returns whether the path points at an existing entity.
2050     ///
2051     /// This function will traverse symbolic links to query information about the
2052     /// destination file. In case of broken symbolic links this will return `false`.
2053     ///
2054     /// # Examples
2055     ///
2056     /// ```no_run
2057     /// use std::path::Path;
2058     /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2059     /// ```
2060     #[stable(feature = "path_ext", since = "1.5.0")]
2061     pub fn exists(&self) -> bool {
2062         fs::metadata(self).is_ok()
2063     }
2064
2065     /// Returns whether the path is pointing at a regular file.
2066     ///
2067     /// This function will traverse symbolic links to query information about the
2068     /// destination file. In case of broken symbolic links this will return `false`.
2069     ///
2070     /// # Examples
2071     ///
2072     /// ```no_run
2073     /// use std::path::Path;
2074     /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2075     /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2076     /// ```
2077     #[stable(feature = "path_ext", since = "1.5.0")]
2078     pub fn is_file(&self) -> bool {
2079         fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2080     }
2081
2082     /// Returns whether the path is pointing at a directory.
2083     ///
2084     /// This function will traverse symbolic links to query information about the
2085     /// destination file. In case of broken symbolic links this will return `false`.
2086     ///
2087     /// # Examples
2088     ///
2089     /// ```no_run
2090     /// use std::path::Path;
2091     /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2092     /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2093     /// ```
2094     #[stable(feature = "path_ext", since = "1.5.0")]
2095     pub fn is_dir(&self) -> bool {
2096         fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2097     }
2098
2099     /// Converts a `Box<Path>` into a `PathBuf` without copying or allocating.
2100     #[unstable(feature = "into_boxed_path", issue = "40380")]
2101     pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2102         let inner: Box<OsStr> = unsafe { mem::transmute(self) };
2103         PathBuf { inner: OsString::from(inner) }
2104     }
2105 }
2106
2107 #[stable(feature = "rust1", since = "1.0.0")]
2108 impl AsRef<OsStr> for Path {
2109     fn as_ref(&self) -> &OsStr {
2110         &self.inner
2111     }
2112 }
2113
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl fmt::Debug for Path {
2116     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2117         self.inner.fmt(formatter)
2118     }
2119 }
2120
2121 /// Helper struct for safely printing paths with `format!()` and `{}`
2122 #[stable(feature = "rust1", since = "1.0.0")]
2123 pub struct Display<'a> {
2124     path: &'a Path,
2125 }
2126
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl<'a> fmt::Debug for Display<'a> {
2129     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2130         fmt::Debug::fmt(&self.path.to_string_lossy(), f)
2131     }
2132 }
2133
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 impl<'a> fmt::Display for Display<'a> {
2136     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2137         fmt::Display::fmt(&self.path.to_string_lossy(), f)
2138     }
2139 }
2140
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 impl cmp::PartialEq for Path {
2143     fn eq(&self, other: &Path) -> bool {
2144         self.components().eq(other.components())
2145     }
2146 }
2147
2148 #[stable(feature = "rust1", since = "1.0.0")]
2149 impl Hash for Path {
2150     fn hash<H: Hasher>(&self, h: &mut H) {
2151         for component in self.components() {
2152             component.hash(h);
2153         }
2154     }
2155 }
2156
2157 #[stable(feature = "rust1", since = "1.0.0")]
2158 impl cmp::Eq for Path {}
2159
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl cmp::PartialOrd for Path {
2162     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2163         self.components().partial_cmp(other.components())
2164     }
2165 }
2166
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 impl cmp::Ord for Path {
2169     fn cmp(&self, other: &Path) -> cmp::Ordering {
2170         self.components().cmp(other.components())
2171     }
2172 }
2173
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 impl AsRef<Path> for Path {
2176     fn as_ref(&self) -> &Path {
2177         self
2178     }
2179 }
2180
2181 #[stable(feature = "rust1", since = "1.0.0")]
2182 impl AsRef<Path> for OsStr {
2183     fn as_ref(&self) -> &Path {
2184         Path::new(self)
2185     }
2186 }
2187
2188 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2189 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2190     fn as_ref(&self) -> &Path {
2191         Path::new(self)
2192     }
2193 }
2194
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 impl AsRef<Path> for OsString {
2197     fn as_ref(&self) -> &Path {
2198         Path::new(self)
2199     }
2200 }
2201
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 impl AsRef<Path> for str {
2204     fn as_ref(&self) -> &Path {
2205         Path::new(self)
2206     }
2207 }
2208
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 impl AsRef<Path> for String {
2211     fn as_ref(&self) -> &Path {
2212         Path::new(self)
2213     }
2214 }
2215
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 impl AsRef<Path> for PathBuf {
2218     fn as_ref(&self) -> &Path {
2219         self
2220     }
2221 }
2222
2223 #[stable(feature = "path_into_iter", since = "1.6.0")]
2224 impl<'a> IntoIterator for &'a PathBuf {
2225     type Item = &'a OsStr;
2226     type IntoIter = Iter<'a>;
2227     fn into_iter(self) -> Iter<'a> { self.iter() }
2228 }
2229
2230 #[stable(feature = "path_into_iter", since = "1.6.0")]
2231 impl<'a> IntoIterator for &'a Path {
2232     type Item = &'a OsStr;
2233     type IntoIter = Iter<'a>;
2234     fn into_iter(self) -> Iter<'a> { self.iter() }
2235 }
2236
2237 macro_rules! impl_cmp {
2238     ($lhs:ty, $rhs: ty) => {
2239         #[stable(feature = "partialeq_path", since = "1.6.0")]
2240         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2241             #[inline]
2242             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2243         }
2244
2245         #[stable(feature = "partialeq_path", since = "1.6.0")]
2246         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2247             #[inline]
2248             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2249         }
2250
2251         #[stable(feature = "cmp_path", since = "1.8.0")]
2252         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2253             #[inline]
2254             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2255                 <Path as PartialOrd>::partial_cmp(self, other)
2256             }
2257         }
2258
2259         #[stable(feature = "cmp_path", since = "1.8.0")]
2260         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2261             #[inline]
2262             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2263                 <Path as PartialOrd>::partial_cmp(self, other)
2264             }
2265         }
2266     }
2267 }
2268
2269 impl_cmp!(PathBuf, Path);
2270 impl_cmp!(PathBuf, &'a Path);
2271 impl_cmp!(Cow<'a, Path>, Path);
2272 impl_cmp!(Cow<'a, Path>, &'b Path);
2273 impl_cmp!(Cow<'a, Path>, PathBuf);
2274
2275 macro_rules! impl_cmp_os_str {
2276     ($lhs:ty, $rhs: ty) => {
2277         #[stable(feature = "cmp_path", since = "1.8.0")]
2278         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2279             #[inline]
2280             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2281         }
2282
2283         #[stable(feature = "cmp_path", since = "1.8.0")]
2284         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2285             #[inline]
2286             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2287         }
2288
2289         #[stable(feature = "cmp_path", since = "1.8.0")]
2290         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2291             #[inline]
2292             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2293                 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2294             }
2295         }
2296
2297         #[stable(feature = "cmp_path", since = "1.8.0")]
2298         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2299             #[inline]
2300             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2301                 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2302             }
2303         }
2304     }
2305 }
2306
2307 impl_cmp_os_str!(PathBuf, OsStr);
2308 impl_cmp_os_str!(PathBuf, &'a OsStr);
2309 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2310 impl_cmp_os_str!(PathBuf, OsString);
2311 impl_cmp_os_str!(Path, OsStr);
2312 impl_cmp_os_str!(Path, &'a OsStr);
2313 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2314 impl_cmp_os_str!(Path, OsString);
2315 impl_cmp_os_str!(&'a Path, OsStr);
2316 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2317 impl_cmp_os_str!(&'a Path, OsString);
2318 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2319 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2320 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2321
2322 #[stable(since = "1.7.0", feature = "strip_prefix")]
2323 impl fmt::Display for StripPrefixError {
2324     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2325         self.description().fmt(f)
2326     }
2327 }
2328
2329 #[stable(since = "1.7.0", feature = "strip_prefix")]
2330 impl Error for StripPrefixError {
2331     fn description(&self) -> &str { "prefix not found" }
2332 }
2333
2334 #[cfg(test)]
2335 mod tests {
2336     use super::*;
2337
2338     macro_rules! t(
2339         ($path:expr, iter: $iter:expr) => (
2340             {
2341                 let path = Path::new($path);
2342
2343                 // Forward iteration
2344                 let comps = path.iter()
2345                     .map(|p| p.to_string_lossy().into_owned())
2346                     .collect::<Vec<String>>();
2347                 let exp: &[&str] = &$iter;
2348                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2349                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2350                         exps, comps);
2351
2352                 // Reverse iteration
2353                 let comps = Path::new($path).iter().rev()
2354                     .map(|p| p.to_string_lossy().into_owned())
2355                     .collect::<Vec<String>>();
2356                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2357                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2358                         exps, comps);
2359             }
2360         );
2361
2362         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2363             {
2364                 let path = Path::new($path);
2365
2366                 let act_root = path.has_root();
2367                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2368                         $has_root, act_root);
2369
2370                 let act_abs = path.is_absolute();
2371                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2372                         $is_absolute, act_abs);
2373             }
2374         );
2375
2376         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2377             {
2378                 let path = Path::new($path);
2379
2380                 let parent = path.parent().map(|p| p.to_str().unwrap());
2381                 let exp_parent: Option<&str> = $parent;
2382                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2383                         exp_parent, parent);
2384
2385                 let file = path.file_name().map(|p| p.to_str().unwrap());
2386                 let exp_file: Option<&str> = $file;
2387                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2388                         exp_file, file);
2389             }
2390         );
2391
2392         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2393             {
2394                 let path = Path::new($path);
2395
2396                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2397                 let exp_stem: Option<&str> = $file_stem;
2398                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2399                         exp_stem, stem);
2400
2401                 let ext = path.extension().map(|p| p.to_str().unwrap());
2402                 let exp_ext: Option<&str> = $extension;
2403                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2404                         exp_ext, ext);
2405             }
2406         );
2407
2408         ($path:expr, iter: $iter:expr,
2409                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2410                      parent: $parent:expr, file_name: $file:expr,
2411                      file_stem: $file_stem:expr, extension: $extension:expr) => (
2412             {
2413                 t!($path, iter: $iter);
2414                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2415                 t!($path, parent: $parent, file_name: $file);
2416                 t!($path, file_stem: $file_stem, extension: $extension);
2417             }
2418         );
2419     );
2420
2421     #[test]
2422     fn into() {
2423         use borrow::Cow;
2424
2425         let static_path = Path::new("/home/foo");
2426         let static_cow_path: Cow<'static, Path> = static_path.into();
2427         let pathbuf = PathBuf::from("/home/foo");
2428
2429         {
2430             let path: &Path = &pathbuf;
2431             let borrowed_cow_path: Cow<Path> = path.into();
2432
2433             assert_eq!(static_cow_path, borrowed_cow_path);
2434         }
2435
2436         let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2437
2438         assert_eq!(static_cow_path, owned_cow_path);
2439     }
2440
2441     #[test]
2442     #[cfg(unix)]
2443     pub fn test_decompositions_unix() {
2444         t!("",
2445            iter: [],
2446            has_root: false,
2447            is_absolute: false,
2448            parent: None,
2449            file_name: None,
2450            file_stem: None,
2451            extension: None
2452            );
2453
2454         t!("foo",
2455            iter: ["foo"],
2456            has_root: false,
2457            is_absolute: false,
2458            parent: Some(""),
2459            file_name: Some("foo"),
2460            file_stem: Some("foo"),
2461            extension: None
2462            );
2463
2464         t!("/",
2465            iter: ["/"],
2466            has_root: true,
2467            is_absolute: true,
2468            parent: None,
2469            file_name: None,
2470            file_stem: None,
2471            extension: None
2472            );
2473
2474         t!("/foo",
2475            iter: ["/", "foo"],
2476            has_root: true,
2477            is_absolute: true,
2478            parent: Some("/"),
2479            file_name: Some("foo"),
2480            file_stem: Some("foo"),
2481            extension: None
2482            );
2483
2484         t!("foo/",
2485            iter: ["foo"],
2486            has_root: false,
2487            is_absolute: false,
2488            parent: Some(""),
2489            file_name: Some("foo"),
2490            file_stem: Some("foo"),
2491            extension: None
2492            );
2493
2494         t!("/foo/",
2495            iter: ["/", "foo"],
2496            has_root: true,
2497            is_absolute: true,
2498            parent: Some("/"),
2499            file_name: Some("foo"),
2500            file_stem: Some("foo"),
2501            extension: None
2502            );
2503
2504         t!("foo/bar",
2505            iter: ["foo", "bar"],
2506            has_root: false,
2507            is_absolute: false,
2508            parent: Some("foo"),
2509            file_name: Some("bar"),
2510            file_stem: Some("bar"),
2511            extension: None
2512            );
2513
2514         t!("/foo/bar",
2515            iter: ["/", "foo", "bar"],
2516            has_root: true,
2517            is_absolute: true,
2518            parent: Some("/foo"),
2519            file_name: Some("bar"),
2520            file_stem: Some("bar"),
2521            extension: None
2522            );
2523
2524         t!("///foo///",
2525            iter: ["/", "foo"],
2526            has_root: true,
2527            is_absolute: true,
2528            parent: Some("/"),
2529            file_name: Some("foo"),
2530            file_stem: Some("foo"),
2531            extension: None
2532            );
2533
2534         t!("///foo///bar",
2535            iter: ["/", "foo", "bar"],
2536            has_root: true,
2537            is_absolute: true,
2538            parent: Some("///foo"),
2539            file_name: Some("bar"),
2540            file_stem: Some("bar"),
2541            extension: None
2542            );
2543
2544         t!("./.",
2545            iter: ["."],
2546            has_root: false,
2547            is_absolute: false,
2548            parent: Some(""),
2549            file_name: None,
2550            file_stem: None,
2551            extension: None
2552            );
2553
2554         t!("/..",
2555            iter: ["/", ".."],
2556            has_root: true,
2557            is_absolute: true,
2558            parent: Some("/"),
2559            file_name: None,
2560            file_stem: None,
2561            extension: None
2562            );
2563
2564         t!("../",
2565            iter: [".."],
2566            has_root: false,
2567            is_absolute: false,
2568            parent: Some(""),
2569            file_name: None,
2570            file_stem: None,
2571            extension: None
2572            );
2573
2574         t!("foo/.",
2575            iter: ["foo"],
2576            has_root: false,
2577            is_absolute: false,
2578            parent: Some(""),
2579            file_name: Some("foo"),
2580            file_stem: Some("foo"),
2581            extension: None
2582            );
2583
2584         t!("foo/..",
2585            iter: ["foo", ".."],
2586            has_root: false,
2587            is_absolute: false,
2588            parent: Some("foo"),
2589            file_name: None,
2590            file_stem: None,
2591            extension: None
2592            );
2593
2594         t!("foo/./",
2595            iter: ["foo"],
2596            has_root: false,
2597            is_absolute: false,
2598            parent: Some(""),
2599            file_name: Some("foo"),
2600            file_stem: Some("foo"),
2601            extension: None
2602            );
2603
2604         t!("foo/./bar",
2605            iter: ["foo", "bar"],
2606            has_root: false,
2607            is_absolute: false,
2608            parent: Some("foo"),
2609            file_name: Some("bar"),
2610            file_stem: Some("bar"),
2611            extension: None
2612            );
2613
2614         t!("foo/../",
2615            iter: ["foo", ".."],
2616            has_root: false,
2617            is_absolute: false,
2618            parent: Some("foo"),
2619            file_name: None,
2620            file_stem: None,
2621            extension: None
2622            );
2623
2624         t!("foo/../bar",
2625            iter: ["foo", "..", "bar"],
2626            has_root: false,
2627            is_absolute: false,
2628            parent: Some("foo/.."),
2629            file_name: Some("bar"),
2630            file_stem: Some("bar"),
2631            extension: None
2632            );
2633
2634         t!("./a",
2635            iter: [".", "a"],
2636            has_root: false,
2637            is_absolute: false,
2638            parent: Some("."),
2639            file_name: Some("a"),
2640            file_stem: Some("a"),
2641            extension: None
2642            );
2643
2644         t!(".",
2645            iter: ["."],
2646            has_root: false,
2647            is_absolute: false,
2648            parent: Some(""),
2649            file_name: None,
2650            file_stem: None,
2651            extension: None
2652            );
2653
2654         t!("./",
2655            iter: ["."],
2656            has_root: false,
2657            is_absolute: false,
2658            parent: Some(""),
2659            file_name: None,
2660            file_stem: None,
2661            extension: None
2662            );
2663
2664         t!("a/b",
2665            iter: ["a", "b"],
2666            has_root: false,
2667            is_absolute: false,
2668            parent: Some("a"),
2669            file_name: Some("b"),
2670            file_stem: Some("b"),
2671            extension: None
2672            );
2673
2674         t!("a//b",
2675            iter: ["a", "b"],
2676            has_root: false,
2677            is_absolute: false,
2678            parent: Some("a"),
2679            file_name: Some("b"),
2680            file_stem: Some("b"),
2681            extension: None
2682            );
2683
2684         t!("a/./b",
2685            iter: ["a", "b"],
2686            has_root: false,
2687            is_absolute: false,
2688            parent: Some("a"),
2689            file_name: Some("b"),
2690            file_stem: Some("b"),
2691            extension: None
2692            );
2693
2694         t!("a/b/c",
2695            iter: ["a", "b", "c"],
2696            has_root: false,
2697            is_absolute: false,
2698            parent: Some("a/b"),
2699            file_name: Some("c"),
2700            file_stem: Some("c"),
2701            extension: None
2702            );
2703
2704         t!(".foo",
2705            iter: [".foo"],
2706            has_root: false,
2707            is_absolute: false,
2708            parent: Some(""),
2709            file_name: Some(".foo"),
2710            file_stem: Some(".foo"),
2711            extension: None
2712            );
2713     }
2714
2715     #[test]
2716     #[cfg(windows)]
2717     pub fn test_decompositions_windows() {
2718         t!("",
2719            iter: [],
2720            has_root: false,
2721            is_absolute: false,
2722            parent: None,
2723            file_name: None,
2724            file_stem: None,
2725            extension: None
2726            );
2727
2728         t!("foo",
2729            iter: ["foo"],
2730            has_root: false,
2731            is_absolute: false,
2732            parent: Some(""),
2733            file_name: Some("foo"),
2734            file_stem: Some("foo"),
2735            extension: None
2736            );
2737
2738         t!("/",
2739            iter: ["\\"],
2740            has_root: true,
2741            is_absolute: false,
2742            parent: None,
2743            file_name: None,
2744            file_stem: None,
2745            extension: None
2746            );
2747
2748         t!("\\",
2749            iter: ["\\"],
2750            has_root: true,
2751            is_absolute: false,
2752            parent: None,
2753            file_name: None,
2754            file_stem: None,
2755            extension: None
2756            );
2757
2758         t!("c:",
2759            iter: ["c:"],
2760            has_root: false,
2761            is_absolute: false,
2762            parent: None,
2763            file_name: None,
2764            file_stem: None,
2765            extension: None
2766            );
2767
2768         t!("c:\\",
2769            iter: ["c:", "\\"],
2770            has_root: true,
2771            is_absolute: true,
2772            parent: None,
2773            file_name: None,
2774            file_stem: None,
2775            extension: None
2776            );
2777
2778         t!("c:/",
2779            iter: ["c:", "\\"],
2780            has_root: true,
2781            is_absolute: true,
2782            parent: None,
2783            file_name: None,
2784            file_stem: None,
2785            extension: None
2786            );
2787
2788         t!("/foo",
2789            iter: ["\\", "foo"],
2790            has_root: true,
2791            is_absolute: false,
2792            parent: Some("/"),
2793            file_name: Some("foo"),
2794            file_stem: Some("foo"),
2795            extension: None
2796            );
2797
2798         t!("foo/",
2799            iter: ["foo"],
2800            has_root: false,
2801            is_absolute: false,
2802            parent: Some(""),
2803            file_name: Some("foo"),
2804            file_stem: Some("foo"),
2805            extension: None
2806            );
2807
2808         t!("/foo/",
2809            iter: ["\\", "foo"],
2810            has_root: true,
2811            is_absolute: false,
2812            parent: Some("/"),
2813            file_name: Some("foo"),
2814            file_stem: Some("foo"),
2815            extension: None
2816            );
2817
2818         t!("foo/bar",
2819            iter: ["foo", "bar"],
2820            has_root: false,
2821            is_absolute: false,
2822            parent: Some("foo"),
2823            file_name: Some("bar"),
2824            file_stem: Some("bar"),
2825            extension: None
2826            );
2827
2828         t!("/foo/bar",
2829            iter: ["\\", "foo", "bar"],
2830            has_root: true,
2831            is_absolute: false,
2832            parent: Some("/foo"),
2833            file_name: Some("bar"),
2834            file_stem: Some("bar"),
2835            extension: None
2836            );
2837
2838         t!("///foo///",
2839            iter: ["\\", "foo"],
2840            has_root: true,
2841            is_absolute: false,
2842            parent: Some("/"),
2843            file_name: Some("foo"),
2844            file_stem: Some("foo"),
2845            extension: None
2846            );
2847
2848         t!("///foo///bar",
2849            iter: ["\\", "foo", "bar"],
2850            has_root: true,
2851            is_absolute: false,
2852            parent: Some("///foo"),
2853            file_name: Some("bar"),
2854            file_stem: Some("bar"),
2855            extension: None
2856            );
2857
2858         t!("./.",
2859            iter: ["."],
2860            has_root: false,
2861            is_absolute: false,
2862            parent: Some(""),
2863            file_name: None,
2864            file_stem: None,
2865            extension: None
2866            );
2867
2868         t!("/..",
2869            iter: ["\\", ".."],
2870            has_root: true,
2871            is_absolute: false,
2872            parent: Some("/"),
2873            file_name: None,
2874            file_stem: None,
2875            extension: None
2876            );
2877
2878         t!("../",
2879            iter: [".."],
2880            has_root: false,
2881            is_absolute: false,
2882            parent: Some(""),
2883            file_name: None,
2884            file_stem: None,
2885            extension: None
2886            );
2887
2888         t!("foo/.",
2889            iter: ["foo"],
2890            has_root: false,
2891            is_absolute: false,
2892            parent: Some(""),
2893            file_name: Some("foo"),
2894            file_stem: Some("foo"),
2895            extension: None
2896            );
2897
2898         t!("foo/..",
2899            iter: ["foo", ".."],
2900            has_root: false,
2901            is_absolute: false,
2902            parent: Some("foo"),
2903            file_name: None,
2904            file_stem: None,
2905            extension: None
2906            );
2907
2908         t!("foo/./",
2909            iter: ["foo"],
2910            has_root: false,
2911            is_absolute: false,
2912            parent: Some(""),
2913            file_name: Some("foo"),
2914            file_stem: Some("foo"),
2915            extension: None
2916            );
2917
2918         t!("foo/./bar",
2919            iter: ["foo", "bar"],
2920            has_root: false,
2921            is_absolute: false,
2922            parent: Some("foo"),
2923            file_name: Some("bar"),
2924            file_stem: Some("bar"),
2925            extension: None
2926            );
2927
2928         t!("foo/../",
2929            iter: ["foo", ".."],
2930            has_root: false,
2931            is_absolute: false,
2932            parent: Some("foo"),
2933            file_name: None,
2934            file_stem: None,
2935            extension: None
2936            );
2937
2938         t!("foo/../bar",
2939            iter: ["foo", "..", "bar"],
2940            has_root: false,
2941            is_absolute: false,
2942            parent: Some("foo/.."),
2943            file_name: Some("bar"),
2944            file_stem: Some("bar"),
2945            extension: None
2946            );
2947
2948         t!("./a",
2949            iter: [".", "a"],
2950            has_root: false,
2951            is_absolute: false,
2952            parent: Some("."),
2953            file_name: Some("a"),
2954            file_stem: Some("a"),
2955            extension: None
2956            );
2957
2958         t!(".",
2959            iter: ["."],
2960            has_root: false,
2961            is_absolute: false,
2962            parent: Some(""),
2963            file_name: None,
2964            file_stem: None,
2965            extension: None
2966            );
2967
2968         t!("./",
2969            iter: ["."],
2970            has_root: false,
2971            is_absolute: false,
2972            parent: Some(""),
2973            file_name: None,
2974            file_stem: None,
2975            extension: None
2976            );
2977
2978         t!("a/b",
2979            iter: ["a", "b"],
2980            has_root: false,
2981            is_absolute: false,
2982            parent: Some("a"),
2983            file_name: Some("b"),
2984            file_stem: Some("b"),
2985            extension: None
2986            );
2987
2988         t!("a//b",
2989            iter: ["a", "b"],
2990            has_root: false,
2991            is_absolute: false,
2992            parent: Some("a"),
2993            file_name: Some("b"),
2994            file_stem: Some("b"),
2995            extension: None
2996            );
2997
2998         t!("a/./b",
2999            iter: ["a", "b"],
3000            has_root: false,
3001            is_absolute: false,
3002            parent: Some("a"),
3003            file_name: Some("b"),
3004            file_stem: Some("b"),
3005            extension: None
3006            );
3007
3008         t!("a/b/c",
3009            iter: ["a", "b", "c"],
3010            has_root: false,
3011            is_absolute: false,
3012            parent: Some("a/b"),
3013            file_name: Some("c"),
3014            file_stem: Some("c"),
3015            extension: None);
3016
3017         t!("a\\b\\c",
3018            iter: ["a", "b", "c"],
3019            has_root: false,
3020            is_absolute: false,
3021            parent: Some("a\\b"),
3022            file_name: Some("c"),
3023            file_stem: Some("c"),
3024            extension: None
3025            );
3026
3027         t!("\\a",
3028            iter: ["\\", "a"],
3029            has_root: true,
3030            is_absolute: false,
3031            parent: Some("\\"),
3032            file_name: Some("a"),
3033            file_stem: Some("a"),
3034            extension: None
3035            );
3036
3037         t!("c:\\foo.txt",
3038            iter: ["c:", "\\", "foo.txt"],
3039            has_root: true,
3040            is_absolute: true,
3041            parent: Some("c:\\"),
3042            file_name: Some("foo.txt"),
3043            file_stem: Some("foo"),
3044            extension: Some("txt")
3045            );
3046
3047         t!("\\\\server\\share\\foo.txt",
3048            iter: ["\\\\server\\share", "\\", "foo.txt"],
3049            has_root: true,
3050            is_absolute: true,
3051            parent: Some("\\\\server\\share\\"),
3052            file_name: Some("foo.txt"),
3053            file_stem: Some("foo"),
3054            extension: Some("txt")
3055            );
3056
3057         t!("\\\\server\\share",
3058            iter: ["\\\\server\\share", "\\"],
3059            has_root: true,
3060            is_absolute: true,
3061            parent: None,
3062            file_name: None,
3063            file_stem: None,
3064            extension: None
3065            );
3066
3067         t!("\\\\server",
3068            iter: ["\\", "server"],
3069            has_root: true,
3070            is_absolute: false,
3071            parent: Some("\\"),
3072            file_name: Some("server"),
3073            file_stem: Some("server"),
3074            extension: None
3075            );
3076
3077         t!("\\\\?\\bar\\foo.txt",
3078            iter: ["\\\\?\\bar", "\\", "foo.txt"],
3079            has_root: true,
3080            is_absolute: true,
3081            parent: Some("\\\\?\\bar\\"),
3082            file_name: Some("foo.txt"),
3083            file_stem: Some("foo"),
3084            extension: Some("txt")
3085            );
3086
3087         t!("\\\\?\\bar",
3088            iter: ["\\\\?\\bar"],
3089            has_root: true,
3090            is_absolute: true,
3091            parent: None,
3092            file_name: None,
3093            file_stem: None,
3094            extension: None
3095            );
3096
3097         t!("\\\\?\\",
3098            iter: ["\\\\?\\"],
3099            has_root: true,
3100            is_absolute: true,
3101            parent: None,
3102            file_name: None,
3103            file_stem: None,
3104            extension: None
3105            );
3106
3107         t!("\\\\?\\UNC\\server\\share\\foo.txt",
3108            iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3109            has_root: true,
3110            is_absolute: true,
3111            parent: Some("\\\\?\\UNC\\server\\share\\"),
3112            file_name: Some("foo.txt"),
3113            file_stem: Some("foo"),
3114            extension: Some("txt")
3115            );
3116
3117         t!("\\\\?\\UNC\\server",
3118            iter: ["\\\\?\\UNC\\server"],
3119            has_root: true,
3120            is_absolute: true,
3121            parent: None,
3122            file_name: None,
3123            file_stem: None,
3124            extension: None
3125            );
3126
3127         t!("\\\\?\\UNC\\",
3128            iter: ["\\\\?\\UNC\\"],
3129            has_root: true,
3130            is_absolute: true,
3131            parent: None,
3132            file_name: None,
3133            file_stem: None,
3134            extension: None
3135            );
3136
3137         t!("\\\\?\\C:\\foo.txt",
3138            iter: ["\\\\?\\C:", "\\", "foo.txt"],
3139            has_root: true,
3140            is_absolute: true,
3141            parent: Some("\\\\?\\C:\\"),
3142            file_name: Some("foo.txt"),
3143            file_stem: Some("foo"),
3144            extension: Some("txt")
3145            );
3146
3147
3148         t!("\\\\?\\C:\\",
3149            iter: ["\\\\?\\C:", "\\"],
3150            has_root: true,
3151            is_absolute: true,
3152            parent: None,
3153            file_name: None,
3154            file_stem: None,
3155            extension: None
3156            );
3157
3158
3159         t!("\\\\?\\C:",
3160            iter: ["\\\\?\\C:"],
3161            has_root: true,
3162            is_absolute: true,
3163            parent: None,
3164            file_name: None,
3165            file_stem: None,
3166            extension: None
3167            );
3168
3169
3170         t!("\\\\?\\foo/bar",
3171            iter: ["\\\\?\\foo/bar"],
3172            has_root: true,
3173            is_absolute: true,
3174            parent: None,
3175            file_name: None,
3176            file_stem: None,
3177            extension: None
3178            );
3179
3180
3181         t!("\\\\?\\C:/foo",
3182            iter: ["\\\\?\\C:/foo"],
3183            has_root: true,
3184            is_absolute: true,
3185            parent: None,
3186            file_name: None,
3187            file_stem: None,
3188            extension: None
3189            );
3190
3191
3192         t!("\\\\.\\foo\\bar",
3193            iter: ["\\\\.\\foo", "\\", "bar"],
3194            has_root: true,
3195            is_absolute: true,
3196            parent: Some("\\\\.\\foo\\"),
3197            file_name: Some("bar"),
3198            file_stem: Some("bar"),
3199            extension: None
3200            );
3201
3202
3203         t!("\\\\.\\foo",
3204            iter: ["\\\\.\\foo", "\\"],
3205            has_root: true,
3206            is_absolute: true,
3207            parent: None,
3208            file_name: None,
3209            file_stem: None,
3210            extension: None
3211            );
3212
3213
3214         t!("\\\\.\\foo/bar",
3215            iter: ["\\\\.\\foo/bar", "\\"],
3216            has_root: true,
3217            is_absolute: true,
3218            parent: None,
3219            file_name: None,
3220            file_stem: None,
3221            extension: None
3222            );
3223
3224
3225         t!("\\\\.\\foo\\bar/baz",
3226            iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3227            has_root: true,
3228            is_absolute: true,
3229            parent: Some("\\\\.\\foo\\bar"),
3230            file_name: Some("baz"),
3231            file_stem: Some("baz"),
3232            extension: None
3233            );
3234
3235
3236         t!("\\\\.\\",
3237            iter: ["\\\\.\\", "\\"],
3238            has_root: true,
3239            is_absolute: true,
3240            parent: None,
3241            file_name: None,
3242            file_stem: None,
3243            extension: None
3244            );
3245
3246         t!("\\\\?\\a\\b\\",
3247            iter: ["\\\\?\\a", "\\", "b"],
3248            has_root: true,
3249            is_absolute: true,
3250            parent: Some("\\\\?\\a\\"),
3251            file_name: Some("b"),
3252            file_stem: Some("b"),
3253            extension: None
3254            );
3255     }
3256
3257     #[test]
3258     pub fn test_stem_ext() {
3259         t!("foo",
3260            file_stem: Some("foo"),
3261            extension: None
3262            );
3263
3264         t!("foo.",
3265            file_stem: Some("foo"),
3266            extension: Some("")
3267            );
3268
3269         t!(".foo",
3270            file_stem: Some(".foo"),
3271            extension: None
3272            );
3273
3274         t!("foo.txt",
3275            file_stem: Some("foo"),
3276            extension: Some("txt")
3277            );
3278
3279         t!("foo.bar.txt",
3280            file_stem: Some("foo.bar"),
3281            extension: Some("txt")
3282            );
3283
3284         t!("foo.bar.",
3285            file_stem: Some("foo.bar"),
3286            extension: Some("")
3287            );
3288
3289         t!(".",
3290            file_stem: None,
3291            extension: None
3292            );
3293
3294         t!("..",
3295            file_stem: None,
3296            extension: None
3297            );
3298
3299         t!("",
3300            file_stem: None,
3301            extension: None
3302            );
3303     }
3304
3305     #[test]
3306     pub fn test_push() {
3307         macro_rules! tp(
3308             ($path:expr, $push:expr, $expected:expr) => ( {
3309                 let mut actual = PathBuf::from($path);
3310                 actual.push($push);
3311                 assert!(actual.to_str() == Some($expected),
3312                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3313                         $push, $path, $expected, actual.to_str().unwrap());
3314             });
3315         );
3316
3317         if cfg!(unix) {
3318             tp!("", "foo", "foo");
3319             tp!("foo", "bar", "foo/bar");
3320             tp!("foo/", "bar", "foo/bar");
3321             tp!("foo//", "bar", "foo//bar");
3322             tp!("foo/.", "bar", "foo/./bar");
3323             tp!("foo./.", "bar", "foo././bar");
3324             tp!("foo", "", "foo/");
3325             tp!("foo", ".", "foo/.");
3326             tp!("foo", "..", "foo/..");
3327             tp!("foo", "/", "/");
3328             tp!("/foo/bar", "/", "/");
3329             tp!("/foo/bar", "/baz", "/baz");
3330             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3331         } else {
3332             tp!("", "foo", "foo");
3333             tp!("foo", "bar", r"foo\bar");
3334             tp!("foo/", "bar", r"foo/bar");
3335             tp!(r"foo\", "bar", r"foo\bar");
3336             tp!("foo//", "bar", r"foo//bar");
3337             tp!(r"foo\\", "bar", r"foo\\bar");
3338             tp!("foo/.", "bar", r"foo/.\bar");
3339             tp!("foo./.", "bar", r"foo./.\bar");
3340             tp!(r"foo\.", "bar", r"foo\.\bar");
3341             tp!(r"foo.\.", "bar", r"foo.\.\bar");
3342             tp!("foo", "", "foo\\");
3343             tp!("foo", ".", r"foo\.");
3344             tp!("foo", "..", r"foo\..");
3345             tp!("foo", "/", "/");
3346             tp!("foo", r"\", r"\");
3347             tp!("/foo/bar", "/", "/");
3348             tp!(r"\foo\bar", r"\", r"\");
3349             tp!("/foo/bar", "/baz", "/baz");
3350             tp!("/foo/bar", r"\baz", r"\baz");
3351             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3352             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3353
3354             tp!("c:\\", "windows", "c:\\windows");
3355             tp!("c:", "windows", "c:windows");
3356
3357             tp!("a\\b\\c", "d", "a\\b\\c\\d");
3358             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3359             tp!("a\\b", "c\\d", "a\\b\\c\\d");
3360             tp!("a\\b", "\\c\\d", "\\c\\d");
3361             tp!("a\\b", ".", "a\\b\\.");
3362             tp!("a\\b", "..\\c", "a\\b\\..\\c");
3363             tp!("a\\b", "C:a.txt", "C:a.txt");
3364             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3365             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3366             tp!("C:\\a\\b\\c", "C:d", "C:d");
3367             tp!("C:a\\b\\c", "C:d", "C:d");
3368             tp!("C:", r"a\b\c", r"C:a\b\c");
3369             tp!("C:", r"..\a", r"C:..\a");
3370             tp!("\\\\server\\share\\foo",
3371                 "bar",
3372                 "\\\\server\\share\\foo\\bar");
3373             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3374             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3375             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3376             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3377             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3378             tp!("\\\\?\\UNC\\server\\share\\foo",
3379                 "bar",
3380                 "\\\\?\\UNC\\server\\share\\foo\\bar");
3381             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3382             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3383
3384             // Note: modified from old path API
3385             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3386
3387             tp!("C:\\a",
3388                 "\\\\?\\UNC\\server\\share",
3389                 "\\\\?\\UNC\\server\\share");
3390             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3391             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3392             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3393             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3394
3395             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3396         }
3397     }
3398
3399     #[test]
3400     pub fn test_pop() {
3401         macro_rules! tp(
3402             ($path:expr, $expected:expr, $output:expr) => ( {
3403                 let mut actual = PathBuf::from($path);
3404                 let output = actual.pop();
3405                 assert!(actual.to_str() == Some($expected) && output == $output,
3406                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3407                         $path, $expected, $output,
3408                         actual.to_str().unwrap(), output);
3409             });
3410         );
3411
3412         tp!("", "", false);
3413         tp!("/", "/", false);
3414         tp!("foo", "", true);
3415         tp!(".", "", true);
3416         tp!("/foo", "/", true);
3417         tp!("/foo/bar", "/foo", true);
3418         tp!("foo/bar", "foo", true);
3419         tp!("foo/.", "", true);
3420         tp!("foo//bar", "foo", true);
3421
3422         if cfg!(windows) {
3423             tp!("a\\b\\c", "a\\b", true);
3424             tp!("\\a", "\\", true);
3425             tp!("\\", "\\", false);
3426
3427             tp!("C:\\a\\b", "C:\\a", true);
3428             tp!("C:\\a", "C:\\", true);
3429             tp!("C:\\", "C:\\", false);
3430             tp!("C:a\\b", "C:a", true);
3431             tp!("C:a", "C:", true);
3432             tp!("C:", "C:", false);
3433             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3434             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3435             tp!("\\\\server\\share", "\\\\server\\share", false);
3436             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3437             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3438             tp!("\\\\?\\a", "\\\\?\\a", false);
3439             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3440             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3441             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3442             tp!("\\\\?\\UNC\\server\\share\\a\\b",
3443                 "\\\\?\\UNC\\server\\share\\a",
3444                 true);
3445             tp!("\\\\?\\UNC\\server\\share\\a",
3446                 "\\\\?\\UNC\\server\\share\\",
3447                 true);
3448             tp!("\\\\?\\UNC\\server\\share",
3449                 "\\\\?\\UNC\\server\\share",
3450                 false);
3451             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3452             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3453             tp!("\\\\.\\a", "\\\\.\\a", false);
3454
3455             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3456         }
3457     }
3458
3459     #[test]
3460     pub fn test_set_file_name() {
3461         macro_rules! tfn(
3462                 ($path:expr, $file:expr, $expected:expr) => ( {
3463                 let mut p = PathBuf::from($path);
3464                 p.set_file_name($file);
3465                 assert!(p.to_str() == Some($expected),
3466                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3467                         $path, $file, $expected,
3468                         p.to_str().unwrap());
3469             });
3470         );
3471
3472         tfn!("foo", "foo", "foo");
3473         tfn!("foo", "bar", "bar");
3474         tfn!("foo", "", "");
3475         tfn!("", "foo", "foo");
3476         if cfg!(unix) {
3477             tfn!(".", "foo", "./foo");
3478             tfn!("foo/", "bar", "bar");
3479             tfn!("foo/.", "bar", "bar");
3480             tfn!("..", "foo", "../foo");
3481             tfn!("foo/..", "bar", "foo/../bar");
3482             tfn!("/", "foo", "/foo");
3483         } else {
3484             tfn!(".", "foo", r".\foo");
3485             tfn!(r"foo\", "bar", r"bar");
3486             tfn!(r"foo\.", "bar", r"bar");
3487             tfn!("..", "foo", r"..\foo");
3488             tfn!(r"foo\..", "bar", r"foo\..\bar");
3489             tfn!(r"\", "foo", r"\foo");
3490         }
3491     }
3492
3493     #[test]
3494     pub fn test_set_extension() {
3495         macro_rules! tfe(
3496                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3497                 let mut p = PathBuf::from($path);
3498                 let output = p.set_extension($ext);
3499                 assert!(p.to_str() == Some($expected) && output == $output,
3500                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3501                         $path, $ext, $expected, $output,
3502                         p.to_str().unwrap(), output);
3503             });
3504         );
3505
3506         tfe!("foo", "txt", "foo.txt", true);
3507         tfe!("foo.bar", "txt", "foo.txt", true);
3508         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3509         tfe!(".test", "txt", ".test.txt", true);
3510         tfe!("foo.txt", "", "foo", true);
3511         tfe!("foo", "", "foo", true);
3512         tfe!("", "foo", "", false);
3513         tfe!(".", "foo", ".", false);
3514         tfe!("foo/", "bar", "foo.bar", true);
3515         tfe!("foo/.", "bar", "foo.bar", true);
3516         tfe!("..", "foo", "..", false);
3517         tfe!("foo/..", "bar", "foo/..", false);
3518         tfe!("/", "foo", "/", false);
3519     }
3520
3521     #[test]
3522     fn test_eq_recievers() {
3523         use borrow::Cow;
3524
3525         let borrowed: &Path = Path::new("foo/bar");
3526         let mut owned: PathBuf = PathBuf::new();
3527         owned.push("foo");
3528         owned.push("bar");
3529         let borrowed_cow: Cow<Path> = borrowed.into();
3530         let owned_cow: Cow<Path> = owned.clone().into();
3531
3532         macro_rules! t {
3533             ($($current:expr),+) => {
3534                 $(
3535                     assert_eq!($current, borrowed);
3536                     assert_eq!($current, owned);
3537                     assert_eq!($current, borrowed_cow);
3538                     assert_eq!($current, owned_cow);
3539                 )+
3540             }
3541         }
3542
3543         t!(borrowed, owned, borrowed_cow, owned_cow);
3544     }
3545
3546     #[test]
3547     pub fn test_compare() {
3548         use hash::{Hash, Hasher};
3549         use collections::hash_map::DefaultHasher;
3550
3551         fn hash<T: Hash>(t: T) -> u64 {
3552             let mut s = DefaultHasher::new();
3553             t.hash(&mut s);
3554             s.finish()
3555         }
3556
3557         macro_rules! tc(
3558             ($path1:expr, $path2:expr, eq: $eq:expr,
3559              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3560              relative_from: $relative_from:expr) => ({
3561                  let path1 = Path::new($path1);
3562                  let path2 = Path::new($path2);
3563
3564                  let eq = path1 == path2;
3565                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3566                          $path1, $path2, $eq, eq);
3567                  assert!($eq == (hash(path1) == hash(path2)),
3568                          "{:?} == {:?}, expected {:?}, got {} and {}",
3569                          $path1, $path2, $eq, hash(path1), hash(path2));
3570
3571                  let starts_with = path1.starts_with(path2);
3572                  assert!(starts_with == $starts_with,
3573                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3574                          $starts_with, starts_with);
3575
3576                  let ends_with = path1.ends_with(path2);
3577                  assert!(ends_with == $ends_with,
3578                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3579                          $ends_with, ends_with);
3580
3581                  let relative_from = path1.strip_prefix(path2)
3582                                           .map(|p| p.to_str().unwrap())
3583                                           .ok();
3584                  let exp: Option<&str> = $relative_from;
3585                  assert!(relative_from == exp,
3586                          "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3587                          $path1, $path2, exp, relative_from);
3588             });
3589         );
3590
3591         tc!("", "",
3592             eq: true,
3593             starts_with: true,
3594             ends_with: true,
3595             relative_from: Some("")
3596             );
3597
3598         tc!("foo", "",
3599             eq: false,
3600             starts_with: true,
3601             ends_with: true,
3602             relative_from: Some("foo")
3603             );
3604
3605         tc!("", "foo",
3606             eq: false,
3607             starts_with: false,
3608             ends_with: false,
3609             relative_from: None
3610             );
3611
3612         tc!("foo", "foo",
3613             eq: true,
3614             starts_with: true,
3615             ends_with: true,
3616             relative_from: Some("")
3617             );
3618
3619         tc!("foo/", "foo",
3620             eq: true,
3621             starts_with: true,
3622             ends_with: true,
3623             relative_from: Some("")
3624             );
3625
3626         tc!("foo/bar", "foo",
3627             eq: false,
3628             starts_with: true,
3629             ends_with: false,
3630             relative_from: Some("bar")
3631             );
3632
3633         tc!("foo/bar/baz", "foo/bar",
3634             eq: false,
3635             starts_with: true,
3636             ends_with: false,
3637             relative_from: Some("baz")
3638             );
3639
3640         tc!("foo/bar", "foo/bar/baz",
3641             eq: false,
3642             starts_with: false,
3643             ends_with: false,
3644             relative_from: None
3645             );
3646
3647         tc!("./foo/bar/", ".",
3648             eq: false,
3649             starts_with: true,
3650             ends_with: false,
3651             relative_from: Some("foo/bar")
3652             );
3653
3654         if cfg!(windows) {
3655             tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3656                 r"c:\src\rust\cargo-test\test",
3657                 eq: false,
3658                 starts_with: true,
3659                 ends_with: false,
3660                 relative_from: Some("Cargo.toml")
3661                 );
3662
3663             tc!(r"c:\foo", r"C:\foo",
3664                 eq: true,
3665                 starts_with: true,
3666                 ends_with: true,
3667                 relative_from: Some("")
3668                 );
3669         }
3670     }
3671
3672     #[test]
3673     fn test_components_debug() {
3674         let path = Path::new("/tmp");
3675
3676         let mut components = path.components();
3677
3678         let expected = "Components([RootDir, Normal(\"tmp\")])";
3679         let actual = format!("{:?}", components);
3680         assert_eq!(expected, actual);
3681
3682         let _ = components.next().unwrap();
3683         let expected = "Components([Normal(\"tmp\")])";
3684         let actual = format!("{:?}", components);
3685         assert_eq!(expected, actual);
3686
3687         let _ = components.next().unwrap();
3688         let expected = "Components([])";
3689         let actual = format!("{:?}", components);
3690         assert_eq!(expected, actual);
3691     }
3692
3693     #[cfg(unix)]
3694     #[test]
3695     fn test_iter_debug() {
3696         let path = Path::new("/tmp");
3697
3698         let mut iter = path.iter();
3699
3700         let expected = "Iter([\"/\", \"tmp\"])";
3701         let actual = format!("{:?}", iter);
3702         assert_eq!(expected, actual);
3703
3704         let _ = iter.next().unwrap();
3705         let expected = "Iter([\"tmp\"])";
3706         let actual = format!("{:?}", iter);
3707         assert_eq!(expected, actual);
3708
3709         let _ = iter.next().unwrap();
3710         let expected = "Iter([])";
3711         let actual = format!("{:?}", iter);
3712         assert_eq!(expected, actual);
3713     }
3714
3715     #[test]
3716     fn into_boxed() {
3717         let orig: &str = "some/sort/of/path";
3718         let path = Path::new(orig);
3719         let boxed: Box<Path> = Box::from(path);
3720         let path_buf = path.to_owned().into_boxed_path().into_path_buf();
3721         assert_eq!(path, &*boxed);
3722         assert_eq!(&*boxed, &*path_buf);
3723         assert_eq!(&*path_buf, path);
3724     }
3725 }