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