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