]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
Fix test
[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 sync::Arc;
92
93 use ffi::{OsStr, OsString};
94
95 use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
96
97 ////////////////////////////////////////////////////////////////////////////////
98 // GENERAL NOTES
99 ////////////////////////////////////////////////////////////////////////////////
100 //
101 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
102 // taking advantage of the fact that OsStr always encodes ASCII characters
103 // as-is.  Eventually, this transmutation should be replaced by direct uses of
104 // OsStr APIs for parsing, but it will take a while for those to become
105 // available.
106
107 ////////////////////////////////////////////////////////////////////////////////
108 // Windows Prefixes
109 ////////////////////////////////////////////////////////////////////////////////
110
111 /// Windows path prefixes, e.g. `C:` or `\\server\share`.
112 ///
113 /// Windows uses a variety of path prefix styles, including references to drive
114 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
115 /// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
116 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
117 /// no normalization is performed.
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// use std::path::{Component, Path, Prefix};
123 /// use std::path::Prefix::*;
124 /// use std::ffi::OsStr;
125 ///
126 /// fn get_path_prefix(s: &str) -> Prefix {
127 ///     let path = Path::new(s);
128 ///     match path.components().next().unwrap() {
129 ///         Component::Prefix(prefix_component) => prefix_component.kind(),
130 ///         _ => panic!(),
131 ///     }
132 /// }
133 ///
134 /// # if cfg!(windows) {
135 /// assert_eq!(Verbatim(OsStr::new("pictures")),
136 ///            get_path_prefix(r"\\?\pictures\kittens"));
137 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
138 ///            get_path_prefix(r"\\?\UNC\server\share"));
139 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
140 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
141 ///            get_path_prefix(r"\\.\BrainInterface"));
142 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
143 ///            get_path_prefix(r"\\server\share"));
144 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
145 /// # }
146 /// ```
147 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub enum Prefix<'a> {
150     /// Verbatim prefix, e.g. `\\?\cat_pics`.
151     ///
152     /// Verbatim prefixes consist of `\\?\` immediately followed by the given
153     /// component.
154     #[stable(feature = "rust1", since = "1.0.0")]
155     Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
156
157     /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
158     /// e.g. `\\?\UNC\server\share`.
159     ///
160     /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
161     /// server's hostname and a share name.
162     #[stable(feature = "rust1", since = "1.0.0")]
163     VerbatimUNC(
164         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
165         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
166     ),
167
168     /// Verbatim disk prefix, e.g. `\\?\C:\`.
169     ///
170     /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
171     /// drive letter and `:\`.
172     #[stable(feature = "rust1", since = "1.0.0")]
173     VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
174
175     /// Device namespace prefix, e.g. `\\.\COM42`.
176     ///
177     /// Device namespace prefixes consist of `\\.\` immediately followed by the
178     /// device name.
179     #[stable(feature = "rust1", since = "1.0.0")]
180     DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
181
182     /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
183     /// `\\server\share`.
184     ///
185     /// UNC prefixes consist of the server's hostname and a share name.
186     #[stable(feature = "rust1", since = "1.0.0")]
187     UNC(
188         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
189         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
190     ),
191
192     /// Prefix `C:` for the given disk drive.
193     #[stable(feature = "rust1", since = "1.0.0")]
194     Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
195 }
196
197 impl<'a> Prefix<'a> {
198     #[inline]
199     fn len(&self) -> usize {
200         use self::Prefix::*;
201         fn os_str_len(s: &OsStr) -> usize {
202             os_str_as_u8_slice(s).len()
203         }
204         match *self {
205             Verbatim(x) => 4 + os_str_len(x),
206             VerbatimUNC(x, y) => {
207                 8 + os_str_len(x) +
208                 if os_str_len(y) > 0 {
209                     1 + os_str_len(y)
210                 } else {
211                     0
212                 }
213             },
214             VerbatimDisk(_) => 6,
215             UNC(x, y) => {
216                 2 + os_str_len(x) +
217                 if os_str_len(y) > 0 {
218                     1 + os_str_len(y)
219                 } else {
220                     0
221                 }
222             },
223             DeviceNS(x) => 4 + os_str_len(x),
224             Disk(_) => 2,
225         }
226
227     }
228
229     /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
230     ///
231     /// # Examples
232     ///
233     /// ```
234     /// use std::path::Prefix::*;
235     /// use std::ffi::OsStr;
236     ///
237     /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
238     /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
239     /// assert!(VerbatimDisk(b'C').is_verbatim());
240     /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
241     /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
242     /// assert!(!Disk(b'C').is_verbatim());
243     /// ```
244     #[inline]
245     #[stable(feature = "rust1", since = "1.0.0")]
246     pub fn is_verbatim(&self) -> bool {
247         use self::Prefix::*;
248         match *self {
249             Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
250             _ => false,
251         }
252     }
253
254     #[inline]
255     fn is_drive(&self) -> bool {
256         match *self {
257             Prefix::Disk(_) => true,
258             _ => false,
259         }
260     }
261
262     #[inline]
263     fn has_implicit_root(&self) -> bool {
264         !self.is_drive()
265     }
266 }
267
268 ////////////////////////////////////////////////////////////////////////////////
269 // Exposed parsing helpers
270 ////////////////////////////////////////////////////////////////////////////////
271
272 /// Determines whether the character is one of the permitted path
273 /// separators for the current platform.
274 ///
275 /// # Examples
276 ///
277 /// ```
278 /// use std::path;
279 ///
280 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
281 /// assert!(!path::is_separator('❤'));
282 /// ```
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub fn is_separator(c: char) -> bool {
285     c.is_ascii() && is_sep_byte(c as u8)
286 }
287
288 /// The primary separator of path components for the current platform.
289 ///
290 /// For example, `/` on Unix and `\` on Windows.
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
293
294 ////////////////////////////////////////////////////////////////////////////////
295 // Misc helpers
296 ////////////////////////////////////////////////////////////////////////////////
297
298 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
299 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
300 // `iter` after having exhausted `prefix`.
301 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
302     where I: Iterator<Item = A> + Clone,
303           J: Iterator<Item = A>,
304           A: PartialEq
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 /// #![feature(path_ancestors)]
1048 ///
1049 /// use std::path::Path;
1050 ///
1051 /// let path = Path::new("/foo/bar");
1052 ///
1053 /// for ancestor in path.ancestors() {
1054 ///     println!("{}", ancestor.display());
1055 /// }
1056 /// ```
1057 ///
1058 /// [`ancestors`]: struct.Path.html#method.ancestors
1059 /// [`Path`]: struct.Path.html
1060 #[derive(Copy, Clone, Debug)]
1061 #[unstable(feature = "path_ancestors", issue = "48581")]
1062 pub struct Ancestors<'a> {
1063     next: Option<&'a Path>,
1064 }
1065
1066 #[unstable(feature = "path_ancestors", issue = "48581")]
1067 impl<'a> Iterator for Ancestors<'a> {
1068     type Item = &'a Path;
1069
1070     fn next(&mut self) -> Option<Self::Item> {
1071         let next = self.next;
1072         self.next = match next {
1073             Some(path) => path.parent(),
1074             None => None,
1075         };
1076         next
1077     }
1078 }
1079
1080 #[unstable(feature = "path_ancestors", issue = "48581")]
1081 impl<'a> FusedIterator for Ancestors<'a> {}
1082
1083 ////////////////////////////////////////////////////////////////////////////////
1084 // Basic types and traits
1085 ////////////////////////////////////////////////////////////////////////////////
1086
1087 /// An owned, mutable path (akin to [`String`]).
1088 ///
1089 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1090 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1091 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1092 ///
1093 /// [`String`]: ../string/struct.String.html
1094 /// [`Path`]: struct.Path.html
1095 /// [`push`]: struct.PathBuf.html#method.push
1096 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1097 /// [`Deref`]: ../ops/trait.Deref.html
1098 ///
1099 /// More details about the overall approach can be found in
1100 /// the [module documentation](index.html).
1101 ///
1102 /// # Examples
1103 ///
1104 /// You can use [`push`] to build up a `PathBuf` from
1105 /// components:
1106 ///
1107 /// ```
1108 /// use std::path::PathBuf;
1109 ///
1110 /// let mut path = PathBuf::new();
1111 ///
1112 /// path.push(r"C:\");
1113 /// path.push("windows");
1114 /// path.push("system32");
1115 ///
1116 /// path.set_extension("dll");
1117 /// ```
1118 ///
1119 /// However, [`push`] is best used for dynamic situations. This is a better way
1120 /// to do this when you know all of the components ahead of time:
1121 ///
1122 /// ```
1123 /// use std::path::PathBuf;
1124 ///
1125 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1126 /// ```
1127 ///
1128 /// We can still do better than this! Since these are all strings, we can use
1129 /// `From::from`:
1130 ///
1131 /// ```
1132 /// use std::path::PathBuf;
1133 ///
1134 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1135 /// ```
1136 ///
1137 /// Which method works best depends on what kind of situation you're in.
1138 #[derive(Clone)]
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub struct PathBuf {
1141     inner: OsString,
1142 }
1143
1144 impl PathBuf {
1145     fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1146         unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1147     }
1148
1149     /// Allocates an empty `PathBuf`.
1150     ///
1151     /// # Examples
1152     ///
1153     /// ```
1154     /// use std::path::PathBuf;
1155     ///
1156     /// let path = PathBuf::new();
1157     /// ```
1158     #[stable(feature = "rust1", since = "1.0.0")]
1159     pub fn new() -> PathBuf {
1160         PathBuf { inner: OsString::new() }
1161     }
1162
1163     /// Coerces to a [`Path`] slice.
1164     ///
1165     /// [`Path`]: struct.Path.html
1166     ///
1167     /// # Examples
1168     ///
1169     /// ```
1170     /// use std::path::{Path, PathBuf};
1171     ///
1172     /// let p = PathBuf::from("/test");
1173     /// assert_eq!(Path::new("/test"), p.as_path());
1174     /// ```
1175     #[stable(feature = "rust1", since = "1.0.0")]
1176     pub fn as_path(&self) -> &Path {
1177         self
1178     }
1179
1180     /// Extends `self` with `path`.
1181     ///
1182     /// If `path` is absolute, it replaces the current path.
1183     ///
1184     /// On Windows:
1185     ///
1186     /// * if `path` has a root but no prefix (e.g. `\windows`), it
1187     ///   replaces everything except for the prefix (if any) of `self`.
1188     /// * if `path` has a prefix but no root, it replaces `self`.
1189     ///
1190     /// # Examples
1191     ///
1192     /// Pushing a relative path extends the existing path:
1193     ///
1194     /// ```
1195     /// use std::path::PathBuf;
1196     ///
1197     /// let mut path = PathBuf::from("/tmp");
1198     /// path.push("file.bk");
1199     /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1200     /// ```
1201     ///
1202     /// Pushing an absolute path replaces the existing path:
1203     ///
1204     /// ```
1205     /// use std::path::PathBuf;
1206     ///
1207     /// let mut path = PathBuf::from("/tmp");
1208     /// path.push("/etc");
1209     /// assert_eq!(path, PathBuf::from("/etc"));
1210     /// ```
1211     #[stable(feature = "rust1", since = "1.0.0")]
1212     pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1213         self._push(path.as_ref())
1214     }
1215
1216     fn _push(&mut self, path: &Path) {
1217         // in general, a separator is needed if the rightmost byte is not a separator
1218         let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1219
1220         // in the special case of `C:` on Windows, do *not* add a separator
1221         {
1222             let comps = self.components();
1223             if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1224                comps.prefix.unwrap().is_drive() {
1225                 need_sep = false
1226             }
1227         }
1228
1229         // absolute `path` replaces `self`
1230         if path.is_absolute() || path.prefix().is_some() {
1231             self.as_mut_vec().truncate(0);
1232
1233         // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1234         } else if path.has_root() {
1235             let prefix_len = self.components().prefix_remaining();
1236             self.as_mut_vec().truncate(prefix_len);
1237
1238         // `path` is a pure relative path
1239         } else if need_sep {
1240             self.inner.push(MAIN_SEP_STR);
1241         }
1242
1243         self.inner.push(path);
1244     }
1245
1246     /// Truncates `self` to [`self.parent`].
1247     ///
1248     /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1249     /// Otherwise, returns `true`.
1250     ///
1251     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1252     /// [`self.parent`]: struct.PathBuf.html#method.parent
1253     /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1254     ///
1255     /// # Examples
1256     ///
1257     /// ```
1258     /// use std::path::{Path, PathBuf};
1259     ///
1260     /// let mut p = PathBuf::from("/test/test.rs");
1261     ///
1262     /// p.pop();
1263     /// assert_eq!(Path::new("/test"), p);
1264     /// p.pop();
1265     /// assert_eq!(Path::new("/"), p);
1266     /// ```
1267     #[stable(feature = "rust1", since = "1.0.0")]
1268     pub fn pop(&mut self) -> bool {
1269         match self.parent().map(|p| p.as_u8_slice().len()) {
1270             Some(len) => {
1271                 self.as_mut_vec().truncate(len);
1272                 true
1273             }
1274             None => false,
1275         }
1276     }
1277
1278     /// Updates [`self.file_name`] to `file_name`.
1279     ///
1280     /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1281     /// `file_name`.
1282     ///
1283     /// Otherwise it is equivalent to calling [`pop`] and then pushing
1284     /// `file_name`. The new path will be a sibling of the original path.
1285     /// (That is, it will have the same parent.)
1286     ///
1287     /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1288     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1289     /// [`pop`]: struct.PathBuf.html#method.pop
1290     ///
1291     /// # Examples
1292     ///
1293     /// ```
1294     /// use std::path::PathBuf;
1295     ///
1296     /// let mut buf = PathBuf::from("/");
1297     /// assert!(buf.file_name() == None);
1298     /// buf.set_file_name("bar");
1299     /// assert!(buf == PathBuf::from("/bar"));
1300     /// assert!(buf.file_name().is_some());
1301     /// buf.set_file_name("baz.txt");
1302     /// assert!(buf == PathBuf::from("/baz.txt"));
1303     /// ```
1304     #[stable(feature = "rust1", since = "1.0.0")]
1305     pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1306         self._set_file_name(file_name.as_ref())
1307     }
1308
1309     fn _set_file_name(&mut self, file_name: &OsStr) {
1310         if self.file_name().is_some() {
1311             let popped = self.pop();
1312             debug_assert!(popped);
1313         }
1314         self.push(file_name);
1315     }
1316
1317     /// Updates [`self.extension`] to `extension`.
1318     ///
1319     /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1320     /// returns `true` and updates the extension otherwise.
1321     ///
1322     /// If [`self.extension`] is [`None`], the extension is added; otherwise
1323     /// it is replaced.
1324     ///
1325     /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1326     /// [`self.extension`]: struct.PathBuf.html#method.extension
1327     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1328     ///
1329     /// # Examples
1330     ///
1331     /// ```
1332     /// use std::path::{Path, PathBuf};
1333     ///
1334     /// let mut p = PathBuf::from("/feel/the");
1335     ///
1336     /// p.set_extension("force");
1337     /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1338     ///
1339     /// p.set_extension("dark_side");
1340     /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1341     /// ```
1342     #[stable(feature = "rust1", since = "1.0.0")]
1343     pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1344         self._set_extension(extension.as_ref())
1345     }
1346
1347     fn _set_extension(&mut self, extension: &OsStr) -> bool {
1348         if self.file_name().is_none() {
1349             return false;
1350         }
1351
1352         let mut stem = match self.file_stem() {
1353             Some(stem) => stem.to_os_string(),
1354             None => OsString::new(),
1355         };
1356
1357         if !os_str_as_u8_slice(extension).is_empty() {
1358             stem.push(".");
1359             stem.push(extension);
1360         }
1361         self.set_file_name(&stem);
1362
1363         true
1364     }
1365
1366     /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1367     ///
1368     /// [`OsString`]: ../ffi/struct.OsString.html
1369     ///
1370     /// # Examples
1371     ///
1372     /// ```
1373     /// use std::path::PathBuf;
1374     ///
1375     /// let p = PathBuf::from("/the/head");
1376     /// let os_str = p.into_os_string();
1377     /// ```
1378     #[stable(feature = "rust1", since = "1.0.0")]
1379     pub fn into_os_string(self) -> OsString {
1380         self.inner
1381     }
1382
1383     /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1384     ///
1385     /// [`Box`]: ../../std/boxed/struct.Box.html
1386     /// [`Path`]: struct.Path.html
1387     #[stable(feature = "into_boxed_path", since = "1.20.0")]
1388     pub fn into_boxed_path(self) -> Box<Path> {
1389         let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1390         unsafe { Box::from_raw(rw) }
1391     }
1392 }
1393
1394 #[stable(feature = "box_from_path", since = "1.17.0")]
1395 impl<'a> From<&'a Path> for Box<Path> {
1396     fn from(path: &'a Path) -> Box<Path> {
1397         let boxed: Box<OsStr> = path.inner.into();
1398         let rw = Box::into_raw(boxed) as *mut Path;
1399         unsafe { Box::from_raw(rw) }
1400     }
1401 }
1402
1403 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1404 impl From<Box<Path>> for PathBuf {
1405     fn from(boxed: Box<Path>) -> PathBuf {
1406         boxed.into_path_buf()
1407     }
1408 }
1409
1410 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1411 impl From<PathBuf> for Box<Path> {
1412     fn from(p: PathBuf) -> Box<Path> {
1413         p.into_boxed_path()
1414     }
1415 }
1416
1417 #[stable(feature = "rust1", since = "1.0.0")]
1418 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1419     fn from(s: &'a T) -> PathBuf {
1420         PathBuf::from(s.as_ref().to_os_string())
1421     }
1422 }
1423
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl From<OsString> for PathBuf {
1426     fn from(s: OsString) -> PathBuf {
1427         PathBuf { inner: s }
1428     }
1429 }
1430
1431 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1432 impl From<PathBuf> for OsString {
1433     fn from(path_buf : PathBuf) -> OsString {
1434         path_buf.inner
1435     }
1436 }
1437
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl From<String> for PathBuf {
1440     fn from(s: String) -> PathBuf {
1441         PathBuf::from(OsString::from(s))
1442     }
1443 }
1444
1445 /// Error returned from [`PathBuf::from_str`][`from_str`].
1446 ///
1447 /// Note that parsing a path will never fail. This error is just a placeholder
1448 /// for implementing `FromStr` for `PathBuf`.
1449 ///
1450 /// [`from_str`]: struct.PathBuf.html#method.from_str
1451 #[derive(Debug, Clone, PartialEq, Eq)]
1452 #[stable(feature = "path_from_str", since = "1.26.0")]
1453 pub enum ParsePathError {}
1454
1455 #[stable(feature = "path_from_str", since = "1.26.0")]
1456 impl fmt::Display for ParsePathError {
1457     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
1458         match *self {}
1459     }
1460 }
1461
1462 #[stable(feature = "path_from_str", since = "1.26.0")]
1463 impl FromStr for PathBuf {
1464     type Err = ParsePathError;
1465
1466     fn from_str(s: &str) -> Result<Self, Self::Err> {
1467         Ok(PathBuf::from(s))
1468     }
1469 }
1470
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1473     fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1474         let mut buf = PathBuf::new();
1475         buf.extend(iter);
1476         buf
1477     }
1478 }
1479
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1482     fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1483         for p in iter {
1484             self.push(p.as_ref())
1485         }
1486     }
1487 }
1488
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl fmt::Debug for PathBuf {
1491     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1492         fmt::Debug::fmt(&**self, formatter)
1493     }
1494 }
1495
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 impl ops::Deref for PathBuf {
1498     type Target = Path;
1499
1500     fn deref(&self) -> &Path {
1501         Path::new(&self.inner)
1502     }
1503 }
1504
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl Borrow<Path> for PathBuf {
1507     fn borrow(&self) -> &Path {
1508         self.deref()
1509     }
1510 }
1511
1512 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1513 impl Default for PathBuf {
1514     fn default() -> Self {
1515         PathBuf::new()
1516     }
1517 }
1518
1519 #[stable(feature = "cow_from_path", since = "1.6.0")]
1520 impl<'a> From<&'a Path> for Cow<'a, Path> {
1521     #[inline]
1522     fn from(s: &'a Path) -> Cow<'a, Path> {
1523         Cow::Borrowed(s)
1524     }
1525 }
1526
1527 #[stable(feature = "cow_from_path", since = "1.6.0")]
1528 impl<'a> From<PathBuf> for Cow<'a, Path> {
1529     #[inline]
1530     fn from(s: PathBuf) -> Cow<'a, Path> {
1531         Cow::Owned(s)
1532     }
1533 }
1534
1535 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1536 impl From<PathBuf> for Arc<Path> {
1537     #[inline]
1538     fn from(s: PathBuf) -> Arc<Path> {
1539         let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1540         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1541     }
1542 }
1543
1544 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1545 impl<'a> From<&'a Path> for Arc<Path> {
1546     #[inline]
1547     fn from(s: &Path) -> Arc<Path> {
1548         let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1549         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1550     }
1551 }
1552
1553 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1554 impl From<PathBuf> for Rc<Path> {
1555     #[inline]
1556     fn from(s: PathBuf) -> Rc<Path> {
1557         let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1558         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1559     }
1560 }
1561
1562 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1563 impl<'a> From<&'a Path> for Rc<Path> {
1564     #[inline]
1565     fn from(s: &Path) -> Rc<Path> {
1566         let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1567         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1568     }
1569 }
1570
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 impl ToOwned for Path {
1573     type Owned = PathBuf;
1574     fn to_owned(&self) -> PathBuf {
1575         self.to_path_buf()
1576     }
1577     fn clone_into(&self, target: &mut PathBuf) {
1578         self.inner.clone_into(&mut target.inner);
1579     }
1580 }
1581
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl cmp::PartialEq for PathBuf {
1584     fn eq(&self, other: &PathBuf) -> bool {
1585         self.components() == other.components()
1586     }
1587 }
1588
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl Hash for PathBuf {
1591     fn hash<H: Hasher>(&self, h: &mut H) {
1592         self.as_path().hash(h)
1593     }
1594 }
1595
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl cmp::Eq for PathBuf {}
1598
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl cmp::PartialOrd for PathBuf {
1601     fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1602         self.components().partial_cmp(other.components())
1603     }
1604 }
1605
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 impl cmp::Ord for PathBuf {
1608     fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1609         self.components().cmp(other.components())
1610     }
1611 }
1612
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl AsRef<OsStr> for PathBuf {
1615     fn as_ref(&self) -> &OsStr {
1616         &self.inner[..]
1617     }
1618 }
1619
1620 /// A slice of a path (akin to [`str`]).
1621 ///
1622 /// This type supports a number of operations for inspecting a path, including
1623 /// breaking the path into its components (separated by `/` on Unix and by either
1624 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1625 /// is absolute, and so on.
1626 ///
1627 /// This is an *unsized* type, meaning that it must always be used behind a
1628 /// pointer like `&` or [`Box`]. For an owned version of this type,
1629 /// see [`PathBuf`].
1630 ///
1631 /// [`str`]: ../primitive.str.html
1632 /// [`Box`]: ../boxed/struct.Box.html
1633 /// [`PathBuf`]: struct.PathBuf.html
1634 ///
1635 /// More details about the overall approach can be found in
1636 /// the [module documentation](index.html).
1637 ///
1638 /// # Examples
1639 ///
1640 /// ```
1641 /// use std::path::Path;
1642 /// use std::ffi::OsStr;
1643 ///
1644 /// // Note: this example does work on Windows
1645 /// let path = Path::new("./foo/bar.txt");
1646 ///
1647 /// let parent = path.parent();
1648 /// assert_eq!(parent, Some(Path::new("./foo")));
1649 ///
1650 /// let file_stem = path.file_stem();
1651 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1652 ///
1653 /// let extension = path.extension();
1654 /// assert_eq!(extension, Some(OsStr::new("txt")));
1655 /// ```
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 pub struct Path {
1658     inner: OsStr,
1659 }
1660
1661 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1662 /// was not found.
1663 ///
1664 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1665 /// See its documentation for more.
1666 ///
1667 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1668 /// [`Path`]: struct.Path.html
1669 #[derive(Debug, Clone, PartialEq, Eq)]
1670 #[stable(since = "1.7.0", feature = "strip_prefix")]
1671 pub struct StripPrefixError(());
1672
1673 impl Path {
1674     // The following (private!) function allows construction of a path from a u8
1675     // slice, which is only safe when it is known to follow the OsStr encoding.
1676     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1677         Path::new(u8_slice_as_os_str(s))
1678     }
1679     // The following (private!) function reveals the byte encoding used for OsStr.
1680     fn as_u8_slice(&self) -> &[u8] {
1681         os_str_as_u8_slice(&self.inner)
1682     }
1683
1684     /// Directly wraps a string slice as a `Path` slice.
1685     ///
1686     /// This is a cost-free conversion.
1687     ///
1688     /// # Examples
1689     ///
1690     /// ```
1691     /// use std::path::Path;
1692     ///
1693     /// Path::new("foo.txt");
1694     /// ```
1695     ///
1696     /// You can create `Path`s from `String`s, or even other `Path`s:
1697     ///
1698     /// ```
1699     /// use std::path::Path;
1700     ///
1701     /// let string = String::from("foo.txt");
1702     /// let from_string = Path::new(&string);
1703     /// let from_path = Path::new(&from_string);
1704     /// assert_eq!(from_string, from_path);
1705     /// ```
1706     #[stable(feature = "rust1", since = "1.0.0")]
1707     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1708         unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1709     }
1710
1711     /// Yields the underlying [`OsStr`] slice.
1712     ///
1713     /// [`OsStr`]: ../ffi/struct.OsStr.html
1714     ///
1715     /// # Examples
1716     ///
1717     /// ```
1718     /// use std::path::Path;
1719     ///
1720     /// let os_str = Path::new("foo.txt").as_os_str();
1721     /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1722     /// ```
1723     #[stable(feature = "rust1", since = "1.0.0")]
1724     pub fn as_os_str(&self) -> &OsStr {
1725         &self.inner
1726     }
1727
1728     /// Yields a [`&str`] slice if the `Path` is valid unicode.
1729     ///
1730     /// This conversion may entail doing a check for UTF-8 validity.
1731     ///
1732     /// [`&str`]: ../primitive.str.html
1733     ///
1734     /// # Examples
1735     ///
1736     /// ```
1737     /// use std::path::Path;
1738     ///
1739     /// let path = Path::new("foo.txt");
1740     /// assert_eq!(path.to_str(), Some("foo.txt"));
1741     /// ```
1742     #[stable(feature = "rust1", since = "1.0.0")]
1743     pub fn to_str(&self) -> Option<&str> {
1744         self.inner.to_str()
1745     }
1746
1747     /// Converts a `Path` to a [`Cow<str>`].
1748     ///
1749     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1750     ///
1751     /// [`Cow<str>`]: ../borrow/enum.Cow.html
1752     ///
1753     /// # Examples
1754     ///
1755     /// Calling `to_string_lossy` on a `Path` with valid unicode:
1756     ///
1757     /// ```
1758     /// use std::path::Path;
1759     ///
1760     /// let path = Path::new("foo.txt");
1761     /// assert_eq!(path.to_string_lossy(), "foo.txt");
1762     /// ```
1763     ///
1764     /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1765     /// have returned `"fo�.txt"`.
1766     #[stable(feature = "rust1", since = "1.0.0")]
1767     pub fn to_string_lossy(&self) -> Cow<str> {
1768         self.inner.to_string_lossy()
1769     }
1770
1771     /// Converts a `Path` to an owned [`PathBuf`].
1772     ///
1773     /// [`PathBuf`]: struct.PathBuf.html
1774     ///
1775     /// # Examples
1776     ///
1777     /// ```
1778     /// use std::path::Path;
1779     ///
1780     /// let path_buf = Path::new("foo.txt").to_path_buf();
1781     /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1782     /// ```
1783     #[rustc_conversion_suggestion]
1784     #[stable(feature = "rust1", since = "1.0.0")]
1785     pub fn to_path_buf(&self) -> PathBuf {
1786         PathBuf::from(self.inner.to_os_string())
1787     }
1788
1789     /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
1790     /// the current directory.
1791     ///
1792     /// * On Unix, a path is absolute if it starts with the root, so
1793     /// `is_absolute` and [`has_root`] are equivalent.
1794     ///
1795     /// * On Windows, a path is absolute if it has a prefix and starts with the
1796     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1797     ///
1798     /// # Examples
1799     ///
1800     /// ```
1801     /// use std::path::Path;
1802     ///
1803     /// assert!(!Path::new("foo.txt").is_absolute());
1804     /// ```
1805     ///
1806     /// [`has_root`]: #method.has_root
1807     #[stable(feature = "rust1", since = "1.0.0")]
1808     #[allow(deprecated)]
1809     pub fn is_absolute(&self) -> bool {
1810         if cfg!(target_os = "redox") {
1811             // FIXME: Allow Redox prefixes
1812             self.has_root() || has_redox_scheme(self.as_u8_slice())
1813         } else {
1814             self.has_root() && (cfg!(unix) || self.prefix().is_some())
1815         }
1816     }
1817
1818     /// Returns `true` if the `Path` is relative, i.e. not absolute.
1819     ///
1820     /// See [`is_absolute`]'s documentation for more details.
1821     ///
1822     /// # Examples
1823     ///
1824     /// ```
1825     /// use std::path::Path;
1826     ///
1827     /// assert!(Path::new("foo.txt").is_relative());
1828     /// ```
1829     ///
1830     /// [`is_absolute`]: #method.is_absolute
1831     #[stable(feature = "rust1", since = "1.0.0")]
1832     pub fn is_relative(&self) -> bool {
1833         !self.is_absolute()
1834     }
1835
1836     fn prefix(&self) -> Option<Prefix> {
1837         self.components().prefix
1838     }
1839
1840     /// Returns `true` if the `Path` has a root.
1841     ///
1842     /// * On Unix, a path has a root if it begins with `/`.
1843     ///
1844     /// * On Windows, a path has a root if it:
1845     ///     * has no prefix and begins with a separator, e.g. `\\windows`
1846     ///     * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1847     ///     * has any non-disk prefix, e.g. `\\server\share`
1848     ///
1849     /// # Examples
1850     ///
1851     /// ```
1852     /// use std::path::Path;
1853     ///
1854     /// assert!(Path::new("/etc/passwd").has_root());
1855     /// ```
1856     #[stable(feature = "rust1", since = "1.0.0")]
1857     pub fn has_root(&self) -> bool {
1858         self.components().has_root()
1859     }
1860
1861     /// Returns the `Path` without its final component, if there is one.
1862     ///
1863     /// Returns [`None`] if the path terminates in a root or prefix.
1864     ///
1865     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1866     ///
1867     /// # Examples
1868     ///
1869     /// ```
1870     /// use std::path::Path;
1871     ///
1872     /// let path = Path::new("/foo/bar");
1873     /// let parent = path.parent().unwrap();
1874     /// assert_eq!(parent, Path::new("/foo"));
1875     ///
1876     /// let grand_parent = parent.parent().unwrap();
1877     /// assert_eq!(grand_parent, Path::new("/"));
1878     /// assert_eq!(grand_parent.parent(), None);
1879     /// ```
1880     #[stable(feature = "rust1", since = "1.0.0")]
1881     pub fn parent(&self) -> Option<&Path> {
1882         let mut comps = self.components();
1883         let comp = comps.next_back();
1884         comp.and_then(|p| {
1885             match p {
1886                 Component::Normal(_) |
1887                 Component::CurDir |
1888                 Component::ParentDir => Some(comps.as_path()),
1889                 _ => None,
1890             }
1891         })
1892     }
1893
1894     /// Produces an iterator over `Path` and its ancestors.
1895     ///
1896     /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1897     /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1898     /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1899     /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1900     /// namely `&self`.
1901     ///
1902     /// # Examples
1903     ///
1904     /// ```
1905     /// #![feature(path_ancestors)]
1906     ///
1907     /// use std::path::Path;
1908     ///
1909     /// let mut ancestors = Path::new("/foo/bar").ancestors();
1910     /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1911     /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1912     /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1913     /// assert_eq!(ancestors.next(), None);
1914     /// ```
1915     ///
1916     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1917     /// [`parent`]: struct.Path.html#method.parent
1918     #[unstable(feature = "path_ancestors", issue = "48581")]
1919     pub fn ancestors(&self) -> Ancestors {
1920         Ancestors {
1921             next: Some(&self),
1922         }
1923     }
1924
1925     /// Returns the final component of the `Path`, if there is one.
1926     ///
1927     /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1928     /// is the directory name.
1929     ///
1930     /// Returns [`None`] if the path terminates in `..`.
1931     ///
1932     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1933     ///
1934     /// # Examples
1935     ///
1936     /// ```
1937     /// use std::path::Path;
1938     /// use std::ffi::OsStr;
1939     ///
1940     /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1941     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1942     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1943     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1944     /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1945     /// assert_eq!(None, Path::new("/").file_name());
1946     /// ```
1947     #[stable(feature = "rust1", since = "1.0.0")]
1948     pub fn file_name(&self) -> Option<&OsStr> {
1949         self.components().next_back().and_then(|p| {
1950             match p {
1951                 Component::Normal(p) => Some(p.as_ref()),
1952                 _ => None,
1953             }
1954         })
1955     }
1956
1957     /// Returns a path that, when joined onto `base`, yields `self`.
1958     ///
1959     /// # Errors
1960     ///
1961     /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1962     /// returns `false`), returns [`Err`].
1963     ///
1964     /// [`starts_with`]: #method.starts_with
1965     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1966     ///
1967     /// # Examples
1968     ///
1969     /// ```
1970     /// use std::path::Path;
1971     ///
1972     /// let path = Path::new("/test/haha/foo.txt");
1973     ///
1974     /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
1975     /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1976     /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
1977     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
1978     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
1979     /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1980     /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1981     /// ```
1982     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1983     pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1984                                        -> Result<&'a Path, StripPrefixError>
1985         where P: AsRef<Path>
1986     {
1987         self._strip_prefix(base.as_ref())
1988     }
1989
1990     fn _strip_prefix<'a>(&'a self, base: &'a Path)
1991                          -> Result<&'a Path, StripPrefixError> {
1992         iter_after(self.components(), base.components())
1993             .map(|c| c.as_path())
1994             .ok_or(StripPrefixError(()))
1995     }
1996
1997     /// Determines whether `base` is a prefix of `self`.
1998     ///
1999     /// Only considers whole path components to match.
2000     ///
2001     /// # Examples
2002     ///
2003     /// ```
2004     /// use std::path::Path;
2005     ///
2006     /// let path = Path::new("/etc/passwd");
2007     ///
2008     /// assert!(path.starts_with("/etc"));
2009     /// assert!(path.starts_with("/etc/"));
2010     /// assert!(path.starts_with("/etc/passwd"));
2011     /// assert!(path.starts_with("/etc/passwd/"));
2012     ///
2013     /// assert!(!path.starts_with("/e"));
2014     /// ```
2015     #[stable(feature = "rust1", since = "1.0.0")]
2016     pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2017         self._starts_with(base.as_ref())
2018     }
2019
2020     fn _starts_with(&self, base: &Path) -> bool {
2021         iter_after(self.components(), base.components()).is_some()
2022     }
2023
2024     /// Determines whether `child` is a suffix of `self`.
2025     ///
2026     /// Only considers whole path components to match.
2027     ///
2028     /// # Examples
2029     ///
2030     /// ```
2031     /// use std::path::Path;
2032     ///
2033     /// let path = Path::new("/etc/passwd");
2034     ///
2035     /// assert!(path.ends_with("passwd"));
2036     /// ```
2037     #[stable(feature = "rust1", since = "1.0.0")]
2038     pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2039         self._ends_with(child.as_ref())
2040     }
2041
2042     fn _ends_with(&self, child: &Path) -> bool {
2043         iter_after(self.components().rev(), child.components().rev()).is_some()
2044     }
2045
2046     /// Extracts the stem (non-extension) portion of [`self.file_name`].
2047     ///
2048     /// [`self.file_name`]: struct.Path.html#method.file_name
2049     ///
2050     /// The stem is:
2051     ///
2052     /// * [`None`], if there is no file name;
2053     /// * The entire file name if there is no embedded `.`;
2054     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2055     /// * Otherwise, the portion of the file name before the final `.`
2056     ///
2057     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2058     ///
2059     /// # Examples
2060     ///
2061     /// ```
2062     /// use std::path::Path;
2063     ///
2064     /// let path = Path::new("foo.rs");
2065     ///
2066     /// assert_eq!("foo", path.file_stem().unwrap());
2067     /// ```
2068     #[stable(feature = "rust1", since = "1.0.0")]
2069     pub fn file_stem(&self) -> Option<&OsStr> {
2070         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2071     }
2072
2073     /// Extracts the extension of [`self.file_name`], if possible.
2074     ///
2075     /// The extension is:
2076     ///
2077     /// * [`None`], if there is no file name;
2078     /// * [`None`], if there is no embedded `.`;
2079     /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2080     /// * Otherwise, the portion of the file name after the final `.`
2081     ///
2082     /// [`self.file_name`]: struct.Path.html#method.file_name
2083     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2084     ///
2085     /// # Examples
2086     ///
2087     /// ```
2088     /// use std::path::Path;
2089     ///
2090     /// let path = Path::new("foo.rs");
2091     ///
2092     /// assert_eq!("rs", path.extension().unwrap());
2093     /// ```
2094     #[stable(feature = "rust1", since = "1.0.0")]
2095     pub fn extension(&self) -> Option<&OsStr> {
2096         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2097     }
2098
2099     /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2100     ///
2101     /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2102     ///
2103     /// [`PathBuf`]: struct.PathBuf.html
2104     /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2105     ///
2106     /// # Examples
2107     ///
2108     /// ```
2109     /// use std::path::{Path, PathBuf};
2110     ///
2111     /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2112     /// ```
2113     #[stable(feature = "rust1", since = "1.0.0")]
2114     pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2115         self._join(path.as_ref())
2116     }
2117
2118     fn _join(&self, path: &Path) -> PathBuf {
2119         let mut buf = self.to_path_buf();
2120         buf.push(path);
2121         buf
2122     }
2123
2124     /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2125     ///
2126     /// See [`PathBuf::set_file_name`] for more details.
2127     ///
2128     /// [`PathBuf`]: struct.PathBuf.html
2129     /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2130     ///
2131     /// # Examples
2132     ///
2133     /// ```
2134     /// use std::path::{Path, PathBuf};
2135     ///
2136     /// let path = Path::new("/tmp/foo.txt");
2137     /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2138     ///
2139     /// let path = Path::new("/tmp");
2140     /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2141     /// ```
2142     #[stable(feature = "rust1", since = "1.0.0")]
2143     pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2144         self._with_file_name(file_name.as_ref())
2145     }
2146
2147     fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2148         let mut buf = self.to_path_buf();
2149         buf.set_file_name(file_name);
2150         buf
2151     }
2152
2153     /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2154     ///
2155     /// See [`PathBuf::set_extension`] for more details.
2156     ///
2157     /// [`PathBuf`]: struct.PathBuf.html
2158     /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2159     ///
2160     /// # Examples
2161     ///
2162     /// ```
2163     /// use std::path::{Path, PathBuf};
2164     ///
2165     /// let path = Path::new("foo.rs");
2166     /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2167     /// ```
2168     #[stable(feature = "rust1", since = "1.0.0")]
2169     pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2170         self._with_extension(extension.as_ref())
2171     }
2172
2173     fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2174         let mut buf = self.to_path_buf();
2175         buf.set_extension(extension);
2176         buf
2177     }
2178
2179     /// Produces an iterator over the [`Component`]s of the path.
2180     ///
2181     /// When parsing the path, there is a small amount of normalization:
2182     ///
2183     /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2184     ///   `a` and `b` as components.
2185     ///
2186     /// * Occurrences of `.` are normalized away, except if they are at the
2187     ///   beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2188     ///   `a/b` all have `a` and `b` as components, but `./a/b` starts with
2189     ///   an additional [`CurDir`] component.
2190     ///
2191     /// Note that no other normalization takes place; in particular, `a/c`
2192     /// and `a/b/../c` are distinct, to account for the possibility that `b`
2193     /// is a symbolic link (so its parent isn't `a`).
2194     ///
2195     /// # Examples
2196     ///
2197     /// ```
2198     /// use std::path::{Path, Component};
2199     /// use std::ffi::OsStr;
2200     ///
2201     /// let mut components = Path::new("/tmp/foo.txt").components();
2202     ///
2203     /// assert_eq!(components.next(), Some(Component::RootDir));
2204     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2205     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2206     /// assert_eq!(components.next(), None)
2207     /// ```
2208     ///
2209     /// [`Component`]: enum.Component.html
2210     /// [`CurDir`]: enum.Component.html#variant.CurDir
2211     #[stable(feature = "rust1", since = "1.0.0")]
2212     pub fn components(&self) -> Components {
2213         let prefix = parse_prefix(self.as_os_str());
2214         Components {
2215             path: self.as_u8_slice(),
2216             prefix,
2217             has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2218                                has_redox_scheme(self.as_u8_slice()),
2219             front: State::Prefix,
2220             back: State::Body,
2221         }
2222     }
2223
2224     /// Produces an iterator over the path's components viewed as [`OsStr`]
2225     /// slices.
2226     ///
2227     /// For more information about the particulars of how the path is separated
2228     /// into components, see [`components`].
2229     ///
2230     /// [`components`]: #method.components
2231     /// [`OsStr`]: ../ffi/struct.OsStr.html
2232     ///
2233     /// # Examples
2234     ///
2235     /// ```
2236     /// use std::path::{self, Path};
2237     /// use std::ffi::OsStr;
2238     ///
2239     /// let mut it = Path::new("/tmp/foo.txt").iter();
2240     /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2241     /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2242     /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2243     /// assert_eq!(it.next(), None)
2244     /// ```
2245     #[stable(feature = "rust1", since = "1.0.0")]
2246     pub fn iter(&self) -> Iter {
2247         Iter { inner: self.components() }
2248     }
2249
2250     /// Returns an object that implements [`Display`] for safely printing paths
2251     /// that may contain non-Unicode data.
2252     ///
2253     /// [`Display`]: ../fmt/trait.Display.html
2254     ///
2255     /// # Examples
2256     ///
2257     /// ```
2258     /// use std::path::Path;
2259     ///
2260     /// let path = Path::new("/tmp/foo.rs");
2261     ///
2262     /// println!("{}", path.display());
2263     /// ```
2264     #[stable(feature = "rust1", since = "1.0.0")]
2265     pub fn display(&self) -> Display {
2266         Display { path: self }
2267     }
2268
2269     /// Queries the file system to get information about a file, directory, etc.
2270     ///
2271     /// This function will traverse symbolic links to query information about the
2272     /// destination file.
2273     ///
2274     /// This is an alias to [`fs::metadata`].
2275     ///
2276     /// [`fs::metadata`]: ../fs/fn.metadata.html
2277     ///
2278     /// # Examples
2279     ///
2280     /// ```no_run
2281     /// use std::path::Path;
2282     ///
2283     /// let path = Path::new("/Minas/tirith");
2284     /// let metadata = path.metadata().expect("metadata call failed");
2285     /// println!("{:?}", metadata.file_type());
2286     /// ```
2287     #[stable(feature = "path_ext", since = "1.5.0")]
2288     pub fn metadata(&self) -> io::Result<fs::Metadata> {
2289         fs::metadata(self)
2290     }
2291
2292     /// Queries the metadata about a file without following symlinks.
2293     ///
2294     /// This is an alias to [`fs::symlink_metadata`].
2295     ///
2296     /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2297     ///
2298     /// # Examples
2299     ///
2300     /// ```no_run
2301     /// use std::path::Path;
2302     ///
2303     /// let path = Path::new("/Minas/tirith");
2304     /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2305     /// println!("{:?}", metadata.file_type());
2306     /// ```
2307     #[stable(feature = "path_ext", since = "1.5.0")]
2308     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2309         fs::symlink_metadata(self)
2310     }
2311
2312     /// Returns the canonical form of the path with all intermediate components
2313     /// normalized and symbolic links resolved.
2314     ///
2315     /// This is an alias to [`fs::canonicalize`].
2316     ///
2317     /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2318     ///
2319     /// # Examples
2320     ///
2321     /// ```no_run
2322     /// use std::path::{Path, PathBuf};
2323     ///
2324     /// let path = Path::new("/foo/test/../test/bar.rs");
2325     /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2326     /// ```
2327     #[stable(feature = "path_ext", since = "1.5.0")]
2328     pub fn canonicalize(&self) -> io::Result<PathBuf> {
2329         fs::canonicalize(self)
2330     }
2331
2332     /// Reads a symbolic link, returning the file that the link points to.
2333     ///
2334     /// This is an alias to [`fs::read_link`].
2335     ///
2336     /// [`fs::read_link`]: ../fs/fn.read_link.html
2337     ///
2338     /// # Examples
2339     ///
2340     /// ```no_run
2341     /// use std::path::Path;
2342     ///
2343     /// let path = Path::new("/laputa/sky_castle.rs");
2344     /// let path_link = path.read_link().expect("read_link call failed");
2345     /// ```
2346     #[stable(feature = "path_ext", since = "1.5.0")]
2347     pub fn read_link(&self) -> io::Result<PathBuf> {
2348         fs::read_link(self)
2349     }
2350
2351     /// Returns an iterator over the entries within a directory.
2352     ///
2353     /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2354     /// errors may be encountered after an iterator is initially constructed.
2355     ///
2356     /// This is an alias to [`fs::read_dir`].
2357     ///
2358     /// [`io::Result`]: ../io/type.Result.html
2359     /// [`DirEntry`]: ../fs/struct.DirEntry.html
2360     /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2361     ///
2362     /// # Examples
2363     ///
2364     /// ```no_run
2365     /// use std::path::Path;
2366     ///
2367     /// let path = Path::new("/laputa");
2368     /// for entry in path.read_dir().expect("read_dir call failed") {
2369     ///     if let Ok(entry) = entry {
2370     ///         println!("{:?}", entry.path());
2371     ///     }
2372     /// }
2373     /// ```
2374     #[stable(feature = "path_ext", since = "1.5.0")]
2375     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2376         fs::read_dir(self)
2377     }
2378
2379     /// Returns whether the path points at an existing entity.
2380     ///
2381     /// This function will traverse symbolic links to query information about the
2382     /// destination file. In case of broken symbolic links this will return `false`.
2383     ///
2384     /// If you cannot access the directory containing the file, e.g. because of a
2385     /// permission error, this will return `false`.
2386     ///
2387     /// # Examples
2388     ///
2389     /// ```no_run
2390     /// use std::path::Path;
2391     /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2392     /// ```
2393     ///
2394     /// # See Also
2395     ///
2396     /// This is a convenience function that coerces errors to false. If you want to
2397     /// check errors, call [fs::metadata].
2398     ///
2399     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2400     #[stable(feature = "path_ext", since = "1.5.0")]
2401     pub fn exists(&self) -> bool {
2402         fs::metadata(self).is_ok()
2403     }
2404
2405     /// Returns whether the path exists on disk and is pointing at a regular file.
2406     ///
2407     /// This function will traverse symbolic links to query information about the
2408     /// destination file. In case of broken symbolic links this will return `false`.
2409     ///
2410     /// If you cannot access the directory containing the file, e.g. because of a
2411     /// permission error, this will return `false`.
2412     ///
2413     /// # Examples
2414     ///
2415     /// ```no_run
2416     /// use std::path::Path;
2417     /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2418     /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2419     /// ```
2420     ///
2421     /// # See Also
2422     ///
2423     /// This is a convenience function that coerces errors to false. If you want to
2424     /// check errors, call [fs::metadata] and handle its Result. Then call
2425     /// [fs::Metadata::is_file] if it was Ok.
2426     ///
2427     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2428     /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2429     #[stable(feature = "path_ext", since = "1.5.0")]
2430     pub fn is_file(&self) -> bool {
2431         fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2432     }
2433
2434     /// Returns whether the path exists on disk and is pointing at a directory.
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_dir(), true);
2447     /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
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_dir] if it was Ok.
2455     ///
2456     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2457     /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2458     #[stable(feature = "path_ext", since = "1.5.0")]
2459     pub fn is_dir(&self) -> bool {
2460         fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2461     }
2462
2463     /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2464     /// allocating.
2465     ///
2466     /// [`Box`]: ../../std/boxed/struct.Box.html
2467     /// [`PathBuf`]: struct.PathBuf.html
2468     #[stable(feature = "into_boxed_path", since = "1.20.0")]
2469     pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2470         let rw = Box::into_raw(self) as *mut OsStr;
2471         let inner = unsafe { Box::from_raw(rw) };
2472         PathBuf { inner: OsString::from(inner) }
2473     }
2474 }
2475
2476 #[stable(feature = "rust1", since = "1.0.0")]
2477 impl AsRef<OsStr> for Path {
2478     fn as_ref(&self) -> &OsStr {
2479         &self.inner
2480     }
2481 }
2482
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 impl fmt::Debug for Path {
2485     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2486         fmt::Debug::fmt(&self.inner, formatter)
2487     }
2488 }
2489
2490 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2491 ///
2492 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2493 /// [`Display`] trait in a way that mitigates that. It is created by the
2494 /// [`display`][`Path::display`] method on [`Path`].
2495 ///
2496 /// # Examples
2497 ///
2498 /// ```
2499 /// use std::path::Path;
2500 ///
2501 /// let path = Path::new("/tmp/foo.rs");
2502 ///
2503 /// println!("{}", path.display());
2504 /// ```
2505 ///
2506 /// [`Display`]: ../../std/fmt/trait.Display.html
2507 /// [`format!`]: ../../std/macro.format.html
2508 /// [`Path`]: struct.Path.html
2509 /// [`Path::display`]: struct.Path.html#method.display
2510 #[stable(feature = "rust1", since = "1.0.0")]
2511 pub struct Display<'a> {
2512     path: &'a Path,
2513 }
2514
2515 #[stable(feature = "rust1", since = "1.0.0")]
2516 impl<'a> fmt::Debug for Display<'a> {
2517     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2518         fmt::Debug::fmt(&self.path, f)
2519     }
2520 }
2521
2522 #[stable(feature = "rust1", since = "1.0.0")]
2523 impl<'a> fmt::Display for Display<'a> {
2524     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2525         self.path.inner.display(f)
2526     }
2527 }
2528
2529 #[stable(feature = "rust1", since = "1.0.0")]
2530 impl cmp::PartialEq for Path {
2531     fn eq(&self, other: &Path) -> bool {
2532         self.components().eq(other.components())
2533     }
2534 }
2535
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 impl Hash for Path {
2538     fn hash<H: Hasher>(&self, h: &mut H) {
2539         for component in self.components() {
2540             component.hash(h);
2541         }
2542     }
2543 }
2544
2545 #[stable(feature = "rust1", since = "1.0.0")]
2546 impl cmp::Eq for Path {}
2547
2548 #[stable(feature = "rust1", since = "1.0.0")]
2549 impl cmp::PartialOrd for Path {
2550     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2551         self.components().partial_cmp(other.components())
2552     }
2553 }
2554
2555 #[stable(feature = "rust1", since = "1.0.0")]
2556 impl cmp::Ord for Path {
2557     fn cmp(&self, other: &Path) -> cmp::Ordering {
2558         self.components().cmp(other.components())
2559     }
2560 }
2561
2562 #[stable(feature = "rust1", since = "1.0.0")]
2563 impl AsRef<Path> for Path {
2564     fn as_ref(&self) -> &Path {
2565         self
2566     }
2567 }
2568
2569 #[stable(feature = "rust1", since = "1.0.0")]
2570 impl AsRef<Path> for OsStr {
2571     fn as_ref(&self) -> &Path {
2572         Path::new(self)
2573     }
2574 }
2575
2576 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2577 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2578     fn as_ref(&self) -> &Path {
2579         Path::new(self)
2580     }
2581 }
2582
2583 #[stable(feature = "rust1", since = "1.0.0")]
2584 impl AsRef<Path> for OsString {
2585     fn as_ref(&self) -> &Path {
2586         Path::new(self)
2587     }
2588 }
2589
2590 #[stable(feature = "rust1", since = "1.0.0")]
2591 impl AsRef<Path> for str {
2592     fn as_ref(&self) -> &Path {
2593         Path::new(self)
2594     }
2595 }
2596
2597 #[stable(feature = "rust1", since = "1.0.0")]
2598 impl AsRef<Path> for String {
2599     fn as_ref(&self) -> &Path {
2600         Path::new(self)
2601     }
2602 }
2603
2604 #[stable(feature = "rust1", since = "1.0.0")]
2605 impl AsRef<Path> for PathBuf {
2606     fn as_ref(&self) -> &Path {
2607         self
2608     }
2609 }
2610
2611 #[stable(feature = "path_into_iter", since = "1.6.0")]
2612 impl<'a> IntoIterator for &'a PathBuf {
2613     type Item = &'a OsStr;
2614     type IntoIter = Iter<'a>;
2615     fn into_iter(self) -> Iter<'a> { self.iter() }
2616 }
2617
2618 #[stable(feature = "path_into_iter", since = "1.6.0")]
2619 impl<'a> IntoIterator for &'a Path {
2620     type Item = &'a OsStr;
2621     type IntoIter = Iter<'a>;
2622     fn into_iter(self) -> Iter<'a> { self.iter() }
2623 }
2624
2625 macro_rules! impl_cmp {
2626     ($lhs:ty, $rhs: ty) => {
2627         #[stable(feature = "partialeq_path", since = "1.6.0")]
2628         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2629             #[inline]
2630             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2631         }
2632
2633         #[stable(feature = "partialeq_path", since = "1.6.0")]
2634         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2635             #[inline]
2636             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2637         }
2638
2639         #[stable(feature = "cmp_path", since = "1.8.0")]
2640         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2641             #[inline]
2642             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2643                 <Path as PartialOrd>::partial_cmp(self, other)
2644             }
2645         }
2646
2647         #[stable(feature = "cmp_path", since = "1.8.0")]
2648         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2649             #[inline]
2650             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2651                 <Path as PartialOrd>::partial_cmp(self, other)
2652             }
2653         }
2654     }
2655 }
2656
2657 impl_cmp!(PathBuf, Path);
2658 impl_cmp!(PathBuf, &'a Path);
2659 impl_cmp!(Cow<'a, Path>, Path);
2660 impl_cmp!(Cow<'a, Path>, &'b Path);
2661 impl_cmp!(Cow<'a, Path>, PathBuf);
2662
2663 macro_rules! impl_cmp_os_str {
2664     ($lhs:ty, $rhs: ty) => {
2665         #[stable(feature = "cmp_path", since = "1.8.0")]
2666         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2667             #[inline]
2668             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2669         }
2670
2671         #[stable(feature = "cmp_path", since = "1.8.0")]
2672         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2673             #[inline]
2674             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2675         }
2676
2677         #[stable(feature = "cmp_path", since = "1.8.0")]
2678         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2679             #[inline]
2680             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2681                 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2682             }
2683         }
2684
2685         #[stable(feature = "cmp_path", since = "1.8.0")]
2686         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2687             #[inline]
2688             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2689                 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2690             }
2691         }
2692     }
2693 }
2694
2695 impl_cmp_os_str!(PathBuf, OsStr);
2696 impl_cmp_os_str!(PathBuf, &'a OsStr);
2697 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2698 impl_cmp_os_str!(PathBuf, OsString);
2699 impl_cmp_os_str!(Path, OsStr);
2700 impl_cmp_os_str!(Path, &'a OsStr);
2701 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2702 impl_cmp_os_str!(Path, OsString);
2703 impl_cmp_os_str!(&'a Path, OsStr);
2704 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2705 impl_cmp_os_str!(&'a Path, OsString);
2706 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2707 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2708 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2709
2710 #[stable(since = "1.7.0", feature = "strip_prefix")]
2711 impl fmt::Display for StripPrefixError {
2712     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2713         self.description().fmt(f)
2714     }
2715 }
2716
2717 #[stable(since = "1.7.0", feature = "strip_prefix")]
2718 impl Error for StripPrefixError {
2719     fn description(&self) -> &str { "prefix not found" }
2720 }
2721
2722 #[cfg(test)]
2723 mod tests {
2724     use super::*;
2725
2726     use rc::Rc;
2727     use sync::Arc;
2728
2729     macro_rules! t(
2730         ($path:expr, iter: $iter:expr) => (
2731             {
2732                 let path = Path::new($path);
2733
2734                 // Forward iteration
2735                 let comps = path.iter()
2736                     .map(|p| p.to_string_lossy().into_owned())
2737                     .collect::<Vec<String>>();
2738                 let exp: &[&str] = &$iter;
2739                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2740                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2741                         exps, comps);
2742
2743                 // Reverse iteration
2744                 let comps = Path::new($path).iter().rev()
2745                     .map(|p| p.to_string_lossy().into_owned())
2746                     .collect::<Vec<String>>();
2747                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2748                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2749                         exps, comps);
2750             }
2751         );
2752
2753         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2754             {
2755                 let path = Path::new($path);
2756
2757                 let act_root = path.has_root();
2758                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2759                         $has_root, act_root);
2760
2761                 let act_abs = path.is_absolute();
2762                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2763                         $is_absolute, act_abs);
2764             }
2765         );
2766
2767         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2768             {
2769                 let path = Path::new($path);
2770
2771                 let parent = path.parent().map(|p| p.to_str().unwrap());
2772                 let exp_parent: Option<&str> = $parent;
2773                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2774                         exp_parent, parent);
2775
2776                 let file = path.file_name().map(|p| p.to_str().unwrap());
2777                 let exp_file: Option<&str> = $file;
2778                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2779                         exp_file, file);
2780             }
2781         );
2782
2783         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2784             {
2785                 let path = Path::new($path);
2786
2787                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2788                 let exp_stem: Option<&str> = $file_stem;
2789                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2790                         exp_stem, stem);
2791
2792                 let ext = path.extension().map(|p| p.to_str().unwrap());
2793                 let exp_ext: Option<&str> = $extension;
2794                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2795                         exp_ext, ext);
2796             }
2797         );
2798
2799         ($path:expr, iter: $iter:expr,
2800                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2801                      parent: $parent:expr, file_name: $file:expr,
2802                      file_stem: $file_stem:expr, extension: $extension:expr) => (
2803             {
2804                 t!($path, iter: $iter);
2805                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2806                 t!($path, parent: $parent, file_name: $file);
2807                 t!($path, file_stem: $file_stem, extension: $extension);
2808             }
2809         );
2810     );
2811
2812     #[test]
2813     fn into() {
2814         use borrow::Cow;
2815
2816         let static_path = Path::new("/home/foo");
2817         let static_cow_path: Cow<'static, Path> = static_path.into();
2818         let pathbuf = PathBuf::from("/home/foo");
2819
2820         {
2821             let path: &Path = &pathbuf;
2822             let borrowed_cow_path: Cow<Path> = path.into();
2823
2824             assert_eq!(static_cow_path, borrowed_cow_path);
2825         }
2826
2827         let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2828
2829         assert_eq!(static_cow_path, owned_cow_path);
2830     }
2831
2832     #[test]
2833     #[cfg(unix)]
2834     pub fn test_decompositions_unix() {
2835         t!("",
2836            iter: [],
2837            has_root: false,
2838            is_absolute: false,
2839            parent: None,
2840            file_name: None,
2841            file_stem: None,
2842            extension: None
2843            );
2844
2845         t!("foo",
2846            iter: ["foo"],
2847            has_root: false,
2848            is_absolute: false,
2849            parent: Some(""),
2850            file_name: Some("foo"),
2851            file_stem: Some("foo"),
2852            extension: None
2853            );
2854
2855         t!("/",
2856            iter: ["/"],
2857            has_root: true,
2858            is_absolute: true,
2859            parent: None,
2860            file_name: None,
2861            file_stem: None,
2862            extension: None
2863            );
2864
2865         t!("/foo",
2866            iter: ["/", "foo"],
2867            has_root: true,
2868            is_absolute: true,
2869            parent: Some("/"),
2870            file_name: Some("foo"),
2871            file_stem: Some("foo"),
2872            extension: None
2873            );
2874
2875         t!("foo/",
2876            iter: ["foo"],
2877            has_root: false,
2878            is_absolute: false,
2879            parent: Some(""),
2880            file_name: Some("foo"),
2881            file_stem: Some("foo"),
2882            extension: None
2883            );
2884
2885         t!("/foo/",
2886            iter: ["/", "foo"],
2887            has_root: true,
2888            is_absolute: true,
2889            parent: Some("/"),
2890            file_name: Some("foo"),
2891            file_stem: Some("foo"),
2892            extension: None
2893            );
2894
2895         t!("foo/bar",
2896            iter: ["foo", "bar"],
2897            has_root: false,
2898            is_absolute: false,
2899            parent: Some("foo"),
2900            file_name: Some("bar"),
2901            file_stem: Some("bar"),
2902            extension: None
2903            );
2904
2905         t!("/foo/bar",
2906            iter: ["/", "foo", "bar"],
2907            has_root: true,
2908            is_absolute: true,
2909            parent: Some("/foo"),
2910            file_name: Some("bar"),
2911            file_stem: Some("bar"),
2912            extension: None
2913            );
2914
2915         t!("///foo///",
2916            iter: ["/", "foo"],
2917            has_root: true,
2918            is_absolute: true,
2919            parent: Some("/"),
2920            file_name: Some("foo"),
2921            file_stem: Some("foo"),
2922            extension: None
2923            );
2924
2925         t!("///foo///bar",
2926            iter: ["/", "foo", "bar"],
2927            has_root: true,
2928            is_absolute: true,
2929            parent: Some("///foo"),
2930            file_name: Some("bar"),
2931            file_stem: Some("bar"),
2932            extension: None
2933            );
2934
2935         t!("./.",
2936            iter: ["."],
2937            has_root: false,
2938            is_absolute: false,
2939            parent: Some(""),
2940            file_name: None,
2941            file_stem: None,
2942            extension: None
2943            );
2944
2945         t!("/..",
2946            iter: ["/", ".."],
2947            has_root: true,
2948            is_absolute: true,
2949            parent: Some("/"),
2950            file_name: None,
2951            file_stem: None,
2952            extension: None
2953            );
2954
2955         t!("../",
2956            iter: [".."],
2957            has_root: false,
2958            is_absolute: false,
2959            parent: Some(""),
2960            file_name: None,
2961            file_stem: None,
2962            extension: None
2963            );
2964
2965         t!("foo/.",
2966            iter: ["foo"],
2967            has_root: false,
2968            is_absolute: false,
2969            parent: Some(""),
2970            file_name: Some("foo"),
2971            file_stem: Some("foo"),
2972            extension: None
2973            );
2974
2975         t!("foo/..",
2976            iter: ["foo", ".."],
2977            has_root: false,
2978            is_absolute: false,
2979            parent: Some("foo"),
2980            file_name: None,
2981            file_stem: None,
2982            extension: None
2983            );
2984
2985         t!("foo/./",
2986            iter: ["foo"],
2987            has_root: false,
2988            is_absolute: false,
2989            parent: Some(""),
2990            file_name: Some("foo"),
2991            file_stem: Some("foo"),
2992            extension: None
2993            );
2994
2995         t!("foo/./bar",
2996            iter: ["foo", "bar"],
2997            has_root: false,
2998            is_absolute: false,
2999            parent: Some("foo"),
3000            file_name: Some("bar"),
3001            file_stem: Some("bar"),
3002            extension: None
3003            );
3004
3005         t!("foo/../",
3006            iter: ["foo", ".."],
3007            has_root: false,
3008            is_absolute: false,
3009            parent: Some("foo"),
3010            file_name: None,
3011            file_stem: None,
3012            extension: None
3013            );
3014
3015         t!("foo/../bar",
3016            iter: ["foo", "..", "bar"],
3017            has_root: false,
3018            is_absolute: false,
3019            parent: Some("foo/.."),
3020            file_name: Some("bar"),
3021            file_stem: Some("bar"),
3022            extension: None
3023            );
3024
3025         t!("./a",
3026            iter: [".", "a"],
3027            has_root: false,
3028            is_absolute: false,
3029            parent: Some("."),
3030            file_name: Some("a"),
3031            file_stem: Some("a"),
3032            extension: None
3033            );
3034
3035         t!(".",
3036            iter: ["."],
3037            has_root: false,
3038            is_absolute: false,
3039            parent: Some(""),
3040            file_name: None,
3041            file_stem: None,
3042            extension: None
3043            );
3044
3045         t!("./",
3046            iter: ["."],
3047            has_root: false,
3048            is_absolute: false,
3049            parent: Some(""),
3050            file_name: None,
3051            file_stem: None,
3052            extension: None
3053            );
3054
3055         t!("a/b",
3056            iter: ["a", "b"],
3057            has_root: false,
3058            is_absolute: false,
3059            parent: Some("a"),
3060            file_name: Some("b"),
3061            file_stem: Some("b"),
3062            extension: None
3063            );
3064
3065         t!("a//b",
3066            iter: ["a", "b"],
3067            has_root: false,
3068            is_absolute: false,
3069            parent: Some("a"),
3070            file_name: Some("b"),
3071            file_stem: Some("b"),
3072            extension: None
3073            );
3074
3075         t!("a/./b",
3076            iter: ["a", "b"],
3077            has_root: false,
3078            is_absolute: false,
3079            parent: Some("a"),
3080            file_name: Some("b"),
3081            file_stem: Some("b"),
3082            extension: None
3083            );
3084
3085         t!("a/b/c",
3086            iter: ["a", "b", "c"],
3087            has_root: false,
3088            is_absolute: false,
3089            parent: Some("a/b"),
3090            file_name: Some("c"),
3091            file_stem: Some("c"),
3092            extension: None
3093            );
3094
3095         t!(".foo",
3096            iter: [".foo"],
3097            has_root: false,
3098            is_absolute: false,
3099            parent: Some(""),
3100            file_name: Some(".foo"),
3101            file_stem: Some(".foo"),
3102            extension: None
3103            );
3104     }
3105
3106     #[test]
3107     #[cfg(windows)]
3108     pub fn test_decompositions_windows() {
3109         t!("",
3110            iter: [],
3111            has_root: false,
3112            is_absolute: false,
3113            parent: None,
3114            file_name: None,
3115            file_stem: None,
3116            extension: None
3117            );
3118
3119         t!("foo",
3120            iter: ["foo"],
3121            has_root: false,
3122            is_absolute: false,
3123            parent: Some(""),
3124            file_name: Some("foo"),
3125            file_stem: Some("foo"),
3126            extension: None
3127            );
3128
3129         t!("/",
3130            iter: ["\\"],
3131            has_root: true,
3132            is_absolute: false,
3133            parent: None,
3134            file_name: None,
3135            file_stem: None,
3136            extension: None
3137            );
3138
3139         t!("\\",
3140            iter: ["\\"],
3141            has_root: true,
3142            is_absolute: false,
3143            parent: None,
3144            file_name: None,
3145            file_stem: None,
3146            extension: None
3147            );
3148
3149         t!("c:",
3150            iter: ["c:"],
3151            has_root: false,
3152            is_absolute: false,
3153            parent: None,
3154            file_name: None,
3155            file_stem: None,
3156            extension: None
3157            );
3158
3159         t!("c:\\",
3160            iter: ["c:", "\\"],
3161            has_root: true,
3162            is_absolute: true,
3163            parent: None,
3164            file_name: None,
3165            file_stem: None,
3166            extension: None
3167            );
3168
3169         t!("c:/",
3170            iter: ["c:", "\\"],
3171            has_root: true,
3172            is_absolute: true,
3173            parent: None,
3174            file_name: None,
3175            file_stem: None,
3176            extension: None
3177            );
3178
3179         t!("/foo",
3180            iter: ["\\", "foo"],
3181            has_root: true,
3182            is_absolute: false,
3183            parent: Some("/"),
3184            file_name: Some("foo"),
3185            file_stem: Some("foo"),
3186            extension: None
3187            );
3188
3189         t!("foo/",
3190            iter: ["foo"],
3191            has_root: false,
3192            is_absolute: false,
3193            parent: Some(""),
3194            file_name: Some("foo"),
3195            file_stem: Some("foo"),
3196            extension: None
3197            );
3198
3199         t!("/foo/",
3200            iter: ["\\", "foo"],
3201            has_root: true,
3202            is_absolute: false,
3203            parent: Some("/"),
3204            file_name: Some("foo"),
3205            file_stem: Some("foo"),
3206            extension: None
3207            );
3208
3209         t!("foo/bar",
3210            iter: ["foo", "bar"],
3211            has_root: false,
3212            is_absolute: false,
3213            parent: Some("foo"),
3214            file_name: Some("bar"),
3215            file_stem: Some("bar"),
3216            extension: None
3217            );
3218
3219         t!("/foo/bar",
3220            iter: ["\\", "foo", "bar"],
3221            has_root: true,
3222            is_absolute: false,
3223            parent: Some("/foo"),
3224            file_name: Some("bar"),
3225            file_stem: Some("bar"),
3226            extension: None
3227            );
3228
3229         t!("///foo///",
3230            iter: ["\\", "foo"],
3231            has_root: true,
3232            is_absolute: false,
3233            parent: Some("/"),
3234            file_name: Some("foo"),
3235            file_stem: Some("foo"),
3236            extension: None
3237            );
3238
3239         t!("///foo///bar",
3240            iter: ["\\", "foo", "bar"],
3241            has_root: true,
3242            is_absolute: false,
3243            parent: Some("///foo"),
3244            file_name: Some("bar"),
3245            file_stem: Some("bar"),
3246            extension: None
3247            );
3248
3249         t!("./.",
3250            iter: ["."],
3251            has_root: false,
3252            is_absolute: false,
3253            parent: Some(""),
3254            file_name: None,
3255            file_stem: None,
3256            extension: None
3257            );
3258
3259         t!("/..",
3260            iter: ["\\", ".."],
3261            has_root: true,
3262            is_absolute: false,
3263            parent: Some("/"),
3264            file_name: None,
3265            file_stem: None,
3266            extension: None
3267            );
3268
3269         t!("../",
3270            iter: [".."],
3271            has_root: false,
3272            is_absolute: false,
3273            parent: Some(""),
3274            file_name: None,
3275            file_stem: None,
3276            extension: None
3277            );
3278
3279         t!("foo/.",
3280            iter: ["foo"],
3281            has_root: false,
3282            is_absolute: false,
3283            parent: Some(""),
3284            file_name: Some("foo"),
3285            file_stem: Some("foo"),
3286            extension: None
3287            );
3288
3289         t!("foo/..",
3290            iter: ["foo", ".."],
3291            has_root: false,
3292            is_absolute: false,
3293            parent: Some("foo"),
3294            file_name: None,
3295            file_stem: None,
3296            extension: None
3297            );
3298
3299         t!("foo/./",
3300            iter: ["foo"],
3301            has_root: false,
3302            is_absolute: false,
3303            parent: Some(""),
3304            file_name: Some("foo"),
3305            file_stem: Some("foo"),
3306            extension: None
3307            );
3308
3309         t!("foo/./bar",
3310            iter: ["foo", "bar"],
3311            has_root: false,
3312            is_absolute: false,
3313            parent: Some("foo"),
3314            file_name: Some("bar"),
3315            file_stem: Some("bar"),
3316            extension: None
3317            );
3318
3319         t!("foo/../",
3320            iter: ["foo", ".."],
3321            has_root: false,
3322            is_absolute: false,
3323            parent: Some("foo"),
3324            file_name: None,
3325            file_stem: None,
3326            extension: None
3327            );
3328
3329         t!("foo/../bar",
3330            iter: ["foo", "..", "bar"],
3331            has_root: false,
3332            is_absolute: false,
3333            parent: Some("foo/.."),
3334            file_name: Some("bar"),
3335            file_stem: Some("bar"),
3336            extension: None
3337            );
3338
3339         t!("./a",
3340            iter: [".", "a"],
3341            has_root: false,
3342            is_absolute: false,
3343            parent: Some("."),
3344            file_name: Some("a"),
3345            file_stem: Some("a"),
3346            extension: None
3347            );
3348
3349         t!(".",
3350            iter: ["."],
3351            has_root: false,
3352            is_absolute: false,
3353            parent: Some(""),
3354            file_name: None,
3355            file_stem: None,
3356            extension: None
3357            );
3358
3359         t!("./",
3360            iter: ["."],
3361            has_root: false,
3362            is_absolute: false,
3363            parent: Some(""),
3364            file_name: None,
3365            file_stem: None,
3366            extension: None
3367            );
3368
3369         t!("a/b",
3370            iter: ["a", "b"],
3371            has_root: false,
3372            is_absolute: false,
3373            parent: Some("a"),
3374            file_name: Some("b"),
3375            file_stem: Some("b"),
3376            extension: None
3377            );
3378
3379         t!("a//b",
3380            iter: ["a", "b"],
3381            has_root: false,
3382            is_absolute: false,
3383            parent: Some("a"),
3384            file_name: Some("b"),
3385            file_stem: Some("b"),
3386            extension: None
3387            );
3388
3389         t!("a/./b",
3390            iter: ["a", "b"],
3391            has_root: false,
3392            is_absolute: false,
3393            parent: Some("a"),
3394            file_name: Some("b"),
3395            file_stem: Some("b"),
3396            extension: None
3397            );
3398
3399         t!("a/b/c",
3400            iter: ["a", "b", "c"],
3401            has_root: false,
3402            is_absolute: false,
3403            parent: Some("a/b"),
3404            file_name: Some("c"),
3405            file_stem: Some("c"),
3406            extension: None);
3407
3408         t!("a\\b\\c",
3409            iter: ["a", "b", "c"],
3410            has_root: false,
3411            is_absolute: false,
3412            parent: Some("a\\b"),
3413            file_name: Some("c"),
3414            file_stem: Some("c"),
3415            extension: None
3416            );
3417
3418         t!("\\a",
3419            iter: ["\\", "a"],
3420            has_root: true,
3421            is_absolute: false,
3422            parent: Some("\\"),
3423            file_name: Some("a"),
3424            file_stem: Some("a"),
3425            extension: None
3426            );
3427
3428         t!("c:\\foo.txt",
3429            iter: ["c:", "\\", "foo.txt"],
3430            has_root: true,
3431            is_absolute: true,
3432            parent: Some("c:\\"),
3433            file_name: Some("foo.txt"),
3434            file_stem: Some("foo"),
3435            extension: Some("txt")
3436            );
3437
3438         t!("\\\\server\\share\\foo.txt",
3439            iter: ["\\\\server\\share", "\\", "foo.txt"],
3440            has_root: true,
3441            is_absolute: true,
3442            parent: Some("\\\\server\\share\\"),
3443            file_name: Some("foo.txt"),
3444            file_stem: Some("foo"),
3445            extension: Some("txt")
3446            );
3447
3448         t!("\\\\server\\share",
3449            iter: ["\\\\server\\share", "\\"],
3450            has_root: true,
3451            is_absolute: true,
3452            parent: None,
3453            file_name: None,
3454            file_stem: None,
3455            extension: None
3456            );
3457
3458         t!("\\\\server",
3459            iter: ["\\", "server"],
3460            has_root: true,
3461            is_absolute: false,
3462            parent: Some("\\"),
3463            file_name: Some("server"),
3464            file_stem: Some("server"),
3465            extension: None
3466            );
3467
3468         t!("\\\\?\\bar\\foo.txt",
3469            iter: ["\\\\?\\bar", "\\", "foo.txt"],
3470            has_root: true,
3471            is_absolute: true,
3472            parent: Some("\\\\?\\bar\\"),
3473            file_name: Some("foo.txt"),
3474            file_stem: Some("foo"),
3475            extension: Some("txt")
3476            );
3477
3478         t!("\\\\?\\bar",
3479            iter: ["\\\\?\\bar"],
3480            has_root: true,
3481            is_absolute: true,
3482            parent: None,
3483            file_name: None,
3484            file_stem: None,
3485            extension: None
3486            );
3487
3488         t!("\\\\?\\",
3489            iter: ["\\\\?\\"],
3490            has_root: true,
3491            is_absolute: true,
3492            parent: None,
3493            file_name: None,
3494            file_stem: None,
3495            extension: None
3496            );
3497
3498         t!("\\\\?\\UNC\\server\\share\\foo.txt",
3499            iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3500            has_root: true,
3501            is_absolute: true,
3502            parent: Some("\\\\?\\UNC\\server\\share\\"),
3503            file_name: Some("foo.txt"),
3504            file_stem: Some("foo"),
3505            extension: Some("txt")
3506            );
3507
3508         t!("\\\\?\\UNC\\server",
3509            iter: ["\\\\?\\UNC\\server"],
3510            has_root: true,
3511            is_absolute: true,
3512            parent: None,
3513            file_name: None,
3514            file_stem: None,
3515            extension: None
3516            );
3517
3518         t!("\\\\?\\UNC\\",
3519            iter: ["\\\\?\\UNC\\"],
3520            has_root: true,
3521            is_absolute: true,
3522            parent: None,
3523            file_name: None,
3524            file_stem: None,
3525            extension: None
3526            );
3527
3528         t!("\\\\?\\C:\\foo.txt",
3529            iter: ["\\\\?\\C:", "\\", "foo.txt"],
3530            has_root: true,
3531            is_absolute: true,
3532            parent: Some("\\\\?\\C:\\"),
3533            file_name: Some("foo.txt"),
3534            file_stem: Some("foo"),
3535            extension: Some("txt")
3536            );
3537
3538
3539         t!("\\\\?\\C:\\",
3540            iter: ["\\\\?\\C:", "\\"],
3541            has_root: true,
3542            is_absolute: true,
3543            parent: None,
3544            file_name: None,
3545            file_stem: None,
3546            extension: None
3547            );
3548
3549
3550         t!("\\\\?\\C:",
3551            iter: ["\\\\?\\C:"],
3552            has_root: true,
3553            is_absolute: true,
3554            parent: None,
3555            file_name: None,
3556            file_stem: None,
3557            extension: None
3558            );
3559
3560
3561         t!("\\\\?\\foo/bar",
3562            iter: ["\\\\?\\foo/bar"],
3563            has_root: true,
3564            is_absolute: true,
3565            parent: None,
3566            file_name: None,
3567            file_stem: None,
3568            extension: None
3569            );
3570
3571
3572         t!("\\\\?\\C:/foo",
3573            iter: ["\\\\?\\C:/foo"],
3574            has_root: true,
3575            is_absolute: true,
3576            parent: None,
3577            file_name: None,
3578            file_stem: None,
3579            extension: None
3580            );
3581
3582
3583         t!("\\\\.\\foo\\bar",
3584            iter: ["\\\\.\\foo", "\\", "bar"],
3585            has_root: true,
3586            is_absolute: true,
3587            parent: Some("\\\\.\\foo\\"),
3588            file_name: Some("bar"),
3589            file_stem: Some("bar"),
3590            extension: None
3591            );
3592
3593
3594         t!("\\\\.\\foo",
3595            iter: ["\\\\.\\foo", "\\"],
3596            has_root: true,
3597            is_absolute: true,
3598            parent: None,
3599            file_name: None,
3600            file_stem: None,
3601            extension: None
3602            );
3603
3604
3605         t!("\\\\.\\foo/bar",
3606            iter: ["\\\\.\\foo/bar", "\\"],
3607            has_root: true,
3608            is_absolute: true,
3609            parent: None,
3610            file_name: None,
3611            file_stem: None,
3612            extension: None
3613            );
3614
3615
3616         t!("\\\\.\\foo\\bar/baz",
3617            iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3618            has_root: true,
3619            is_absolute: true,
3620            parent: Some("\\\\.\\foo\\bar"),
3621            file_name: Some("baz"),
3622            file_stem: Some("baz"),
3623            extension: None
3624            );
3625
3626
3627         t!("\\\\.\\",
3628            iter: ["\\\\.\\", "\\"],
3629            has_root: true,
3630            is_absolute: true,
3631            parent: None,
3632            file_name: None,
3633            file_stem: None,
3634            extension: None
3635            );
3636
3637         t!("\\\\?\\a\\b\\",
3638            iter: ["\\\\?\\a", "\\", "b"],
3639            has_root: true,
3640            is_absolute: true,
3641            parent: Some("\\\\?\\a\\"),
3642            file_name: Some("b"),
3643            file_stem: Some("b"),
3644            extension: None
3645            );
3646     }
3647
3648     #[test]
3649     pub fn test_stem_ext() {
3650         t!("foo",
3651            file_stem: Some("foo"),
3652            extension: None
3653            );
3654
3655         t!("foo.",
3656            file_stem: Some("foo"),
3657            extension: Some("")
3658            );
3659
3660         t!(".foo",
3661            file_stem: Some(".foo"),
3662            extension: None
3663            );
3664
3665         t!("foo.txt",
3666            file_stem: Some("foo"),
3667            extension: Some("txt")
3668            );
3669
3670         t!("foo.bar.txt",
3671            file_stem: Some("foo.bar"),
3672            extension: Some("txt")
3673            );
3674
3675         t!("foo.bar.",
3676            file_stem: Some("foo.bar"),
3677            extension: Some("")
3678            );
3679
3680         t!(".",
3681            file_stem: None,
3682            extension: None
3683            );
3684
3685         t!("..",
3686            file_stem: None,
3687            extension: None
3688            );
3689
3690         t!("",
3691            file_stem: None,
3692            extension: None
3693            );
3694     }
3695
3696     #[test]
3697     pub fn test_push() {
3698         macro_rules! tp(
3699             ($path:expr, $push:expr, $expected:expr) => ( {
3700                 let mut actual = PathBuf::from($path);
3701                 actual.push($push);
3702                 assert!(actual.to_str() == Some($expected),
3703                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3704                         $push, $path, $expected, actual.to_str().unwrap());
3705             });
3706         );
3707
3708         if cfg!(unix) {
3709             tp!("", "foo", "foo");
3710             tp!("foo", "bar", "foo/bar");
3711             tp!("foo/", "bar", "foo/bar");
3712             tp!("foo//", "bar", "foo//bar");
3713             tp!("foo/.", "bar", "foo/./bar");
3714             tp!("foo./.", "bar", "foo././bar");
3715             tp!("foo", "", "foo/");
3716             tp!("foo", ".", "foo/.");
3717             tp!("foo", "..", "foo/..");
3718             tp!("foo", "/", "/");
3719             tp!("/foo/bar", "/", "/");
3720             tp!("/foo/bar", "/baz", "/baz");
3721             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3722         } else {
3723             tp!("", "foo", "foo");
3724             tp!("foo", "bar", r"foo\bar");
3725             tp!("foo/", "bar", r"foo/bar");
3726             tp!(r"foo\", "bar", r"foo\bar");
3727             tp!("foo//", "bar", r"foo//bar");
3728             tp!(r"foo\\", "bar", r"foo\\bar");
3729             tp!("foo/.", "bar", r"foo/.\bar");
3730             tp!("foo./.", "bar", r"foo./.\bar");
3731             tp!(r"foo\.", "bar", r"foo\.\bar");
3732             tp!(r"foo.\.", "bar", r"foo.\.\bar");
3733             tp!("foo", "", "foo\\");
3734             tp!("foo", ".", r"foo\.");
3735             tp!("foo", "..", r"foo\..");
3736             tp!("foo", "/", "/");
3737             tp!("foo", r"\", r"\");
3738             tp!("/foo/bar", "/", "/");
3739             tp!(r"\foo\bar", r"\", r"\");
3740             tp!("/foo/bar", "/baz", "/baz");
3741             tp!("/foo/bar", r"\baz", r"\baz");
3742             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3743             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3744
3745             tp!("c:\\", "windows", "c:\\windows");
3746             tp!("c:", "windows", "c:windows");
3747
3748             tp!("a\\b\\c", "d", "a\\b\\c\\d");
3749             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3750             tp!("a\\b", "c\\d", "a\\b\\c\\d");
3751             tp!("a\\b", "\\c\\d", "\\c\\d");
3752             tp!("a\\b", ".", "a\\b\\.");
3753             tp!("a\\b", "..\\c", "a\\b\\..\\c");
3754             tp!("a\\b", "C:a.txt", "C:a.txt");
3755             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3756             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3757             tp!("C:\\a\\b\\c", "C:d", "C:d");
3758             tp!("C:a\\b\\c", "C:d", "C:d");
3759             tp!("C:", r"a\b\c", r"C:a\b\c");
3760             tp!("C:", r"..\a", r"C:..\a");
3761             tp!("\\\\server\\share\\foo",
3762                 "bar",
3763                 "\\\\server\\share\\foo\\bar");
3764             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3765             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3766             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3767             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3768             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3769             tp!("\\\\?\\UNC\\server\\share\\foo",
3770                 "bar",
3771                 "\\\\?\\UNC\\server\\share\\foo\\bar");
3772             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3773             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3774
3775             // Note: modified from old path API
3776             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3777
3778             tp!("C:\\a",
3779                 "\\\\?\\UNC\\server\\share",
3780                 "\\\\?\\UNC\\server\\share");
3781             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3782             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3783             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3784             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3785
3786             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3787         }
3788     }
3789
3790     #[test]
3791     pub fn test_pop() {
3792         macro_rules! tp(
3793             ($path:expr, $expected:expr, $output:expr) => ( {
3794                 let mut actual = PathBuf::from($path);
3795                 let output = actual.pop();
3796                 assert!(actual.to_str() == Some($expected) && output == $output,
3797                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3798                         $path, $expected, $output,
3799                         actual.to_str().unwrap(), output);
3800             });
3801         );
3802
3803         tp!("", "", false);
3804         tp!("/", "/", false);
3805         tp!("foo", "", true);
3806         tp!(".", "", true);
3807         tp!("/foo", "/", true);
3808         tp!("/foo/bar", "/foo", true);
3809         tp!("foo/bar", "foo", true);
3810         tp!("foo/.", "", true);
3811         tp!("foo//bar", "foo", true);
3812
3813         if cfg!(windows) {
3814             tp!("a\\b\\c", "a\\b", true);
3815             tp!("\\a", "\\", true);
3816             tp!("\\", "\\", false);
3817
3818             tp!("C:\\a\\b", "C:\\a", true);
3819             tp!("C:\\a", "C:\\", true);
3820             tp!("C:\\", "C:\\", false);
3821             tp!("C:a\\b", "C:a", true);
3822             tp!("C:a", "C:", true);
3823             tp!("C:", "C:", false);
3824             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3825             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3826             tp!("\\\\server\\share", "\\\\server\\share", false);
3827             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3828             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3829             tp!("\\\\?\\a", "\\\\?\\a", false);
3830             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3831             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3832             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3833             tp!("\\\\?\\UNC\\server\\share\\a\\b",
3834                 "\\\\?\\UNC\\server\\share\\a",
3835                 true);
3836             tp!("\\\\?\\UNC\\server\\share\\a",
3837                 "\\\\?\\UNC\\server\\share\\",
3838                 true);
3839             tp!("\\\\?\\UNC\\server\\share",
3840                 "\\\\?\\UNC\\server\\share",
3841                 false);
3842             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3843             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3844             tp!("\\\\.\\a", "\\\\.\\a", false);
3845
3846             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3847         }
3848     }
3849
3850     #[test]
3851     pub fn test_set_file_name() {
3852         macro_rules! tfn(
3853                 ($path:expr, $file:expr, $expected:expr) => ( {
3854                 let mut p = PathBuf::from($path);
3855                 p.set_file_name($file);
3856                 assert!(p.to_str() == Some($expected),
3857                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3858                         $path, $file, $expected,
3859                         p.to_str().unwrap());
3860             });
3861         );
3862
3863         tfn!("foo", "foo", "foo");
3864         tfn!("foo", "bar", "bar");
3865         tfn!("foo", "", "");
3866         tfn!("", "foo", "foo");
3867         if cfg!(unix) {
3868             tfn!(".", "foo", "./foo");
3869             tfn!("foo/", "bar", "bar");
3870             tfn!("foo/.", "bar", "bar");
3871             tfn!("..", "foo", "../foo");
3872             tfn!("foo/..", "bar", "foo/../bar");
3873             tfn!("/", "foo", "/foo");
3874         } else {
3875             tfn!(".", "foo", r".\foo");
3876             tfn!(r"foo\", "bar", r"bar");
3877             tfn!(r"foo\.", "bar", r"bar");
3878             tfn!("..", "foo", r"..\foo");
3879             tfn!(r"foo\..", "bar", r"foo\..\bar");
3880             tfn!(r"\", "foo", r"\foo");
3881         }
3882     }
3883
3884     #[test]
3885     pub fn test_set_extension() {
3886         macro_rules! tfe(
3887                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3888                 let mut p = PathBuf::from($path);
3889                 let output = p.set_extension($ext);
3890                 assert!(p.to_str() == Some($expected) && output == $output,
3891                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3892                         $path, $ext, $expected, $output,
3893                         p.to_str().unwrap(), output);
3894             });
3895         );
3896
3897         tfe!("foo", "txt", "foo.txt", true);
3898         tfe!("foo.bar", "txt", "foo.txt", true);
3899         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3900         tfe!(".test", "txt", ".test.txt", true);
3901         tfe!("foo.txt", "", "foo", true);
3902         tfe!("foo", "", "foo", true);
3903         tfe!("", "foo", "", false);
3904         tfe!(".", "foo", ".", false);
3905         tfe!("foo/", "bar", "foo.bar", true);
3906         tfe!("foo/.", "bar", "foo.bar", true);
3907         tfe!("..", "foo", "..", false);
3908         tfe!("foo/..", "bar", "foo/..", false);
3909         tfe!("/", "foo", "/", false);
3910     }
3911
3912     #[test]
3913     fn test_eq_receivers() {
3914         use borrow::Cow;
3915
3916         let borrowed: &Path = Path::new("foo/bar");
3917         let mut owned: PathBuf = PathBuf::new();
3918         owned.push("foo");
3919         owned.push("bar");
3920         let borrowed_cow: Cow<Path> = borrowed.into();
3921         let owned_cow: Cow<Path> = owned.clone().into();
3922
3923         macro_rules! t {
3924             ($($current:expr),+) => {
3925                 $(
3926                     assert_eq!($current, borrowed);
3927                     assert_eq!($current, owned);
3928                     assert_eq!($current, borrowed_cow);
3929                     assert_eq!($current, owned_cow);
3930                 )+
3931             }
3932         }
3933
3934         t!(borrowed, owned, borrowed_cow, owned_cow);
3935     }
3936
3937     #[test]
3938     pub fn test_compare() {
3939         use hash::{Hash, Hasher};
3940         use collections::hash_map::DefaultHasher;
3941
3942         fn hash<T: Hash>(t: T) -> u64 {
3943             let mut s = DefaultHasher::new();
3944             t.hash(&mut s);
3945             s.finish()
3946         }
3947
3948         macro_rules! tc(
3949             ($path1:expr, $path2:expr, eq: $eq:expr,
3950              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3951              relative_from: $relative_from:expr) => ({
3952                  let path1 = Path::new($path1);
3953                  let path2 = Path::new($path2);
3954
3955                  let eq = path1 == path2;
3956                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3957                          $path1, $path2, $eq, eq);
3958                  assert!($eq == (hash(path1) == hash(path2)),
3959                          "{:?} == {:?}, expected {:?}, got {} and {}",
3960                          $path1, $path2, $eq, hash(path1), hash(path2));
3961
3962                  let starts_with = path1.starts_with(path2);
3963                  assert!(starts_with == $starts_with,
3964                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3965                          $starts_with, starts_with);
3966
3967                  let ends_with = path1.ends_with(path2);
3968                  assert!(ends_with == $ends_with,
3969                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3970                          $ends_with, ends_with);
3971
3972                  let relative_from = path1.strip_prefix(path2)
3973                                           .map(|p| p.to_str().unwrap())
3974                                           .ok();
3975                  let exp: Option<&str> = $relative_from;
3976                  assert!(relative_from == exp,
3977                          "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3978                          $path1, $path2, exp, relative_from);
3979             });
3980         );
3981
3982         tc!("", "",
3983             eq: true,
3984             starts_with: true,
3985             ends_with: true,
3986             relative_from: Some("")
3987             );
3988
3989         tc!("foo", "",
3990             eq: false,
3991             starts_with: true,
3992             ends_with: true,
3993             relative_from: Some("foo")
3994             );
3995
3996         tc!("", "foo",
3997             eq: false,
3998             starts_with: false,
3999             ends_with: false,
4000             relative_from: None
4001             );
4002
4003         tc!("foo", "foo",
4004             eq: true,
4005             starts_with: true,
4006             ends_with: true,
4007             relative_from: Some("")
4008             );
4009
4010         tc!("foo/", "foo",
4011             eq: true,
4012             starts_with: true,
4013             ends_with: true,
4014             relative_from: Some("")
4015             );
4016
4017         tc!("foo/bar", "foo",
4018             eq: false,
4019             starts_with: true,
4020             ends_with: false,
4021             relative_from: Some("bar")
4022             );
4023
4024         tc!("foo/bar/baz", "foo/bar",
4025             eq: false,
4026             starts_with: true,
4027             ends_with: false,
4028             relative_from: Some("baz")
4029             );
4030
4031         tc!("foo/bar", "foo/bar/baz",
4032             eq: false,
4033             starts_with: false,
4034             ends_with: false,
4035             relative_from: None
4036             );
4037
4038         tc!("./foo/bar/", ".",
4039             eq: false,
4040             starts_with: true,
4041             ends_with: false,
4042             relative_from: Some("foo/bar")
4043             );
4044
4045         if cfg!(windows) {
4046             tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4047                 r"c:\src\rust\cargo-test\test",
4048                 eq: false,
4049                 starts_with: true,
4050                 ends_with: false,
4051                 relative_from: Some("Cargo.toml")
4052                 );
4053
4054             tc!(r"c:\foo", r"C:\foo",
4055                 eq: true,
4056                 starts_with: true,
4057                 ends_with: true,
4058                 relative_from: Some("")
4059                 );
4060         }
4061     }
4062
4063     #[test]
4064     fn test_components_debug() {
4065         let path = Path::new("/tmp");
4066
4067         let mut components = path.components();
4068
4069         let expected = "Components([RootDir, Normal(\"tmp\")])";
4070         let actual = format!("{:?}", components);
4071         assert_eq!(expected, actual);
4072
4073         let _ = components.next().unwrap();
4074         let expected = "Components([Normal(\"tmp\")])";
4075         let actual = format!("{:?}", components);
4076         assert_eq!(expected, actual);
4077
4078         let _ = components.next().unwrap();
4079         let expected = "Components([])";
4080         let actual = format!("{:?}", components);
4081         assert_eq!(expected, actual);
4082     }
4083
4084     #[cfg(unix)]
4085     #[test]
4086     fn test_iter_debug() {
4087         let path = Path::new("/tmp");
4088
4089         let mut iter = path.iter();
4090
4091         let expected = "Iter([\"/\", \"tmp\"])";
4092         let actual = format!("{:?}", iter);
4093         assert_eq!(expected, actual);
4094
4095         let _ = iter.next().unwrap();
4096         let expected = "Iter([\"tmp\"])";
4097         let actual = format!("{:?}", iter);
4098         assert_eq!(expected, actual);
4099
4100         let _ = iter.next().unwrap();
4101         let expected = "Iter([])";
4102         let actual = format!("{:?}", iter);
4103         assert_eq!(expected, actual);
4104     }
4105
4106     #[test]
4107     fn into_boxed() {
4108         let orig: &str = "some/sort/of/path";
4109         let path = Path::new(orig);
4110         let boxed: Box<Path> = Box::from(path);
4111         let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4112         assert_eq!(path, &*boxed);
4113         assert_eq!(&*boxed, &*path_buf);
4114         assert_eq!(&*path_buf, path);
4115     }
4116
4117     #[test]
4118     fn test_clone_into() {
4119         let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4120         let path = Path::new("short");
4121         path.clone_into(&mut path_buf);
4122         assert_eq!(path, path_buf);
4123         assert!(path_buf.into_os_string().capacity() >= 15);
4124     }
4125
4126     #[test]
4127     fn display_format_flags() {
4128         assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4129         assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4130     }
4131
4132     #[test]
4133     fn into_rc() {
4134         let orig = "hello/world";
4135         let path = Path::new(orig);
4136         let rc: Rc<Path> = Rc::from(path);
4137         let arc: Arc<Path> = Arc::from(path);
4138
4139         assert_eq!(&*rc, path);
4140         assert_eq!(&*arc, path);
4141
4142         let rc2: Rc<Path> = Rc::from(path.to_owned());
4143         let arc2: Arc<Path> = Arc::from(path.to_owned());
4144
4145         assert_eq!(&*rc2, path);
4146         assert_eq!(&*arc2, path);
4147     }
4148 }