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