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