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