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