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