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