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