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