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