]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
Unignore u128 test for stage 0,1
[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
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1201     fn from(s: &'a T) -> PathBuf {
1202         PathBuf::from(s.as_ref().to_os_string())
1203     }
1204 }
1205
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 impl From<OsString> for PathBuf {
1208     fn from(s: OsString) -> PathBuf {
1209         PathBuf { inner: s }
1210     }
1211 }
1212
1213 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1214 impl From<PathBuf> for OsString {
1215     fn from(path_buf : PathBuf) -> OsString {
1216         path_buf.inner
1217     }
1218 }
1219
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl From<String> for PathBuf {
1222     fn from(s: String) -> PathBuf {
1223         PathBuf::from(OsString::from(s))
1224     }
1225 }
1226
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1229     fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1230         let mut buf = PathBuf::new();
1231         buf.extend(iter);
1232         buf
1233     }
1234 }
1235
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1238     fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1239         for p in iter {
1240             self.push(p.as_ref())
1241         }
1242     }
1243 }
1244
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 impl fmt::Debug for PathBuf {
1247     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1248         fmt::Debug::fmt(&**self, formatter)
1249     }
1250 }
1251
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl ops::Deref for PathBuf {
1254     type Target = Path;
1255
1256     fn deref(&self) -> &Path {
1257         Path::new(&self.inner)
1258     }
1259 }
1260
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl Borrow<Path> for PathBuf {
1263     fn borrow(&self) -> &Path {
1264         self.deref()
1265     }
1266 }
1267
1268 #[stable(feature = "cow_from_path", since = "1.6.0")]
1269 impl<'a> From<&'a Path> for Cow<'a, Path> {
1270     #[inline]
1271     fn from(s: &'a Path) -> Cow<'a, Path> {
1272         Cow::Borrowed(s)
1273     }
1274 }
1275
1276 #[stable(feature = "cow_from_path", since = "1.6.0")]
1277 impl<'a> From<PathBuf> for Cow<'a, Path> {
1278     #[inline]
1279     fn from(s: PathBuf) -> Cow<'a, Path> {
1280         Cow::Owned(s)
1281     }
1282 }
1283
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 impl ToOwned for Path {
1286     type Owned = PathBuf;
1287     fn to_owned(&self) -> PathBuf {
1288         self.to_path_buf()
1289     }
1290 }
1291
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl cmp::PartialEq for PathBuf {
1294     fn eq(&self, other: &PathBuf) -> bool {
1295         self.components() == other.components()
1296     }
1297 }
1298
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl Hash for PathBuf {
1301     fn hash<H: Hasher>(&self, h: &mut H) {
1302         self.as_path().hash(h)
1303     }
1304 }
1305
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl cmp::Eq for PathBuf {}
1308
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 impl cmp::PartialOrd for PathBuf {
1311     fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1312         self.components().partial_cmp(other.components())
1313     }
1314 }
1315
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl cmp::Ord for PathBuf {
1318     fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1319         self.components().cmp(other.components())
1320     }
1321 }
1322
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl AsRef<OsStr> for PathBuf {
1325     fn as_ref(&self) -> &OsStr {
1326         &self.inner[..]
1327     }
1328 }
1329
1330 /// A slice of a path (akin to [`str`]).
1331 ///
1332 /// This type supports a number of operations for inspecting a path, including
1333 /// breaking the path into its components (separated by `/` or `\`, depending on
1334 /// the platform), extracting the file name, determining whether the path is
1335 /// absolute, and so on.
1336 ///
1337 /// This is an *unsized* type, meaning that it must always be used behind a
1338 /// pointer like `&` or [`Box`]. For an owned version of this type,
1339 /// see [`PathBuf`].
1340 ///
1341 /// [`str`]: ../primitive.str.html
1342 /// [`Box`]: ../boxed/struct.Box.html
1343 /// [`PathBuf`]: struct.PathBuf.html
1344 ///
1345 /// More details about the overall approach can be found in
1346 /// the module documentation.
1347 ///
1348 /// # Examples
1349 ///
1350 /// ```
1351 /// use std::path::Path;
1352 /// use std::ffi::OsStr;
1353 ///
1354 /// let path = Path::new("/tmp/foo/bar.txt");
1355 ///
1356 /// let parent = path.parent();
1357 /// assert_eq!(parent, Some(Path::new("/tmp/foo")));
1358 ///
1359 /// let file_stem = path.file_stem();
1360 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1361 ///
1362 /// let extension = path.extension();
1363 /// assert_eq!(extension, Some(OsStr::new("txt")));
1364 /// ```
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub struct Path {
1367     inner: OsStr,
1368 }
1369
1370 /// An error returned from the [`Path::strip_prefix`] method indicating that the
1371 /// prefix was not found in `self`.
1372 ///
1373 /// [`Path::strip_prefix`]: struct.Path.html#method.strip_prefix
1374 #[derive(Debug, Clone, PartialEq, Eq)]
1375 #[stable(since = "1.7.0", feature = "strip_prefix")]
1376 pub struct StripPrefixError(());
1377
1378 impl Path {
1379     // The following (private!) function allows construction of a path from a u8
1380     // slice, which is only safe when it is known to follow the OsStr encoding.
1381     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1382         Path::new(u8_slice_as_os_str(s))
1383     }
1384     // The following (private!) function reveals the byte encoding used for OsStr.
1385     fn as_u8_slice(&self) -> &[u8] {
1386         os_str_as_u8_slice(&self.inner)
1387     }
1388
1389     /// Directly wrap a string slice as a `Path` slice.
1390     ///
1391     /// This is a cost-free conversion.
1392     ///
1393     /// # Examples
1394     ///
1395     /// ```
1396     /// use std::path::Path;
1397     ///
1398     /// Path::new("foo.txt");
1399     /// ```
1400     ///
1401     /// You can create `Path`s from `String`s, or even other `Path`s:
1402     ///
1403     /// ```
1404     /// use std::path::Path;
1405     ///
1406     /// let string = String::from("foo.txt");
1407     /// let from_string = Path::new(&string);
1408     /// let from_path = Path::new(&from_string);
1409     /// assert_eq!(from_string, from_path);
1410     /// ```
1411     #[stable(feature = "rust1", since = "1.0.0")]
1412     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1413         unsafe { mem::transmute(s.as_ref()) }
1414     }
1415
1416     /// Yields the underlying [`OsStr`] slice.
1417     ///
1418     /// [`OsStr`]: ../ffi/struct.OsStr.html
1419     ///
1420     /// # Examples
1421     ///
1422     /// ```
1423     /// use std::path::Path;
1424     ///
1425     /// let os_str = Path::new("foo.txt").as_os_str();
1426     /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1427     /// ```
1428     #[stable(feature = "rust1", since = "1.0.0")]
1429     pub fn as_os_str(&self) -> &OsStr {
1430         &self.inner
1431     }
1432
1433     /// Yields a [`&str`] slice if the `Path` is valid unicode.
1434     ///
1435     /// This conversion may entail doing a check for UTF-8 validity.
1436     ///
1437     /// [`&str`]: ../primitive.str.html
1438     ///
1439     /// # Examples
1440     ///
1441     /// ```
1442     /// use std::path::Path;
1443     ///
1444     /// let path = Path::new("foo.txt");
1445     /// assert_eq!(path.to_str(), Some("foo.txt"));
1446     /// ```
1447     #[stable(feature = "rust1", since = "1.0.0")]
1448     pub fn to_str(&self) -> Option<&str> {
1449         self.inner.to_str()
1450     }
1451
1452     /// Converts a `Path` to a [`Cow<str>`].
1453     ///
1454     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1455     ///
1456     /// [`Cow<str>`]: ../borrow/enum.Cow.html
1457     ///
1458     /// # Examples
1459     ///
1460     /// Calling `to_string_lossy` on a `Path` with valid unicode:
1461     ///
1462     /// ```
1463     /// use std::path::Path;
1464     ///
1465     /// let path = Path::new("foo.txt");
1466     /// assert_eq!(path.to_string_lossy(), "foo.txt");
1467     /// ```
1468     ///
1469     /// Had `os_str` contained invalid unicode, the `to_string_lossy` call might
1470     /// have returned `"fo�.txt"`.
1471     #[stable(feature = "rust1", since = "1.0.0")]
1472     pub fn to_string_lossy(&self) -> Cow<str> {
1473         self.inner.to_string_lossy()
1474     }
1475
1476     /// Converts a `Path` to an owned [`PathBuf`].
1477     ///
1478     /// [`PathBuf`]: struct.PathBuf.html
1479     ///
1480     /// # Examples
1481     ///
1482     /// ```
1483     /// use std::path::Path;
1484     ///
1485     /// let path_buf = Path::new("foo.txt").to_path_buf();
1486     /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1487     /// ```
1488     #[stable(feature = "rust1", since = "1.0.0")]
1489     pub fn to_path_buf(&self) -> PathBuf {
1490         PathBuf::from(self.inner.to_os_string())
1491     }
1492
1493     /// A path is *absolute* if it is independent of the current directory.
1494     ///
1495     /// * On Unix, a path is absolute if it starts with the root, so
1496     /// `is_absolute` and `has_root` are equivalent.
1497     ///
1498     /// * On Windows, a path is absolute if it has a prefix and starts with the
1499     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1500     ///
1501     /// # Examples
1502     ///
1503     /// ```
1504     /// use std::path::Path;
1505     ///
1506     /// assert!(!Path::new("foo.txt").is_absolute());
1507     /// ```
1508     #[stable(feature = "rust1", since = "1.0.0")]
1509     #[allow(deprecated)]
1510     pub fn is_absolute(&self) -> bool {
1511         // FIXME: Remove target_os = "redox" and allow Redox prefixes
1512         self.has_root() && (cfg!(unix) || cfg!(target_os = "redox") || self.prefix().is_some())
1513     }
1514
1515     /// A path is *relative* if it is not absolute.
1516     ///
1517     /// # Examples
1518     ///
1519     /// ```
1520     /// use std::path::Path;
1521     ///
1522     /// assert!(Path::new("foo.txt").is_relative());
1523     /// ```
1524     #[stable(feature = "rust1", since = "1.0.0")]
1525     pub fn is_relative(&self) -> bool {
1526         !self.is_absolute()
1527     }
1528
1529     fn prefix(&self) -> Option<Prefix> {
1530         self.components().prefix
1531     }
1532
1533     /// A path has a root if the body of the path begins with the directory separator.
1534     ///
1535     /// * On Unix, a path has a root if it begins with `/`.
1536     ///
1537     /// * On Windows, a path has a root if it:
1538     ///     * has no prefix and begins with a separator, e.g. `\\windows`
1539     ///     * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1540     ///     * has any non-disk prefix, e.g. `\\server\share`
1541     ///
1542     /// # Examples
1543     ///
1544     /// ```
1545     /// use std::path::Path;
1546     ///
1547     /// assert!(Path::new("/etc/passwd").has_root());
1548     /// ```
1549     #[stable(feature = "rust1", since = "1.0.0")]
1550     pub fn has_root(&self) -> bool {
1551         self.components().has_root()
1552     }
1553
1554     /// The path without its final component, if any.
1555     ///
1556     /// Returns [`None`] if the path terminates in a root or prefix.
1557     ///
1558     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1559     ///
1560     /// # Examples
1561     ///
1562     /// ```
1563     /// use std::path::Path;
1564     ///
1565     /// let path = Path::new("/foo/bar");
1566     /// let parent = path.parent().unwrap();
1567     /// assert_eq!(parent, Path::new("/foo"));
1568     ///
1569     /// let grand_parent = parent.parent().unwrap();
1570     /// assert_eq!(grand_parent, Path::new("/"));
1571     /// assert_eq!(grand_parent.parent(), None);
1572     /// ```
1573     #[stable(feature = "rust1", since = "1.0.0")]
1574     pub fn parent(&self) -> Option<&Path> {
1575         let mut comps = self.components();
1576         let comp = comps.next_back();
1577         comp.and_then(|p| {
1578             match p {
1579                 Component::Normal(_) |
1580                 Component::CurDir |
1581                 Component::ParentDir => Some(comps.as_path()),
1582                 _ => None,
1583             }
1584         })
1585     }
1586
1587     /// The final component of the path, if it is a normal file.
1588     ///
1589     /// If the path terminates in `..`, `file_name` will return [`None`].
1590     ///
1591     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1592     ///
1593     /// # Examples
1594     ///
1595     /// ```
1596     /// use std::path::Path;
1597     /// use std::ffi::OsStr;
1598     ///
1599     /// let path = Path::new("foo.txt");
1600     /// let os_str = OsStr::new("foo.txt");
1601     ///
1602     /// assert_eq!(Some(os_str), path.file_name());
1603     /// ```
1604     ///
1605     /// # Other examples
1606     ///
1607     /// ```
1608     /// use std::path::Path;
1609     /// use std::ffi::OsStr;
1610     ///
1611     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1612     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1613     /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1614     /// ```
1615     #[stable(feature = "rust1", since = "1.0.0")]
1616     pub fn file_name(&self) -> Option<&OsStr> {
1617         self.components().next_back().and_then(|p| {
1618             match p {
1619                 Component::Normal(p) => Some(p.as_ref()),
1620                 _ => None,
1621             }
1622         })
1623     }
1624
1625     /// Returns a path that, when joined onto `base`, yields `self`.
1626     ///
1627     /// # Errors
1628     ///
1629     /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1630     /// returns `false`), returns [`Err`].
1631     ///
1632     /// [`starts_with`]: #method.starts_with
1633     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1634     ///
1635     /// # Examples
1636     ///
1637     /// ```
1638     /// use std::path::Path;
1639     ///
1640     /// let path = Path::new("/test/haha/foo.txt");
1641     ///
1642     /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1643     /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1644     /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1645     /// ```
1646     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1647     pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1648                                        -> Result<&'a Path, StripPrefixError>
1649         where P: AsRef<Path>
1650     {
1651         self._strip_prefix(base.as_ref())
1652     }
1653
1654     fn _strip_prefix<'a>(&'a self, base: &'a Path)
1655                          -> Result<&'a Path, StripPrefixError> {
1656         iter_after(self.components(), base.components())
1657             .map(|c| c.as_path())
1658             .ok_or(StripPrefixError(()))
1659     }
1660
1661     /// Determines whether `base` is a prefix of `self`.
1662     ///
1663     /// Only considers whole path components to match.
1664     ///
1665     /// # Examples
1666     ///
1667     /// ```
1668     /// use std::path::Path;
1669     ///
1670     /// let path = Path::new("/etc/passwd");
1671     ///
1672     /// assert!(path.starts_with("/etc"));
1673     ///
1674     /// assert!(!path.starts_with("/e"));
1675     /// ```
1676     #[stable(feature = "rust1", since = "1.0.0")]
1677     pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1678         self._starts_with(base.as_ref())
1679     }
1680
1681     fn _starts_with(&self, base: &Path) -> bool {
1682         iter_after(self.components(), base.components()).is_some()
1683     }
1684
1685     /// Determines whether `child` is a suffix of `self`.
1686     ///
1687     /// Only considers whole path components to match.
1688     ///
1689     /// # Examples
1690     ///
1691     /// ```
1692     /// use std::path::Path;
1693     ///
1694     /// let path = Path::new("/etc/passwd");
1695     ///
1696     /// assert!(path.ends_with("passwd"));
1697     /// ```
1698     #[stable(feature = "rust1", since = "1.0.0")]
1699     pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1700         self._ends_with(child.as_ref())
1701     }
1702
1703     fn _ends_with(&self, child: &Path) -> bool {
1704         iter_after(self.components().rev(), child.components().rev()).is_some()
1705     }
1706
1707     /// Extracts the stem (non-extension) portion of [`self.file_name()`].
1708     ///
1709     /// [`self.file_name()`]: struct.Path.html#method.file_name
1710     ///
1711     /// The stem is:
1712     ///
1713     /// * [`None`], if there is no file name;
1714     /// * The entire file name if there is no embedded `.`;
1715     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1716     /// * Otherwise, the portion of the file name before the final `.`
1717     ///
1718     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1719     ///
1720     /// # Examples
1721     ///
1722     /// ```
1723     /// use std::path::Path;
1724     ///
1725     /// let path = Path::new("foo.rs");
1726     ///
1727     /// assert_eq!("foo", path.file_stem().unwrap());
1728     /// ```
1729     #[stable(feature = "rust1", since = "1.0.0")]
1730     pub fn file_stem(&self) -> Option<&OsStr> {
1731         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1732     }
1733
1734     /// Extracts the extension of [`self.file_name()`], if possible.
1735     ///
1736     /// The extension is:
1737     ///
1738     /// * [`None`], if there is no file name;
1739     /// * [`None`], if there is no embedded `.`;
1740     /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1741     /// * Otherwise, the portion of the file name after the final `.`
1742     ///
1743     /// [`self.file_name()`]: struct.Path.html#method.file_name
1744     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1745     ///
1746     /// # Examples
1747     ///
1748     /// ```
1749     /// use std::path::Path;
1750     ///
1751     /// let path = Path::new("foo.rs");
1752     ///
1753     /// assert_eq!("rs", path.extension().unwrap());
1754     /// ```
1755     #[stable(feature = "rust1", since = "1.0.0")]
1756     pub fn extension(&self) -> Option<&OsStr> {
1757         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1758     }
1759
1760     /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1761     ///
1762     /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1763     ///
1764     /// [`PathBuf`]: struct.PathBuf.html
1765     /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1766     ///
1767     /// # Examples
1768     ///
1769     /// ```
1770     /// use std::path::{Path, PathBuf};
1771     ///
1772     /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1773     /// ```
1774     #[stable(feature = "rust1", since = "1.0.0")]
1775     pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1776         self._join(path.as_ref())
1777     }
1778
1779     fn _join(&self, path: &Path) -> PathBuf {
1780         let mut buf = self.to_path_buf();
1781         buf.push(path);
1782         buf
1783     }
1784
1785     /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1786     ///
1787     /// See [`PathBuf::set_file_name`] for more details.
1788     ///
1789     /// [`PathBuf`]: struct.PathBuf.html
1790     /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1791     ///
1792     /// # Examples
1793     ///
1794     /// ```
1795     /// use std::path::{Path, PathBuf};
1796     ///
1797     /// let path = Path::new("/tmp/foo.txt");
1798     /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1799     /// ```
1800     #[stable(feature = "rust1", since = "1.0.0")]
1801     pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1802         self._with_file_name(file_name.as_ref())
1803     }
1804
1805     fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1806         let mut buf = self.to_path_buf();
1807         buf.set_file_name(file_name);
1808         buf
1809     }
1810
1811     /// Creates an owned [`PathBuf`] like `self` but with the given extension.
1812     ///
1813     /// See [`PathBuf::set_extension`] for more details.
1814     ///
1815     /// [`PathBuf`]: struct.PathBuf.html
1816     /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
1817     ///
1818     /// # Examples
1819     ///
1820     /// ```
1821     /// use std::path::{Path, PathBuf};
1822     ///
1823     /// let path = Path::new("foo.rs");
1824     /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1825     /// ```
1826     #[stable(feature = "rust1", since = "1.0.0")]
1827     pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1828         self._with_extension(extension.as_ref())
1829     }
1830
1831     fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1832         let mut buf = self.to_path_buf();
1833         buf.set_extension(extension);
1834         buf
1835     }
1836
1837     /// Produce an iterator over the components of the path.
1838     ///
1839     /// # Examples
1840     ///
1841     /// ```
1842     /// use std::path::{Path, Component};
1843     /// use std::ffi::OsStr;
1844     ///
1845     /// let mut components = Path::new("/tmp/foo.txt").components();
1846     ///
1847     /// assert_eq!(components.next(), Some(Component::RootDir));
1848     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1849     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1850     /// assert_eq!(components.next(), None)
1851     /// ```
1852     #[stable(feature = "rust1", since = "1.0.0")]
1853     pub fn components(&self) -> Components {
1854         let prefix = parse_prefix(self.as_os_str());
1855         Components {
1856             path: self.as_u8_slice(),
1857             prefix: prefix,
1858             has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1859             front: State::Prefix,
1860             back: State::Body,
1861         }
1862     }
1863
1864     /// Produce an iterator over the path's components viewed as [`OsStr`] slices.
1865     ///
1866     /// [`OsStr`]: ../ffi/struct.OsStr.html
1867     ///
1868     /// # Examples
1869     ///
1870     /// ```
1871     /// use std::path::{self, Path};
1872     /// use std::ffi::OsStr;
1873     ///
1874     /// let mut it = Path::new("/tmp/foo.txt").iter();
1875     /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1876     /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1877     /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1878     /// assert_eq!(it.next(), None)
1879     /// ```
1880     #[stable(feature = "rust1", since = "1.0.0")]
1881     pub fn iter(&self) -> Iter {
1882         Iter { inner: self.components() }
1883     }
1884
1885     /// Returns an object that implements [`Display`] for safely printing paths
1886     /// that may contain non-Unicode data.
1887     ///
1888     /// [`Display`]: ../fmt/trait.Display.html
1889     ///
1890     /// # Examples
1891     ///
1892     /// ```
1893     /// use std::path::Path;
1894     ///
1895     /// let path = Path::new("/tmp/foo.rs");
1896     ///
1897     /// println!("{}", path.display());
1898     /// ```
1899     #[stable(feature = "rust1", since = "1.0.0")]
1900     pub fn display(&self) -> Display {
1901         Display { path: self }
1902     }
1903
1904     /// Query the file system to get information about a file, directory, etc.
1905     ///
1906     /// This function will traverse symbolic links to query information about the
1907     /// destination file.
1908     ///
1909     /// This is an alias to [`fs::metadata`].
1910     ///
1911     /// [`fs::metadata`]: ../fs/fn.metadata.html
1912     ///
1913     /// # Examples
1914     ///
1915     /// ```no_run
1916     /// use std::path::Path;
1917     ///
1918     /// let path = Path::new("/Minas/tirith");
1919     /// let metadata = path.metadata().expect("metadata call failed");
1920     /// println!("{:?}", metadata.file_type());
1921     /// ```
1922     #[stable(feature = "path_ext", since = "1.5.0")]
1923     pub fn metadata(&self) -> io::Result<fs::Metadata> {
1924         fs::metadata(self)
1925     }
1926
1927     /// Query the metadata about a file without following symlinks.
1928     ///
1929     /// This is an alias to [`fs::symlink_metadata`].
1930     ///
1931     /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
1932     ///
1933     /// # Examples
1934     ///
1935     /// ```no_run
1936     /// use std::path::Path;
1937     ///
1938     /// let path = Path::new("/Minas/tirith");
1939     /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
1940     /// println!("{:?}", metadata.file_type());
1941     /// ```
1942     #[stable(feature = "path_ext", since = "1.5.0")]
1943     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1944         fs::symlink_metadata(self)
1945     }
1946
1947     /// Returns the canonical form of the path with all intermediate components
1948     /// normalized and symbolic links resolved.
1949     ///
1950     /// This is an alias to [`fs::canonicalize`].
1951     ///
1952     /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
1953     ///
1954     /// # Examples
1955     ///
1956     /// ```no_run
1957     /// use std::path::{Path, PathBuf};
1958     ///
1959     /// let path = Path::new("/foo/test/../test/bar.rs");
1960     /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
1961     /// ```
1962     #[stable(feature = "path_ext", since = "1.5.0")]
1963     pub fn canonicalize(&self) -> io::Result<PathBuf> {
1964         fs::canonicalize(self)
1965     }
1966
1967     /// Reads a symbolic link, returning the file that the link points to.
1968     ///
1969     /// This is an alias to [`fs::read_link`].
1970     ///
1971     /// [`fs::read_link`]: ../fs/fn.read_link.html
1972     ///
1973     /// # Examples
1974     ///
1975     /// ```no_run
1976     /// use std::path::Path;
1977     ///
1978     /// let path = Path::new("/laputa/sky_castle.rs");
1979     /// let path_link = path.read_link().expect("read_link call failed");
1980     /// ```
1981     #[stable(feature = "path_ext", since = "1.5.0")]
1982     pub fn read_link(&self) -> io::Result<PathBuf> {
1983         fs::read_link(self)
1984     }
1985
1986     /// Returns an iterator over the entries within a directory.
1987     ///
1988     /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
1989     /// errors may be encountered after an iterator is initially constructed.
1990     ///
1991     /// This is an alias to [`fs::read_dir`].
1992     ///
1993     /// [`io::Result`]: ../io/type.Result.html
1994     /// [`DirEntry`]: ../fs/struct.DirEntry.html
1995     /// [`fs::read_dir`]: ../fs/fn.read_dir.html
1996     ///
1997     /// # Examples
1998     ///
1999     /// ```no_run
2000     /// use std::path::Path;
2001     ///
2002     /// let path = Path::new("/laputa");
2003     /// for entry in path.read_dir().expect("read_dir call failed") {
2004     ///     if let Ok(entry) = entry {
2005     ///         println!("{:?}", entry.path());
2006     ///     }
2007     /// }
2008     /// ```
2009     #[stable(feature = "path_ext", since = "1.5.0")]
2010     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2011         fs::read_dir(self)
2012     }
2013
2014     /// Returns whether the path points at an existing entity.
2015     ///
2016     /// This function will traverse symbolic links to query information about the
2017     /// destination file. In case of broken symbolic links this will return `false`.
2018     ///
2019     /// # Examples
2020     ///
2021     /// ```no_run
2022     /// use std::path::Path;
2023     /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2024     /// ```
2025     #[stable(feature = "path_ext", since = "1.5.0")]
2026     pub fn exists(&self) -> bool {
2027         fs::metadata(self).is_ok()
2028     }
2029
2030     /// Returns whether the path is pointing at a regular file.
2031     ///
2032     /// This function will traverse symbolic links to query information about the
2033     /// destination file. In case of broken symbolic links this will return `false`.
2034     ///
2035     /// # Examples
2036     ///
2037     /// ```no_run
2038     /// use std::path::Path;
2039     /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2040     /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2041     /// ```
2042     #[stable(feature = "path_ext", since = "1.5.0")]
2043     pub fn is_file(&self) -> bool {
2044         fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2045     }
2046
2047     /// Returns whether the path is pointing at a directory.
2048     ///
2049     /// This function will traverse symbolic links to query information about the
2050     /// destination file. In case of broken symbolic links this will return `false`.
2051     ///
2052     /// # Examples
2053     ///
2054     /// ```no_run
2055     /// use std::path::Path;
2056     /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2057     /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2058     /// ```
2059     #[stable(feature = "path_ext", since = "1.5.0")]
2060     pub fn is_dir(&self) -> bool {
2061         fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2062     }
2063 }
2064
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 impl AsRef<OsStr> for Path {
2067     fn as_ref(&self) -> &OsStr {
2068         &self.inner
2069     }
2070 }
2071
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl fmt::Debug for Path {
2074     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2075         self.inner.fmt(formatter)
2076     }
2077 }
2078
2079 /// Helper struct for safely printing paths with `format!()` and `{}`
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 pub struct Display<'a> {
2082     path: &'a Path,
2083 }
2084
2085 #[stable(feature = "rust1", since = "1.0.0")]
2086 impl<'a> fmt::Debug for Display<'a> {
2087     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2088         fmt::Debug::fmt(&self.path.to_string_lossy(), f)
2089     }
2090 }
2091
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl<'a> fmt::Display for Display<'a> {
2094     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2095         fmt::Display::fmt(&self.path.to_string_lossy(), f)
2096     }
2097 }
2098
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 impl cmp::PartialEq for Path {
2101     fn eq(&self, other: &Path) -> bool {
2102         self.components().eq(other.components())
2103     }
2104 }
2105
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl Hash for Path {
2108     fn hash<H: Hasher>(&self, h: &mut H) {
2109         for component in self.components() {
2110             component.hash(h);
2111         }
2112     }
2113 }
2114
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 impl cmp::Eq for Path {}
2117
2118 #[stable(feature = "rust1", since = "1.0.0")]
2119 impl cmp::PartialOrd for Path {
2120     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2121         self.components().partial_cmp(other.components())
2122     }
2123 }
2124
2125 #[stable(feature = "rust1", since = "1.0.0")]
2126 impl cmp::Ord for Path {
2127     fn cmp(&self, other: &Path) -> cmp::Ordering {
2128         self.components().cmp(other.components())
2129     }
2130 }
2131
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl AsRef<Path> for Path {
2134     fn as_ref(&self) -> &Path {
2135         self
2136     }
2137 }
2138
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 impl AsRef<Path> for OsStr {
2141     fn as_ref(&self) -> &Path {
2142         Path::new(self)
2143     }
2144 }
2145
2146 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2147 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2148     fn as_ref(&self) -> &Path {
2149         Path::new(self)
2150     }
2151 }
2152
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 impl AsRef<Path> for OsString {
2155     fn as_ref(&self) -> &Path {
2156         Path::new(self)
2157     }
2158 }
2159
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl AsRef<Path> for str {
2162     fn as_ref(&self) -> &Path {
2163         Path::new(self)
2164     }
2165 }
2166
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 impl AsRef<Path> for String {
2169     fn as_ref(&self) -> &Path {
2170         Path::new(self)
2171     }
2172 }
2173
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 impl AsRef<Path> for PathBuf {
2176     fn as_ref(&self) -> &Path {
2177         self
2178     }
2179 }
2180
2181 #[stable(feature = "path_into_iter", since = "1.6.0")]
2182 impl<'a> IntoIterator for &'a PathBuf {
2183     type Item = &'a OsStr;
2184     type IntoIter = Iter<'a>;
2185     fn into_iter(self) -> Iter<'a> { self.iter() }
2186 }
2187
2188 #[stable(feature = "path_into_iter", since = "1.6.0")]
2189 impl<'a> IntoIterator for &'a Path {
2190     type Item = &'a OsStr;
2191     type IntoIter = Iter<'a>;
2192     fn into_iter(self) -> Iter<'a> { self.iter() }
2193 }
2194
2195 macro_rules! impl_cmp {
2196     ($lhs:ty, $rhs: ty) => {
2197         #[stable(feature = "partialeq_path", since = "1.6.0")]
2198         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2199             #[inline]
2200             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2201         }
2202
2203         #[stable(feature = "partialeq_path", since = "1.6.0")]
2204         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2205             #[inline]
2206             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2207         }
2208
2209         #[stable(feature = "cmp_path", since = "1.8.0")]
2210         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2211             #[inline]
2212             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2213                 <Path as PartialOrd>::partial_cmp(self, other)
2214             }
2215         }
2216
2217         #[stable(feature = "cmp_path", since = "1.8.0")]
2218         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2219             #[inline]
2220             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2221                 <Path as PartialOrd>::partial_cmp(self, other)
2222             }
2223         }
2224     }
2225 }
2226
2227 impl_cmp!(PathBuf, Path);
2228 impl_cmp!(PathBuf, &'a Path);
2229 impl_cmp!(Cow<'a, Path>, Path);
2230 impl_cmp!(Cow<'a, Path>, &'b Path);
2231 impl_cmp!(Cow<'a, Path>, PathBuf);
2232
2233 macro_rules! impl_cmp_os_str {
2234     ($lhs:ty, $rhs: ty) => {
2235         #[stable(feature = "cmp_path", since = "1.8.0")]
2236         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2237             #[inline]
2238             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2239         }
2240
2241         #[stable(feature = "cmp_path", since = "1.8.0")]
2242         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2243             #[inline]
2244             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2245         }
2246
2247         #[stable(feature = "cmp_path", since = "1.8.0")]
2248         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2249             #[inline]
2250             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2251                 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2252             }
2253         }
2254
2255         #[stable(feature = "cmp_path", since = "1.8.0")]
2256         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2257             #[inline]
2258             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2259                 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2260             }
2261         }
2262     }
2263 }
2264
2265 impl_cmp_os_str!(PathBuf, OsStr);
2266 impl_cmp_os_str!(PathBuf, &'a OsStr);
2267 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2268 impl_cmp_os_str!(PathBuf, OsString);
2269 impl_cmp_os_str!(Path, OsStr);
2270 impl_cmp_os_str!(Path, &'a OsStr);
2271 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2272 impl_cmp_os_str!(Path, OsString);
2273 impl_cmp_os_str!(&'a Path, OsStr);
2274 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2275 impl_cmp_os_str!(&'a Path, OsString);
2276 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2277 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2278 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2279
2280 #[stable(since = "1.7.0", feature = "strip_prefix")]
2281 impl fmt::Display for StripPrefixError {
2282     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2283         self.description().fmt(f)
2284     }
2285 }
2286
2287 #[stable(since = "1.7.0", feature = "strip_prefix")]
2288 impl Error for StripPrefixError {
2289     fn description(&self) -> &str { "prefix not found" }
2290 }
2291
2292 #[cfg(test)]
2293 mod tests {
2294     use super::*;
2295
2296     macro_rules! t(
2297         ($path:expr, iter: $iter:expr) => (
2298             {
2299                 let path = Path::new($path);
2300
2301                 // Forward iteration
2302                 let comps = path.iter()
2303                     .map(|p| p.to_string_lossy().into_owned())
2304                     .collect::<Vec<String>>();
2305                 let exp: &[&str] = &$iter;
2306                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2307                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2308                         exps, comps);
2309
2310                 // Reverse iteration
2311                 let comps = Path::new($path).iter().rev()
2312                     .map(|p| p.to_string_lossy().into_owned())
2313                     .collect::<Vec<String>>();
2314                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2315                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2316                         exps, comps);
2317             }
2318         );
2319
2320         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2321             {
2322                 let path = Path::new($path);
2323
2324                 let act_root = path.has_root();
2325                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2326                         $has_root, act_root);
2327
2328                 let act_abs = path.is_absolute();
2329                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2330                         $is_absolute, act_abs);
2331             }
2332         );
2333
2334         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2335             {
2336                 let path = Path::new($path);
2337
2338                 let parent = path.parent().map(|p| p.to_str().unwrap());
2339                 let exp_parent: Option<&str> = $parent;
2340                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2341                         exp_parent, parent);
2342
2343                 let file = path.file_name().map(|p| p.to_str().unwrap());
2344                 let exp_file: Option<&str> = $file;
2345                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2346                         exp_file, file);
2347             }
2348         );
2349
2350         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2351             {
2352                 let path = Path::new($path);
2353
2354                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2355                 let exp_stem: Option<&str> = $file_stem;
2356                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2357                         exp_stem, stem);
2358
2359                 let ext = path.extension().map(|p| p.to_str().unwrap());
2360                 let exp_ext: Option<&str> = $extension;
2361                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2362                         exp_ext, ext);
2363             }
2364         );
2365
2366         ($path:expr, iter: $iter:expr,
2367                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2368                      parent: $parent:expr, file_name: $file:expr,
2369                      file_stem: $file_stem:expr, extension: $extension:expr) => (
2370             {
2371                 t!($path, iter: $iter);
2372                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2373                 t!($path, parent: $parent, file_name: $file);
2374                 t!($path, file_stem: $file_stem, extension: $extension);
2375             }
2376         );
2377     );
2378
2379     #[test]
2380     fn into() {
2381         use borrow::Cow;
2382
2383         let static_path = Path::new("/home/foo");
2384         let static_cow_path: Cow<'static, Path> = static_path.into();
2385         let pathbuf = PathBuf::from("/home/foo");
2386
2387         {
2388             let path: &Path = &pathbuf;
2389             let borrowed_cow_path: Cow<Path> = path.into();
2390
2391             assert_eq!(static_cow_path, borrowed_cow_path);
2392         }
2393
2394         let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2395
2396         assert_eq!(static_cow_path, owned_cow_path);
2397     }
2398
2399     #[test]
2400     #[cfg(unix)]
2401     pub fn test_decompositions_unix() {
2402         t!("",
2403            iter: [],
2404            has_root: false,
2405            is_absolute: false,
2406            parent: None,
2407            file_name: None,
2408            file_stem: None,
2409            extension: None
2410            );
2411
2412         t!("foo",
2413            iter: ["foo"],
2414            has_root: false,
2415            is_absolute: false,
2416            parent: Some(""),
2417            file_name: Some("foo"),
2418            file_stem: Some("foo"),
2419            extension: None
2420            );
2421
2422         t!("/",
2423            iter: ["/"],
2424            has_root: true,
2425            is_absolute: true,
2426            parent: None,
2427            file_name: None,
2428            file_stem: None,
2429            extension: None
2430            );
2431
2432         t!("/foo",
2433            iter: ["/", "foo"],
2434            has_root: true,
2435            is_absolute: true,
2436            parent: Some("/"),
2437            file_name: Some("foo"),
2438            file_stem: Some("foo"),
2439            extension: None
2440            );
2441
2442         t!("foo/",
2443            iter: ["foo"],
2444            has_root: false,
2445            is_absolute: false,
2446            parent: Some(""),
2447            file_name: Some("foo"),
2448            file_stem: Some("foo"),
2449            extension: None
2450            );
2451
2452         t!("/foo/",
2453            iter: ["/", "foo"],
2454            has_root: true,
2455            is_absolute: true,
2456            parent: Some("/"),
2457            file_name: Some("foo"),
2458            file_stem: Some("foo"),
2459            extension: None
2460            );
2461
2462         t!("foo/bar",
2463            iter: ["foo", "bar"],
2464            has_root: false,
2465            is_absolute: false,
2466            parent: Some("foo"),
2467            file_name: Some("bar"),
2468            file_stem: Some("bar"),
2469            extension: None
2470            );
2471
2472         t!("/foo/bar",
2473            iter: ["/", "foo", "bar"],
2474            has_root: true,
2475            is_absolute: true,
2476            parent: Some("/foo"),
2477            file_name: Some("bar"),
2478            file_stem: Some("bar"),
2479            extension: None
2480            );
2481
2482         t!("///foo///",
2483            iter: ["/", "foo"],
2484            has_root: true,
2485            is_absolute: true,
2486            parent: Some("/"),
2487            file_name: Some("foo"),
2488            file_stem: Some("foo"),
2489            extension: None
2490            );
2491
2492         t!("///foo///bar",
2493            iter: ["/", "foo", "bar"],
2494            has_root: true,
2495            is_absolute: true,
2496            parent: Some("///foo"),
2497            file_name: Some("bar"),
2498            file_stem: Some("bar"),
2499            extension: None
2500            );
2501
2502         t!("./.",
2503            iter: ["."],
2504            has_root: false,
2505            is_absolute: false,
2506            parent: Some(""),
2507            file_name: None,
2508            file_stem: None,
2509            extension: None
2510            );
2511
2512         t!("/..",
2513            iter: ["/", ".."],
2514            has_root: true,
2515            is_absolute: true,
2516            parent: Some("/"),
2517            file_name: None,
2518            file_stem: None,
2519            extension: None
2520            );
2521
2522         t!("../",
2523            iter: [".."],
2524            has_root: false,
2525            is_absolute: false,
2526            parent: Some(""),
2527            file_name: None,
2528            file_stem: None,
2529            extension: None
2530            );
2531
2532         t!("foo/.",
2533            iter: ["foo"],
2534            has_root: false,
2535            is_absolute: false,
2536            parent: Some(""),
2537            file_name: Some("foo"),
2538            file_stem: Some("foo"),
2539            extension: None
2540            );
2541
2542         t!("foo/..",
2543            iter: ["foo", ".."],
2544            has_root: false,
2545            is_absolute: false,
2546            parent: Some("foo"),
2547            file_name: None,
2548            file_stem: None,
2549            extension: None
2550            );
2551
2552         t!("foo/./",
2553            iter: ["foo"],
2554            has_root: false,
2555            is_absolute: false,
2556            parent: Some(""),
2557            file_name: Some("foo"),
2558            file_stem: Some("foo"),
2559            extension: None
2560            );
2561
2562         t!("foo/./bar",
2563            iter: ["foo", "bar"],
2564            has_root: false,
2565            is_absolute: false,
2566            parent: Some("foo"),
2567            file_name: Some("bar"),
2568            file_stem: Some("bar"),
2569            extension: None
2570            );
2571
2572         t!("foo/../",
2573            iter: ["foo", ".."],
2574            has_root: false,
2575            is_absolute: false,
2576            parent: Some("foo"),
2577            file_name: None,
2578            file_stem: None,
2579            extension: None
2580            );
2581
2582         t!("foo/../bar",
2583            iter: ["foo", "..", "bar"],
2584            has_root: false,
2585            is_absolute: false,
2586            parent: Some("foo/.."),
2587            file_name: Some("bar"),
2588            file_stem: Some("bar"),
2589            extension: None
2590            );
2591
2592         t!("./a",
2593            iter: [".", "a"],
2594            has_root: false,
2595            is_absolute: false,
2596            parent: Some("."),
2597            file_name: Some("a"),
2598            file_stem: Some("a"),
2599            extension: None
2600            );
2601
2602         t!(".",
2603            iter: ["."],
2604            has_root: false,
2605            is_absolute: false,
2606            parent: Some(""),
2607            file_name: None,
2608            file_stem: None,
2609            extension: None
2610            );
2611
2612         t!("./",
2613            iter: ["."],
2614            has_root: false,
2615            is_absolute: false,
2616            parent: Some(""),
2617            file_name: None,
2618            file_stem: None,
2619            extension: None
2620            );
2621
2622         t!("a/b",
2623            iter: ["a", "b"],
2624            has_root: false,
2625            is_absolute: false,
2626            parent: Some("a"),
2627            file_name: Some("b"),
2628            file_stem: Some("b"),
2629            extension: None
2630            );
2631
2632         t!("a//b",
2633            iter: ["a", "b"],
2634            has_root: false,
2635            is_absolute: false,
2636            parent: Some("a"),
2637            file_name: Some("b"),
2638            file_stem: Some("b"),
2639            extension: None
2640            );
2641
2642         t!("a/./b",
2643            iter: ["a", "b"],
2644            has_root: false,
2645            is_absolute: false,
2646            parent: Some("a"),
2647            file_name: Some("b"),
2648            file_stem: Some("b"),
2649            extension: None
2650            );
2651
2652         t!("a/b/c",
2653            iter: ["a", "b", "c"],
2654            has_root: false,
2655            is_absolute: false,
2656            parent: Some("a/b"),
2657            file_name: Some("c"),
2658            file_stem: Some("c"),
2659            extension: None
2660            );
2661
2662         t!(".foo",
2663            iter: [".foo"],
2664            has_root: false,
2665            is_absolute: false,
2666            parent: Some(""),
2667            file_name: Some(".foo"),
2668            file_stem: Some(".foo"),
2669            extension: None
2670            );
2671     }
2672
2673     #[test]
2674     #[cfg(windows)]
2675     pub fn test_decompositions_windows() {
2676         t!("",
2677            iter: [],
2678            has_root: false,
2679            is_absolute: false,
2680            parent: None,
2681            file_name: None,
2682            file_stem: None,
2683            extension: None
2684            );
2685
2686         t!("foo",
2687            iter: ["foo"],
2688            has_root: false,
2689            is_absolute: false,
2690            parent: Some(""),
2691            file_name: Some("foo"),
2692            file_stem: Some("foo"),
2693            extension: None
2694            );
2695
2696         t!("/",
2697            iter: ["\\"],
2698            has_root: true,
2699            is_absolute: false,
2700            parent: None,
2701            file_name: None,
2702            file_stem: None,
2703            extension: None
2704            );
2705
2706         t!("\\",
2707            iter: ["\\"],
2708            has_root: true,
2709            is_absolute: false,
2710            parent: None,
2711            file_name: None,
2712            file_stem: None,
2713            extension: None
2714            );
2715
2716         t!("c:",
2717            iter: ["c:"],
2718            has_root: false,
2719            is_absolute: false,
2720            parent: None,
2721            file_name: None,
2722            file_stem: None,
2723            extension: None
2724            );
2725
2726         t!("c:\\",
2727            iter: ["c:", "\\"],
2728            has_root: true,
2729            is_absolute: true,
2730            parent: None,
2731            file_name: None,
2732            file_stem: None,
2733            extension: None
2734            );
2735
2736         t!("c:/",
2737            iter: ["c:", "\\"],
2738            has_root: true,
2739            is_absolute: true,
2740            parent: None,
2741            file_name: None,
2742            file_stem: None,
2743            extension: None
2744            );
2745
2746         t!("/foo",
2747            iter: ["\\", "foo"],
2748            has_root: true,
2749            is_absolute: false,
2750            parent: Some("/"),
2751            file_name: Some("foo"),
2752            file_stem: Some("foo"),
2753            extension: None
2754            );
2755
2756         t!("foo/",
2757            iter: ["foo"],
2758            has_root: false,
2759            is_absolute: false,
2760            parent: Some(""),
2761            file_name: Some("foo"),
2762            file_stem: Some("foo"),
2763            extension: None
2764            );
2765
2766         t!("/foo/",
2767            iter: ["\\", "foo"],
2768            has_root: true,
2769            is_absolute: false,
2770            parent: Some("/"),
2771            file_name: Some("foo"),
2772            file_stem: Some("foo"),
2773            extension: None
2774            );
2775
2776         t!("foo/bar",
2777            iter: ["foo", "bar"],
2778            has_root: false,
2779            is_absolute: false,
2780            parent: Some("foo"),
2781            file_name: Some("bar"),
2782            file_stem: Some("bar"),
2783            extension: None
2784            );
2785
2786         t!("/foo/bar",
2787            iter: ["\\", "foo", "bar"],
2788            has_root: true,
2789            is_absolute: false,
2790            parent: Some("/foo"),
2791            file_name: Some("bar"),
2792            file_stem: Some("bar"),
2793            extension: None
2794            );
2795
2796         t!("///foo///",
2797            iter: ["\\", "foo"],
2798            has_root: true,
2799            is_absolute: false,
2800            parent: Some("/"),
2801            file_name: Some("foo"),
2802            file_stem: Some("foo"),
2803            extension: None
2804            );
2805
2806         t!("///foo///bar",
2807            iter: ["\\", "foo", "bar"],
2808            has_root: true,
2809            is_absolute: false,
2810            parent: Some("///foo"),
2811            file_name: Some("bar"),
2812            file_stem: Some("bar"),
2813            extension: None
2814            );
2815
2816         t!("./.",
2817            iter: ["."],
2818            has_root: false,
2819            is_absolute: false,
2820            parent: Some(""),
2821            file_name: None,
2822            file_stem: None,
2823            extension: None
2824            );
2825
2826         t!("/..",
2827            iter: ["\\", ".."],
2828            has_root: true,
2829            is_absolute: false,
2830            parent: Some("/"),
2831            file_name: None,
2832            file_stem: None,
2833            extension: None
2834            );
2835
2836         t!("../",
2837            iter: [".."],
2838            has_root: false,
2839            is_absolute: false,
2840            parent: Some(""),
2841            file_name: None,
2842            file_stem: None,
2843            extension: None
2844            );
2845
2846         t!("foo/.",
2847            iter: ["foo"],
2848            has_root: false,
2849            is_absolute: false,
2850            parent: Some(""),
2851            file_name: Some("foo"),
2852            file_stem: Some("foo"),
2853            extension: None
2854            );
2855
2856         t!("foo/..",
2857            iter: ["foo", ".."],
2858            has_root: false,
2859            is_absolute: false,
2860            parent: Some("foo"),
2861            file_name: None,
2862            file_stem: None,
2863            extension: None
2864            );
2865
2866         t!("foo/./",
2867            iter: ["foo"],
2868            has_root: false,
2869            is_absolute: false,
2870            parent: Some(""),
2871            file_name: Some("foo"),
2872            file_stem: Some("foo"),
2873            extension: None
2874            );
2875
2876         t!("foo/./bar",
2877            iter: ["foo", "bar"],
2878            has_root: false,
2879            is_absolute: false,
2880            parent: Some("foo"),
2881            file_name: Some("bar"),
2882            file_stem: Some("bar"),
2883            extension: None
2884            );
2885
2886         t!("foo/../",
2887            iter: ["foo", ".."],
2888            has_root: false,
2889            is_absolute: false,
2890            parent: Some("foo"),
2891            file_name: None,
2892            file_stem: None,
2893            extension: None
2894            );
2895
2896         t!("foo/../bar",
2897            iter: ["foo", "..", "bar"],
2898            has_root: false,
2899            is_absolute: false,
2900            parent: Some("foo/.."),
2901            file_name: Some("bar"),
2902            file_stem: Some("bar"),
2903            extension: None
2904            );
2905
2906         t!("./a",
2907            iter: [".", "a"],
2908            has_root: false,
2909            is_absolute: false,
2910            parent: Some("."),
2911            file_name: Some("a"),
2912            file_stem: Some("a"),
2913            extension: None
2914            );
2915
2916         t!(".",
2917            iter: ["."],
2918            has_root: false,
2919            is_absolute: false,
2920            parent: Some(""),
2921            file_name: None,
2922            file_stem: None,
2923            extension: None
2924            );
2925
2926         t!("./",
2927            iter: ["."],
2928            has_root: false,
2929            is_absolute: false,
2930            parent: Some(""),
2931            file_name: None,
2932            file_stem: None,
2933            extension: None
2934            );
2935
2936         t!("a/b",
2937            iter: ["a", "b"],
2938            has_root: false,
2939            is_absolute: false,
2940            parent: Some("a"),
2941            file_name: Some("b"),
2942            file_stem: Some("b"),
2943            extension: None
2944            );
2945
2946         t!("a//b",
2947            iter: ["a", "b"],
2948            has_root: false,
2949            is_absolute: false,
2950            parent: Some("a"),
2951            file_name: Some("b"),
2952            file_stem: Some("b"),
2953            extension: None
2954            );
2955
2956         t!("a/./b",
2957            iter: ["a", "b"],
2958            has_root: false,
2959            is_absolute: false,
2960            parent: Some("a"),
2961            file_name: Some("b"),
2962            file_stem: Some("b"),
2963            extension: None
2964            );
2965
2966         t!("a/b/c",
2967            iter: ["a", "b", "c"],
2968            has_root: false,
2969            is_absolute: false,
2970            parent: Some("a/b"),
2971            file_name: Some("c"),
2972            file_stem: Some("c"),
2973            extension: None);
2974
2975         t!("a\\b\\c",
2976            iter: ["a", "b", "c"],
2977            has_root: false,
2978            is_absolute: false,
2979            parent: Some("a\\b"),
2980            file_name: Some("c"),
2981            file_stem: Some("c"),
2982            extension: None
2983            );
2984
2985         t!("\\a",
2986            iter: ["\\", "a"],
2987            has_root: true,
2988            is_absolute: false,
2989            parent: Some("\\"),
2990            file_name: Some("a"),
2991            file_stem: Some("a"),
2992            extension: None
2993            );
2994
2995         t!("c:\\foo.txt",
2996            iter: ["c:", "\\", "foo.txt"],
2997            has_root: true,
2998            is_absolute: true,
2999            parent: Some("c:\\"),
3000            file_name: Some("foo.txt"),
3001            file_stem: Some("foo"),
3002            extension: Some("txt")
3003            );
3004
3005         t!("\\\\server\\share\\foo.txt",
3006            iter: ["\\\\server\\share", "\\", "foo.txt"],
3007            has_root: true,
3008            is_absolute: true,
3009            parent: Some("\\\\server\\share\\"),
3010            file_name: Some("foo.txt"),
3011            file_stem: Some("foo"),
3012            extension: Some("txt")
3013            );
3014
3015         t!("\\\\server\\share",
3016            iter: ["\\\\server\\share", "\\"],
3017            has_root: true,
3018            is_absolute: true,
3019            parent: None,
3020            file_name: None,
3021            file_stem: None,
3022            extension: None
3023            );
3024
3025         t!("\\\\server",
3026            iter: ["\\", "server"],
3027            has_root: true,
3028            is_absolute: false,
3029            parent: Some("\\"),
3030            file_name: Some("server"),
3031            file_stem: Some("server"),
3032            extension: None
3033            );
3034
3035         t!("\\\\?\\bar\\foo.txt",
3036            iter: ["\\\\?\\bar", "\\", "foo.txt"],
3037            has_root: true,
3038            is_absolute: true,
3039            parent: Some("\\\\?\\bar\\"),
3040            file_name: Some("foo.txt"),
3041            file_stem: Some("foo"),
3042            extension: Some("txt")
3043            );
3044
3045         t!("\\\\?\\bar",
3046            iter: ["\\\\?\\bar"],
3047            has_root: true,
3048            is_absolute: true,
3049            parent: None,
3050            file_name: None,
3051            file_stem: None,
3052            extension: None
3053            );
3054
3055         t!("\\\\?\\",
3056            iter: ["\\\\?\\"],
3057            has_root: true,
3058            is_absolute: true,
3059            parent: None,
3060            file_name: None,
3061            file_stem: None,
3062            extension: None
3063            );
3064
3065         t!("\\\\?\\UNC\\server\\share\\foo.txt",
3066            iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3067            has_root: true,
3068            is_absolute: true,
3069            parent: Some("\\\\?\\UNC\\server\\share\\"),
3070            file_name: Some("foo.txt"),
3071            file_stem: Some("foo"),
3072            extension: Some("txt")
3073            );
3074
3075         t!("\\\\?\\UNC\\server",
3076            iter: ["\\\\?\\UNC\\server"],
3077            has_root: true,
3078            is_absolute: true,
3079            parent: None,
3080            file_name: None,
3081            file_stem: None,
3082            extension: None
3083            );
3084
3085         t!("\\\\?\\UNC\\",
3086            iter: ["\\\\?\\UNC\\"],
3087            has_root: true,
3088            is_absolute: true,
3089            parent: None,
3090            file_name: None,
3091            file_stem: None,
3092            extension: None
3093            );
3094
3095         t!("\\\\?\\C:\\foo.txt",
3096            iter: ["\\\\?\\C:", "\\", "foo.txt"],
3097            has_root: true,
3098            is_absolute: true,
3099            parent: Some("\\\\?\\C:\\"),
3100            file_name: Some("foo.txt"),
3101            file_stem: Some("foo"),
3102            extension: Some("txt")
3103            );
3104
3105
3106         t!("\\\\?\\C:\\",
3107            iter: ["\\\\?\\C:", "\\"],
3108            has_root: true,
3109            is_absolute: true,
3110            parent: None,
3111            file_name: None,
3112            file_stem: None,
3113            extension: None
3114            );
3115
3116
3117         t!("\\\\?\\C:",
3118            iter: ["\\\\?\\C:"],
3119            has_root: true,
3120            is_absolute: true,
3121            parent: None,
3122            file_name: None,
3123            file_stem: None,
3124            extension: None
3125            );
3126
3127
3128         t!("\\\\?\\foo/bar",
3129            iter: ["\\\\?\\foo/bar"],
3130            has_root: true,
3131            is_absolute: true,
3132            parent: None,
3133            file_name: None,
3134            file_stem: None,
3135            extension: None
3136            );
3137
3138
3139         t!("\\\\?\\C:/foo",
3140            iter: ["\\\\?\\C:/foo"],
3141            has_root: true,
3142            is_absolute: true,
3143            parent: None,
3144            file_name: None,
3145            file_stem: None,
3146            extension: None
3147            );
3148
3149
3150         t!("\\\\.\\foo\\bar",
3151            iter: ["\\\\.\\foo", "\\", "bar"],
3152            has_root: true,
3153            is_absolute: true,
3154            parent: Some("\\\\.\\foo\\"),
3155            file_name: Some("bar"),
3156            file_stem: Some("bar"),
3157            extension: None
3158            );
3159
3160
3161         t!("\\\\.\\foo",
3162            iter: ["\\\\.\\foo", "\\"],
3163            has_root: true,
3164            is_absolute: true,
3165            parent: None,
3166            file_name: None,
3167            file_stem: None,
3168            extension: None
3169            );
3170
3171
3172         t!("\\\\.\\foo/bar",
3173            iter: ["\\\\.\\foo/bar", "\\"],
3174            has_root: true,
3175            is_absolute: true,
3176            parent: None,
3177            file_name: None,
3178            file_stem: None,
3179            extension: None
3180            );
3181
3182
3183         t!("\\\\.\\foo\\bar/baz",
3184            iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3185            has_root: true,
3186            is_absolute: true,
3187            parent: Some("\\\\.\\foo\\bar"),
3188            file_name: Some("baz"),
3189            file_stem: Some("baz"),
3190            extension: None
3191            );
3192
3193
3194         t!("\\\\.\\",
3195            iter: ["\\\\.\\", "\\"],
3196            has_root: true,
3197            is_absolute: true,
3198            parent: None,
3199            file_name: None,
3200            file_stem: None,
3201            extension: None
3202            );
3203
3204         t!("\\\\?\\a\\b\\",
3205            iter: ["\\\\?\\a", "\\", "b"],
3206            has_root: true,
3207            is_absolute: true,
3208            parent: Some("\\\\?\\a\\"),
3209            file_name: Some("b"),
3210            file_stem: Some("b"),
3211            extension: None
3212            );
3213     }
3214
3215     #[test]
3216     pub fn test_stem_ext() {
3217         t!("foo",
3218            file_stem: Some("foo"),
3219            extension: None
3220            );
3221
3222         t!("foo.",
3223            file_stem: Some("foo"),
3224            extension: Some("")
3225            );
3226
3227         t!(".foo",
3228            file_stem: Some(".foo"),
3229            extension: None
3230            );
3231
3232         t!("foo.txt",
3233            file_stem: Some("foo"),
3234            extension: Some("txt")
3235            );
3236
3237         t!("foo.bar.txt",
3238            file_stem: Some("foo.bar"),
3239            extension: Some("txt")
3240            );
3241
3242         t!("foo.bar.",
3243            file_stem: Some("foo.bar"),
3244            extension: Some("")
3245            );
3246
3247         t!(".",
3248            file_stem: None,
3249            extension: None
3250            );
3251
3252         t!("..",
3253            file_stem: None,
3254            extension: None
3255            );
3256
3257         t!("",
3258            file_stem: None,
3259            extension: None
3260            );
3261     }
3262
3263     #[test]
3264     pub fn test_push() {
3265         macro_rules! tp(
3266             ($path:expr, $push:expr, $expected:expr) => ( {
3267                 let mut actual = PathBuf::from($path);
3268                 actual.push($push);
3269                 assert!(actual.to_str() == Some($expected),
3270                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3271                         $push, $path, $expected, actual.to_str().unwrap());
3272             });
3273         );
3274
3275         if cfg!(unix) {
3276             tp!("", "foo", "foo");
3277             tp!("foo", "bar", "foo/bar");
3278             tp!("foo/", "bar", "foo/bar");
3279             tp!("foo//", "bar", "foo//bar");
3280             tp!("foo/.", "bar", "foo/./bar");
3281             tp!("foo./.", "bar", "foo././bar");
3282             tp!("foo", "", "foo/");
3283             tp!("foo", ".", "foo/.");
3284             tp!("foo", "..", "foo/..");
3285             tp!("foo", "/", "/");
3286             tp!("/foo/bar", "/", "/");
3287             tp!("/foo/bar", "/baz", "/baz");
3288             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3289         } else {
3290             tp!("", "foo", "foo");
3291             tp!("foo", "bar", r"foo\bar");
3292             tp!("foo/", "bar", r"foo/bar");
3293             tp!(r"foo\", "bar", r"foo\bar");
3294             tp!("foo//", "bar", r"foo//bar");
3295             tp!(r"foo\\", "bar", r"foo\\bar");
3296             tp!("foo/.", "bar", r"foo/.\bar");
3297             tp!("foo./.", "bar", r"foo./.\bar");
3298             tp!(r"foo\.", "bar", r"foo\.\bar");
3299             tp!(r"foo.\.", "bar", r"foo.\.\bar");
3300             tp!("foo", "", "foo\\");
3301             tp!("foo", ".", r"foo\.");
3302             tp!("foo", "..", r"foo\..");
3303             tp!("foo", "/", "/");
3304             tp!("foo", r"\", r"\");
3305             tp!("/foo/bar", "/", "/");
3306             tp!(r"\foo\bar", r"\", r"\");
3307             tp!("/foo/bar", "/baz", "/baz");
3308             tp!("/foo/bar", r"\baz", r"\baz");
3309             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3310             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3311
3312             tp!("c:\\", "windows", "c:\\windows");
3313             tp!("c:", "windows", "c:windows");
3314
3315             tp!("a\\b\\c", "d", "a\\b\\c\\d");
3316             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3317             tp!("a\\b", "c\\d", "a\\b\\c\\d");
3318             tp!("a\\b", "\\c\\d", "\\c\\d");
3319             tp!("a\\b", ".", "a\\b\\.");
3320             tp!("a\\b", "..\\c", "a\\b\\..\\c");
3321             tp!("a\\b", "C:a.txt", "C:a.txt");
3322             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3323             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3324             tp!("C:\\a\\b\\c", "C:d", "C:d");
3325             tp!("C:a\\b\\c", "C:d", "C:d");
3326             tp!("C:", r"a\b\c", r"C:a\b\c");
3327             tp!("C:", r"..\a", r"C:..\a");
3328             tp!("\\\\server\\share\\foo",
3329                 "bar",
3330                 "\\\\server\\share\\foo\\bar");
3331             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3332             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3333             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3334             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3335             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3336             tp!("\\\\?\\UNC\\server\\share\\foo",
3337                 "bar",
3338                 "\\\\?\\UNC\\server\\share\\foo\\bar");
3339             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3340             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3341
3342             // Note: modified from old path API
3343             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3344
3345             tp!("C:\\a",
3346                 "\\\\?\\UNC\\server\\share",
3347                 "\\\\?\\UNC\\server\\share");
3348             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3349             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3350             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3351             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3352
3353             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3354         }
3355     }
3356
3357     #[test]
3358     pub fn test_pop() {
3359         macro_rules! tp(
3360             ($path:expr, $expected:expr, $output:expr) => ( {
3361                 let mut actual = PathBuf::from($path);
3362                 let output = actual.pop();
3363                 assert!(actual.to_str() == Some($expected) && output == $output,
3364                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3365                         $path, $expected, $output,
3366                         actual.to_str().unwrap(), output);
3367             });
3368         );
3369
3370         tp!("", "", false);
3371         tp!("/", "/", false);
3372         tp!("foo", "", true);
3373         tp!(".", "", true);
3374         tp!("/foo", "/", true);
3375         tp!("/foo/bar", "/foo", true);
3376         tp!("foo/bar", "foo", true);
3377         tp!("foo/.", "", true);
3378         tp!("foo//bar", "foo", true);
3379
3380         if cfg!(windows) {
3381             tp!("a\\b\\c", "a\\b", true);
3382             tp!("\\a", "\\", true);
3383             tp!("\\", "\\", false);
3384
3385             tp!("C:\\a\\b", "C:\\a", true);
3386             tp!("C:\\a", "C:\\", true);
3387             tp!("C:\\", "C:\\", false);
3388             tp!("C:a\\b", "C:a", true);
3389             tp!("C:a", "C:", true);
3390             tp!("C:", "C:", false);
3391             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3392             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3393             tp!("\\\\server\\share", "\\\\server\\share", false);
3394             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3395             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3396             tp!("\\\\?\\a", "\\\\?\\a", false);
3397             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3398             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3399             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3400             tp!("\\\\?\\UNC\\server\\share\\a\\b",
3401                 "\\\\?\\UNC\\server\\share\\a",
3402                 true);
3403             tp!("\\\\?\\UNC\\server\\share\\a",
3404                 "\\\\?\\UNC\\server\\share\\",
3405                 true);
3406             tp!("\\\\?\\UNC\\server\\share",
3407                 "\\\\?\\UNC\\server\\share",
3408                 false);
3409             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3410             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3411             tp!("\\\\.\\a", "\\\\.\\a", false);
3412
3413             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3414         }
3415     }
3416
3417     #[test]
3418     pub fn test_set_file_name() {
3419         macro_rules! tfn(
3420                 ($path:expr, $file:expr, $expected:expr) => ( {
3421                 let mut p = PathBuf::from($path);
3422                 p.set_file_name($file);
3423                 assert!(p.to_str() == Some($expected),
3424                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3425                         $path, $file, $expected,
3426                         p.to_str().unwrap());
3427             });
3428         );
3429
3430         tfn!("foo", "foo", "foo");
3431         tfn!("foo", "bar", "bar");
3432         tfn!("foo", "", "");
3433         tfn!("", "foo", "foo");
3434         if cfg!(unix) {
3435             tfn!(".", "foo", "./foo");
3436             tfn!("foo/", "bar", "bar");
3437             tfn!("foo/.", "bar", "bar");
3438             tfn!("..", "foo", "../foo");
3439             tfn!("foo/..", "bar", "foo/../bar");
3440             tfn!("/", "foo", "/foo");
3441         } else {
3442             tfn!(".", "foo", r".\foo");
3443             tfn!(r"foo\", "bar", r"bar");
3444             tfn!(r"foo\.", "bar", r"bar");
3445             tfn!("..", "foo", r"..\foo");
3446             tfn!(r"foo\..", "bar", r"foo\..\bar");
3447             tfn!(r"\", "foo", r"\foo");
3448         }
3449     }
3450
3451     #[test]
3452     pub fn test_set_extension() {
3453         macro_rules! tfe(
3454                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3455                 let mut p = PathBuf::from($path);
3456                 let output = p.set_extension($ext);
3457                 assert!(p.to_str() == Some($expected) && output == $output,
3458                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3459                         $path, $ext, $expected, $output,
3460                         p.to_str().unwrap(), output);
3461             });
3462         );
3463
3464         tfe!("foo", "txt", "foo.txt", true);
3465         tfe!("foo.bar", "txt", "foo.txt", true);
3466         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3467         tfe!(".test", "txt", ".test.txt", true);
3468         tfe!("foo.txt", "", "foo", true);
3469         tfe!("foo", "", "foo", true);
3470         tfe!("", "foo", "", false);
3471         tfe!(".", "foo", ".", false);
3472         tfe!("foo/", "bar", "foo.bar", true);
3473         tfe!("foo/.", "bar", "foo.bar", true);
3474         tfe!("..", "foo", "..", false);
3475         tfe!("foo/..", "bar", "foo/..", false);
3476         tfe!("/", "foo", "/", false);
3477     }
3478
3479     #[test]
3480     fn test_eq_recievers() {
3481         use borrow::Cow;
3482
3483         let borrowed: &Path = Path::new("foo/bar");
3484         let mut owned: PathBuf = PathBuf::new();
3485         owned.push("foo");
3486         owned.push("bar");
3487         let borrowed_cow: Cow<Path> = borrowed.into();
3488         let owned_cow: Cow<Path> = owned.clone().into();
3489
3490         macro_rules! t {
3491             ($($current:expr),+) => {
3492                 $(
3493                     assert_eq!($current, borrowed);
3494                     assert_eq!($current, owned);
3495                     assert_eq!($current, borrowed_cow);
3496                     assert_eq!($current, owned_cow);
3497                 )+
3498             }
3499         }
3500
3501         t!(borrowed, owned, borrowed_cow, owned_cow);
3502     }
3503
3504     #[test]
3505     pub fn test_compare() {
3506         use hash::{Hash, Hasher};
3507         use collections::hash_map::DefaultHasher;
3508
3509         fn hash<T: Hash>(t: T) -> u64 {
3510             let mut s = DefaultHasher::new();
3511             t.hash(&mut s);
3512             s.finish()
3513         }
3514
3515         macro_rules! tc(
3516             ($path1:expr, $path2:expr, eq: $eq:expr,
3517              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3518              relative_from: $relative_from:expr) => ({
3519                  let path1 = Path::new($path1);
3520                  let path2 = Path::new($path2);
3521
3522                  let eq = path1 == path2;
3523                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3524                          $path1, $path2, $eq, eq);
3525                  assert!($eq == (hash(path1) == hash(path2)),
3526                          "{:?} == {:?}, expected {:?}, got {} and {}",
3527                          $path1, $path2, $eq, hash(path1), hash(path2));
3528
3529                  let starts_with = path1.starts_with(path2);
3530                  assert!(starts_with == $starts_with,
3531                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3532                          $starts_with, starts_with);
3533
3534                  let ends_with = path1.ends_with(path2);
3535                  assert!(ends_with == $ends_with,
3536                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3537                          $ends_with, ends_with);
3538
3539                  let relative_from = path1.strip_prefix(path2)
3540                                           .map(|p| p.to_str().unwrap())
3541                                           .ok();
3542                  let exp: Option<&str> = $relative_from;
3543                  assert!(relative_from == exp,
3544                          "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3545                          $path1, $path2, exp, relative_from);
3546             });
3547         );
3548
3549         tc!("", "",
3550             eq: true,
3551             starts_with: true,
3552             ends_with: true,
3553             relative_from: Some("")
3554             );
3555
3556         tc!("foo", "",
3557             eq: false,
3558             starts_with: true,
3559             ends_with: true,
3560             relative_from: Some("foo")
3561             );
3562
3563         tc!("", "foo",
3564             eq: false,
3565             starts_with: false,
3566             ends_with: false,
3567             relative_from: None
3568             );
3569
3570         tc!("foo", "foo",
3571             eq: true,
3572             starts_with: true,
3573             ends_with: true,
3574             relative_from: Some("")
3575             );
3576
3577         tc!("foo/", "foo",
3578             eq: true,
3579             starts_with: true,
3580             ends_with: true,
3581             relative_from: Some("")
3582             );
3583
3584         tc!("foo/bar", "foo",
3585             eq: false,
3586             starts_with: true,
3587             ends_with: false,
3588             relative_from: Some("bar")
3589             );
3590
3591         tc!("foo/bar/baz", "foo/bar",
3592             eq: false,
3593             starts_with: true,
3594             ends_with: false,
3595             relative_from: Some("baz")
3596             );
3597
3598         tc!("foo/bar", "foo/bar/baz",
3599             eq: false,
3600             starts_with: false,
3601             ends_with: false,
3602             relative_from: None
3603             );
3604
3605         tc!("./foo/bar/", ".",
3606             eq: false,
3607             starts_with: true,
3608             ends_with: false,
3609             relative_from: Some("foo/bar")
3610             );
3611
3612         if cfg!(windows) {
3613             tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3614                 r"c:\src\rust\cargo-test\test",
3615                 eq: false,
3616                 starts_with: true,
3617                 ends_with: false,
3618                 relative_from: Some("Cargo.toml")
3619                 );
3620
3621             tc!(r"c:\foo", r"C:\foo",
3622                 eq: true,
3623                 starts_with: true,
3624                 ends_with: true,
3625                 relative_from: Some("")
3626                 );
3627         }
3628     }
3629
3630     #[test]
3631     fn test_components_debug() {
3632         let path = Path::new("/tmp");
3633
3634         let mut components = path.components();
3635
3636         let expected = "Components([RootDir, Normal(\"tmp\")])";
3637         let actual = format!("{:?}", components);
3638         assert_eq!(expected, actual);
3639
3640         let _ = components.next().unwrap();
3641         let expected = "Components([Normal(\"tmp\")])";
3642         let actual = format!("{:?}", components);
3643         assert_eq!(expected, actual);
3644
3645         let _ = components.next().unwrap();
3646         let expected = "Components([])";
3647         let actual = format!("{:?}", components);
3648         assert_eq!(expected, actual);
3649     }
3650
3651     #[cfg(unix)]
3652     #[test]
3653     fn test_iter_debug() {
3654         let path = Path::new("/tmp");
3655
3656         let mut iter = path.iter();
3657
3658         let expected = "Iter([\"/\", \"tmp\"])";
3659         let actual = format!("{:?}", iter);
3660         assert_eq!(expected, actual);
3661
3662         let _ = iter.next().unwrap();
3663         let expected = "Iter([\"tmp\"])";
3664         let actual = format!("{:?}", iter);
3665         assert_eq!(expected, actual);
3666
3667         let _ = iter.next().unwrap();
3668         let expected = "Iter([])";
3669         let actual = format!("{:?}", iter);
3670         assert_eq!(expected, actual);
3671     }
3672 }