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