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