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