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