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