]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
Rollup merge of #66735 - SOF3:feature/str_strip, r=KodrAus
[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     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2790         self.description().fmt(f)
2791     }
2792 }
2793
2794 #[stable(since = "1.7.0", feature = "strip_prefix")]
2795 impl Error for StripPrefixError {
2796     fn description(&self) -> &str {
2797         "prefix not found"
2798     }
2799 }
2800
2801 #[cfg(test)]
2802 mod tests {
2803     use super::*;
2804
2805     use crate::rc::Rc;
2806     use crate::sync::Arc;
2807
2808     macro_rules! t(
2809         ($path:expr, iter: $iter:expr) => (
2810             {
2811                 let path = Path::new($path);
2812
2813                 // Forward iteration
2814                 let comps = path.iter()
2815                     .map(|p| p.to_string_lossy().into_owned())
2816                     .collect::<Vec<String>>();
2817                 let exp: &[&str] = &$iter;
2818                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2819                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2820                         exps, comps);
2821
2822                 // Reverse iteration
2823                 let comps = Path::new($path).iter().rev()
2824                     .map(|p| p.to_string_lossy().into_owned())
2825                     .collect::<Vec<String>>();
2826                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2827                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2828                         exps, comps);
2829             }
2830         );
2831
2832         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2833             {
2834                 let path = Path::new($path);
2835
2836                 let act_root = path.has_root();
2837                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2838                         $has_root, act_root);
2839
2840                 let act_abs = path.is_absolute();
2841                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2842                         $is_absolute, act_abs);
2843             }
2844         );
2845
2846         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2847             {
2848                 let path = Path::new($path);
2849
2850                 let parent = path.parent().map(|p| p.to_str().unwrap());
2851                 let exp_parent: Option<&str> = $parent;
2852                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2853                         exp_parent, parent);
2854
2855                 let file = path.file_name().map(|p| p.to_str().unwrap());
2856                 let exp_file: Option<&str> = $file;
2857                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2858                         exp_file, file);
2859             }
2860         );
2861
2862         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2863             {
2864                 let path = Path::new($path);
2865
2866                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2867                 let exp_stem: Option<&str> = $file_stem;
2868                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2869                         exp_stem, stem);
2870
2871                 let ext = path.extension().map(|p| p.to_str().unwrap());
2872                 let exp_ext: Option<&str> = $extension;
2873                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2874                         exp_ext, ext);
2875             }
2876         );
2877
2878         ($path:expr, iter: $iter:expr,
2879                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2880                      parent: $parent:expr, file_name: $file:expr,
2881                      file_stem: $file_stem:expr, extension: $extension:expr) => (
2882             {
2883                 t!($path, iter: $iter);
2884                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2885                 t!($path, parent: $parent, file_name: $file);
2886                 t!($path, file_stem: $file_stem, extension: $extension);
2887             }
2888         );
2889     );
2890
2891     #[test]
2892     fn into() {
2893         use crate::borrow::Cow;
2894
2895         let static_path = Path::new("/home/foo");
2896         let static_cow_path: Cow<'static, Path> = static_path.into();
2897         let pathbuf = PathBuf::from("/home/foo");
2898
2899         {
2900             let path: &Path = &pathbuf;
2901             let borrowed_cow_path: Cow<'_, Path> = path.into();
2902
2903             assert_eq!(static_cow_path, borrowed_cow_path);
2904         }
2905
2906         let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2907
2908         assert_eq!(static_cow_path, owned_cow_path);
2909     }
2910
2911     #[test]
2912     #[cfg(unix)]
2913     pub fn test_decompositions_unix() {
2914         t!("",
2915         iter: [],
2916         has_root: false,
2917         is_absolute: false,
2918         parent: None,
2919         file_name: None,
2920         file_stem: None,
2921         extension: None
2922         );
2923
2924         t!("foo",
2925         iter: ["foo"],
2926         has_root: false,
2927         is_absolute: false,
2928         parent: Some(""),
2929         file_name: Some("foo"),
2930         file_stem: Some("foo"),
2931         extension: None
2932         );
2933
2934         t!("/",
2935         iter: ["/"],
2936         has_root: true,
2937         is_absolute: true,
2938         parent: None,
2939         file_name: None,
2940         file_stem: None,
2941         extension: None
2942         );
2943
2944         t!("/foo",
2945         iter: ["/", "foo"],
2946         has_root: true,
2947         is_absolute: true,
2948         parent: Some("/"),
2949         file_name: Some("foo"),
2950         file_stem: Some("foo"),
2951         extension: None
2952         );
2953
2954         t!("foo/",
2955         iter: ["foo"],
2956         has_root: false,
2957         is_absolute: false,
2958         parent: Some(""),
2959         file_name: Some("foo"),
2960         file_stem: Some("foo"),
2961         extension: None
2962         );
2963
2964         t!("/foo/",
2965         iter: ["/", "foo"],
2966         has_root: true,
2967         is_absolute: true,
2968         parent: Some("/"),
2969         file_name: Some("foo"),
2970         file_stem: Some("foo"),
2971         extension: None
2972         );
2973
2974         t!("foo/bar",
2975         iter: ["foo", "bar"],
2976         has_root: false,
2977         is_absolute: false,
2978         parent: Some("foo"),
2979         file_name: Some("bar"),
2980         file_stem: Some("bar"),
2981         extension: None
2982         );
2983
2984         t!("/foo/bar",
2985         iter: ["/", "foo", "bar"],
2986         has_root: true,
2987         is_absolute: true,
2988         parent: Some("/foo"),
2989         file_name: Some("bar"),
2990         file_stem: Some("bar"),
2991         extension: None
2992         );
2993
2994         t!("///foo///",
2995         iter: ["/", "foo"],
2996         has_root: true,
2997         is_absolute: true,
2998         parent: Some("/"),
2999         file_name: Some("foo"),
3000         file_stem: Some("foo"),
3001         extension: None
3002         );
3003
3004         t!("///foo///bar",
3005         iter: ["/", "foo", "bar"],
3006         has_root: true,
3007         is_absolute: true,
3008         parent: Some("///foo"),
3009         file_name: Some("bar"),
3010         file_stem: Some("bar"),
3011         extension: None
3012         );
3013
3014         t!("./.",
3015         iter: ["."],
3016         has_root: false,
3017         is_absolute: false,
3018         parent: Some(""),
3019         file_name: None,
3020         file_stem: None,
3021         extension: None
3022         );
3023
3024         t!("/..",
3025         iter: ["/", ".."],
3026         has_root: true,
3027         is_absolute: true,
3028         parent: Some("/"),
3029         file_name: None,
3030         file_stem: None,
3031         extension: None
3032         );
3033
3034         t!("../",
3035         iter: [".."],
3036         has_root: false,
3037         is_absolute: false,
3038         parent: Some(""),
3039         file_name: None,
3040         file_stem: None,
3041         extension: None
3042         );
3043
3044         t!("foo/.",
3045         iter: ["foo"],
3046         has_root: false,
3047         is_absolute: false,
3048         parent: Some(""),
3049         file_name: Some("foo"),
3050         file_stem: Some("foo"),
3051         extension: None
3052         );
3053
3054         t!("foo/..",
3055         iter: ["foo", ".."],
3056         has_root: false,
3057         is_absolute: false,
3058         parent: Some("foo"),
3059         file_name: None,
3060         file_stem: None,
3061         extension: None
3062         );
3063
3064         t!("foo/./",
3065         iter: ["foo"],
3066         has_root: false,
3067         is_absolute: false,
3068         parent: Some(""),
3069         file_name: Some("foo"),
3070         file_stem: Some("foo"),
3071         extension: None
3072         );
3073
3074         t!("foo/./bar",
3075         iter: ["foo", "bar"],
3076         has_root: false,
3077         is_absolute: false,
3078         parent: Some("foo"),
3079         file_name: Some("bar"),
3080         file_stem: Some("bar"),
3081         extension: None
3082         );
3083
3084         t!("foo/../",
3085         iter: ["foo", ".."],
3086         has_root: false,
3087         is_absolute: false,
3088         parent: Some("foo"),
3089         file_name: None,
3090         file_stem: None,
3091         extension: None
3092         );
3093
3094         t!("foo/../bar",
3095         iter: ["foo", "..", "bar"],
3096         has_root: false,
3097         is_absolute: false,
3098         parent: Some("foo/.."),
3099         file_name: Some("bar"),
3100         file_stem: Some("bar"),
3101         extension: None
3102         );
3103
3104         t!("./a",
3105         iter: [".", "a"],
3106         has_root: false,
3107         is_absolute: false,
3108         parent: Some("."),
3109         file_name: Some("a"),
3110         file_stem: Some("a"),
3111         extension: None
3112         );
3113
3114         t!(".",
3115         iter: ["."],
3116         has_root: false,
3117         is_absolute: false,
3118         parent: Some(""),
3119         file_name: None,
3120         file_stem: None,
3121         extension: None
3122         );
3123
3124         t!("./",
3125         iter: ["."],
3126         has_root: false,
3127         is_absolute: false,
3128         parent: Some(""),
3129         file_name: None,
3130         file_stem: None,
3131         extension: None
3132         );
3133
3134         t!("a/b",
3135         iter: ["a", "b"],
3136         has_root: false,
3137         is_absolute: false,
3138         parent: Some("a"),
3139         file_name: Some("b"),
3140         file_stem: Some("b"),
3141         extension: None
3142         );
3143
3144         t!("a//b",
3145         iter: ["a", "b"],
3146         has_root: false,
3147         is_absolute: false,
3148         parent: Some("a"),
3149         file_name: Some("b"),
3150         file_stem: Some("b"),
3151         extension: None
3152         );
3153
3154         t!("a/./b",
3155         iter: ["a", "b"],
3156         has_root: false,
3157         is_absolute: false,
3158         parent: Some("a"),
3159         file_name: Some("b"),
3160         file_stem: Some("b"),
3161         extension: None
3162         );
3163
3164         t!("a/b/c",
3165         iter: ["a", "b", "c"],
3166         has_root: false,
3167         is_absolute: false,
3168         parent: Some("a/b"),
3169         file_name: Some("c"),
3170         file_stem: Some("c"),
3171         extension: None
3172         );
3173
3174         t!(".foo",
3175         iter: [".foo"],
3176         has_root: false,
3177         is_absolute: false,
3178         parent: Some(""),
3179         file_name: Some(".foo"),
3180         file_stem: Some(".foo"),
3181         extension: None
3182         );
3183     }
3184
3185     #[test]
3186     #[cfg(windows)]
3187     pub fn test_decompositions_windows() {
3188         t!("",
3189         iter: [],
3190         has_root: false,
3191         is_absolute: false,
3192         parent: None,
3193         file_name: None,
3194         file_stem: None,
3195         extension: None
3196         );
3197
3198         t!("foo",
3199         iter: ["foo"],
3200         has_root: false,
3201         is_absolute: false,
3202         parent: Some(""),
3203         file_name: Some("foo"),
3204         file_stem: Some("foo"),
3205         extension: None
3206         );
3207
3208         t!("/",
3209         iter: ["\\"],
3210         has_root: true,
3211         is_absolute: false,
3212         parent: None,
3213         file_name: None,
3214         file_stem: None,
3215         extension: None
3216         );
3217
3218         t!("\\",
3219         iter: ["\\"],
3220         has_root: true,
3221         is_absolute: false,
3222         parent: None,
3223         file_name: None,
3224         file_stem: None,
3225         extension: None
3226         );
3227
3228         t!("c:",
3229         iter: ["c:"],
3230         has_root: false,
3231         is_absolute: false,
3232         parent: None,
3233         file_name: None,
3234         file_stem: None,
3235         extension: None
3236         );
3237
3238         t!("c:\\",
3239         iter: ["c:", "\\"],
3240         has_root: true,
3241         is_absolute: true,
3242         parent: None,
3243         file_name: None,
3244         file_stem: None,
3245         extension: None
3246         );
3247
3248         t!("c:/",
3249         iter: ["c:", "\\"],
3250         has_root: true,
3251         is_absolute: true,
3252         parent: None,
3253         file_name: None,
3254         file_stem: None,
3255         extension: None
3256         );
3257
3258         t!("/foo",
3259         iter: ["\\", "foo"],
3260         has_root: true,
3261         is_absolute: false,
3262         parent: Some("/"),
3263         file_name: Some("foo"),
3264         file_stem: Some("foo"),
3265         extension: None
3266         );
3267
3268         t!("foo/",
3269         iter: ["foo"],
3270         has_root: false,
3271         is_absolute: false,
3272         parent: Some(""),
3273         file_name: Some("foo"),
3274         file_stem: Some("foo"),
3275         extension: None
3276         );
3277
3278         t!("/foo/",
3279         iter: ["\\", "foo"],
3280         has_root: true,
3281         is_absolute: false,
3282         parent: Some("/"),
3283         file_name: Some("foo"),
3284         file_stem: Some("foo"),
3285         extension: None
3286         );
3287
3288         t!("foo/bar",
3289         iter: ["foo", "bar"],
3290         has_root: false,
3291         is_absolute: false,
3292         parent: Some("foo"),
3293         file_name: Some("bar"),
3294         file_stem: Some("bar"),
3295         extension: None
3296         );
3297
3298         t!("/foo/bar",
3299         iter: ["\\", "foo", "bar"],
3300         has_root: true,
3301         is_absolute: false,
3302         parent: Some("/foo"),
3303         file_name: Some("bar"),
3304         file_stem: Some("bar"),
3305         extension: None
3306         );
3307
3308         t!("///foo///",
3309         iter: ["\\", "foo"],
3310         has_root: true,
3311         is_absolute: false,
3312         parent: Some("/"),
3313         file_name: Some("foo"),
3314         file_stem: Some("foo"),
3315         extension: None
3316         );
3317
3318         t!("///foo///bar",
3319         iter: ["\\", "foo", "bar"],
3320         has_root: true,
3321         is_absolute: false,
3322         parent: Some("///foo"),
3323         file_name: Some("bar"),
3324         file_stem: Some("bar"),
3325         extension: None
3326         );
3327
3328         t!("./.",
3329         iter: ["."],
3330         has_root: false,
3331         is_absolute: false,
3332         parent: Some(""),
3333         file_name: None,
3334         file_stem: None,
3335         extension: None
3336         );
3337
3338         t!("/..",
3339         iter: ["\\", ".."],
3340         has_root: true,
3341         is_absolute: false,
3342         parent: Some("/"),
3343         file_name: None,
3344         file_stem: None,
3345         extension: None
3346         );
3347
3348         t!("../",
3349         iter: [".."],
3350         has_root: false,
3351         is_absolute: false,
3352         parent: Some(""),
3353         file_name: None,
3354         file_stem: None,
3355         extension: None
3356         );
3357
3358         t!("foo/.",
3359         iter: ["foo"],
3360         has_root: false,
3361         is_absolute: false,
3362         parent: Some(""),
3363         file_name: Some("foo"),
3364         file_stem: Some("foo"),
3365         extension: None
3366         );
3367
3368         t!("foo/..",
3369         iter: ["foo", ".."],
3370         has_root: false,
3371         is_absolute: false,
3372         parent: Some("foo"),
3373         file_name: None,
3374         file_stem: None,
3375         extension: None
3376         );
3377
3378         t!("foo/./",
3379         iter: ["foo"],
3380         has_root: false,
3381         is_absolute: false,
3382         parent: Some(""),
3383         file_name: Some("foo"),
3384         file_stem: Some("foo"),
3385         extension: None
3386         );
3387
3388         t!("foo/./bar",
3389         iter: ["foo", "bar"],
3390         has_root: false,
3391         is_absolute: false,
3392         parent: Some("foo"),
3393         file_name: Some("bar"),
3394         file_stem: Some("bar"),
3395         extension: None
3396         );
3397
3398         t!("foo/../",
3399         iter: ["foo", ".."],
3400         has_root: false,
3401         is_absolute: false,
3402         parent: Some("foo"),
3403         file_name: None,
3404         file_stem: None,
3405         extension: None
3406         );
3407
3408         t!("foo/../bar",
3409         iter: ["foo", "..", "bar"],
3410         has_root: false,
3411         is_absolute: false,
3412         parent: Some("foo/.."),
3413         file_name: Some("bar"),
3414         file_stem: Some("bar"),
3415         extension: None
3416         );
3417
3418         t!("./a",
3419         iter: [".", "a"],
3420         has_root: false,
3421         is_absolute: false,
3422         parent: Some("."),
3423         file_name: Some("a"),
3424         file_stem: Some("a"),
3425         extension: None
3426         );
3427
3428         t!(".",
3429         iter: ["."],
3430         has_root: false,
3431         is_absolute: false,
3432         parent: Some(""),
3433         file_name: None,
3434         file_stem: None,
3435         extension: None
3436         );
3437
3438         t!("./",
3439         iter: ["."],
3440         has_root: false,
3441         is_absolute: false,
3442         parent: Some(""),
3443         file_name: None,
3444         file_stem: None,
3445         extension: None
3446         );
3447
3448         t!("a/b",
3449         iter: ["a", "b"],
3450         has_root: false,
3451         is_absolute: false,
3452         parent: Some("a"),
3453         file_name: Some("b"),
3454         file_stem: Some("b"),
3455         extension: None
3456         );
3457
3458         t!("a//b",
3459         iter: ["a", "b"],
3460         has_root: false,
3461         is_absolute: false,
3462         parent: Some("a"),
3463         file_name: Some("b"),
3464         file_stem: Some("b"),
3465         extension: None
3466         );
3467
3468         t!("a/./b",
3469         iter: ["a", "b"],
3470         has_root: false,
3471         is_absolute: false,
3472         parent: Some("a"),
3473         file_name: Some("b"),
3474         file_stem: Some("b"),
3475         extension: None
3476         );
3477
3478         t!("a/b/c",
3479            iter: ["a", "b", "c"],
3480            has_root: false,
3481            is_absolute: false,
3482            parent: Some("a/b"),
3483            file_name: Some("c"),
3484            file_stem: Some("c"),
3485            extension: None);
3486
3487         t!("a\\b\\c",
3488         iter: ["a", "b", "c"],
3489         has_root: false,
3490         is_absolute: false,
3491         parent: Some("a\\b"),
3492         file_name: Some("c"),
3493         file_stem: Some("c"),
3494         extension: None
3495         );
3496
3497         t!("\\a",
3498         iter: ["\\", "a"],
3499         has_root: true,
3500         is_absolute: false,
3501         parent: Some("\\"),
3502         file_name: Some("a"),
3503         file_stem: Some("a"),
3504         extension: None
3505         );
3506
3507         t!("c:\\foo.txt",
3508         iter: ["c:", "\\", "foo.txt"],
3509         has_root: true,
3510         is_absolute: true,
3511         parent: Some("c:\\"),
3512         file_name: Some("foo.txt"),
3513         file_stem: Some("foo"),
3514         extension: Some("txt")
3515         );
3516
3517         t!("\\\\server\\share\\foo.txt",
3518         iter: ["\\\\server\\share", "\\", "foo.txt"],
3519         has_root: true,
3520         is_absolute: true,
3521         parent: Some("\\\\server\\share\\"),
3522         file_name: Some("foo.txt"),
3523         file_stem: Some("foo"),
3524         extension: Some("txt")
3525         );
3526
3527         t!("\\\\server\\share",
3528         iter: ["\\\\server\\share", "\\"],
3529         has_root: true,
3530         is_absolute: true,
3531         parent: None,
3532         file_name: None,
3533         file_stem: None,
3534         extension: None
3535         );
3536
3537         t!("\\\\server",
3538         iter: ["\\", "server"],
3539         has_root: true,
3540         is_absolute: false,
3541         parent: Some("\\"),
3542         file_name: Some("server"),
3543         file_stem: Some("server"),
3544         extension: None
3545         );
3546
3547         t!("\\\\?\\bar\\foo.txt",
3548         iter: ["\\\\?\\bar", "\\", "foo.txt"],
3549         has_root: true,
3550         is_absolute: true,
3551         parent: Some("\\\\?\\bar\\"),
3552         file_name: Some("foo.txt"),
3553         file_stem: Some("foo"),
3554         extension: Some("txt")
3555         );
3556
3557         t!("\\\\?\\bar",
3558         iter: ["\\\\?\\bar"],
3559         has_root: true,
3560         is_absolute: true,
3561         parent: None,
3562         file_name: None,
3563         file_stem: None,
3564         extension: None
3565         );
3566
3567         t!("\\\\?\\",
3568         iter: ["\\\\?\\"],
3569         has_root: true,
3570         is_absolute: true,
3571         parent: None,
3572         file_name: None,
3573         file_stem: None,
3574         extension: None
3575         );
3576
3577         t!("\\\\?\\UNC\\server\\share\\foo.txt",
3578         iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3579         has_root: true,
3580         is_absolute: true,
3581         parent: Some("\\\\?\\UNC\\server\\share\\"),
3582         file_name: Some("foo.txt"),
3583         file_stem: Some("foo"),
3584         extension: Some("txt")
3585         );
3586
3587         t!("\\\\?\\UNC\\server",
3588         iter: ["\\\\?\\UNC\\server"],
3589         has_root: true,
3590         is_absolute: true,
3591         parent: None,
3592         file_name: None,
3593         file_stem: None,
3594         extension: None
3595         );
3596
3597         t!("\\\\?\\UNC\\",
3598         iter: ["\\\\?\\UNC\\"],
3599         has_root: true,
3600         is_absolute: true,
3601         parent: None,
3602         file_name: None,
3603         file_stem: None,
3604         extension: None
3605         );
3606
3607         t!("\\\\?\\C:\\foo.txt",
3608         iter: ["\\\\?\\C:", "\\", "foo.txt"],
3609         has_root: true,
3610         is_absolute: true,
3611         parent: Some("\\\\?\\C:\\"),
3612         file_name: Some("foo.txt"),
3613         file_stem: Some("foo"),
3614         extension: Some("txt")
3615         );
3616
3617         t!("\\\\?\\C:\\",
3618         iter: ["\\\\?\\C:", "\\"],
3619         has_root: true,
3620         is_absolute: true,
3621         parent: None,
3622         file_name: None,
3623         file_stem: None,
3624         extension: None
3625         );
3626
3627         t!("\\\\?\\C:",
3628         iter: ["\\\\?\\C:"],
3629         has_root: true,
3630         is_absolute: true,
3631         parent: None,
3632         file_name: None,
3633         file_stem: None,
3634         extension: None
3635         );
3636
3637         t!("\\\\?\\foo/bar",
3638         iter: ["\\\\?\\foo/bar"],
3639         has_root: true,
3640         is_absolute: true,
3641         parent: None,
3642         file_name: None,
3643         file_stem: None,
3644         extension: None
3645         );
3646
3647         t!("\\\\?\\C:/foo",
3648         iter: ["\\\\?\\C:/foo"],
3649         has_root: true,
3650         is_absolute: true,
3651         parent: None,
3652         file_name: None,
3653         file_stem: None,
3654         extension: None
3655         );
3656
3657         t!("\\\\.\\foo\\bar",
3658         iter: ["\\\\.\\foo", "\\", "bar"],
3659         has_root: true,
3660         is_absolute: true,
3661         parent: Some("\\\\.\\foo\\"),
3662         file_name: Some("bar"),
3663         file_stem: Some("bar"),
3664         extension: None
3665         );
3666
3667         t!("\\\\.\\foo",
3668         iter: ["\\\\.\\foo", "\\"],
3669         has_root: true,
3670         is_absolute: true,
3671         parent: None,
3672         file_name: None,
3673         file_stem: None,
3674         extension: None
3675         );
3676
3677         t!("\\\\.\\foo/bar",
3678         iter: ["\\\\.\\foo/bar", "\\"],
3679         has_root: true,
3680         is_absolute: true,
3681         parent: None,
3682         file_name: None,
3683         file_stem: None,
3684         extension: None
3685         );
3686
3687         t!("\\\\.\\foo\\bar/baz",
3688         iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3689         has_root: true,
3690         is_absolute: true,
3691         parent: Some("\\\\.\\foo\\bar"),
3692         file_name: Some("baz"),
3693         file_stem: Some("baz"),
3694         extension: None
3695         );
3696
3697         t!("\\\\.\\",
3698         iter: ["\\\\.\\", "\\"],
3699         has_root: true,
3700         is_absolute: true,
3701         parent: None,
3702         file_name: None,
3703         file_stem: None,
3704         extension: None
3705         );
3706
3707         t!("\\\\?\\a\\b\\",
3708         iter: ["\\\\?\\a", "\\", "b"],
3709         has_root: true,
3710         is_absolute: true,
3711         parent: Some("\\\\?\\a\\"),
3712         file_name: Some("b"),
3713         file_stem: Some("b"),
3714         extension: None
3715         );
3716     }
3717
3718     #[test]
3719     pub fn test_stem_ext() {
3720         t!("foo",
3721         file_stem: Some("foo"),
3722         extension: None
3723         );
3724
3725         t!("foo.",
3726         file_stem: Some("foo"),
3727         extension: Some("")
3728         );
3729
3730         t!(".foo",
3731         file_stem: Some(".foo"),
3732         extension: None
3733         );
3734
3735         t!("foo.txt",
3736         file_stem: Some("foo"),
3737         extension: Some("txt")
3738         );
3739
3740         t!("foo.bar.txt",
3741         file_stem: Some("foo.bar"),
3742         extension: Some("txt")
3743         );
3744
3745         t!("foo.bar.",
3746         file_stem: Some("foo.bar"),
3747         extension: Some("")
3748         );
3749
3750         t!(".", file_stem: None, extension: None);
3751
3752         t!("..", file_stem: None, extension: None);
3753
3754         t!("", file_stem: None, extension: None);
3755     }
3756
3757     #[test]
3758     pub fn test_push() {
3759         macro_rules! tp(
3760             ($path:expr, $push:expr, $expected:expr) => ( {
3761                 let mut actual = PathBuf::from($path);
3762                 actual.push($push);
3763                 assert!(actual.to_str() == Some($expected),
3764                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3765                         $push, $path, $expected, actual.to_str().unwrap());
3766             });
3767         );
3768
3769         if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3770             tp!("", "foo", "foo");
3771             tp!("foo", "bar", "foo/bar");
3772             tp!("foo/", "bar", "foo/bar");
3773             tp!("foo//", "bar", "foo//bar");
3774             tp!("foo/.", "bar", "foo/./bar");
3775             tp!("foo./.", "bar", "foo././bar");
3776             tp!("foo", "", "foo/");
3777             tp!("foo", ".", "foo/.");
3778             tp!("foo", "..", "foo/..");
3779             tp!("foo", "/", "/");
3780             tp!("/foo/bar", "/", "/");
3781             tp!("/foo/bar", "/baz", "/baz");
3782             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3783         } else {
3784             tp!("", "foo", "foo");
3785             tp!("foo", "bar", r"foo\bar");
3786             tp!("foo/", "bar", r"foo/bar");
3787             tp!(r"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!("foo./.", "bar", r"foo./.\bar");
3792             tp!(r"foo\.", "bar", r"foo\.\bar");
3793             tp!(r"foo.\.", "bar", r"foo.\.\bar");
3794             tp!("foo", "", "foo\\");
3795             tp!("foo", ".", r"foo\.");
3796             tp!("foo", "..", r"foo\..");
3797             tp!("foo", "/", "/");
3798             tp!("foo", r"\", r"\");
3799             tp!("/foo/bar", "/", "/");
3800             tp!(r"\foo\bar", r"\", r"\");
3801             tp!("/foo/bar", "/baz", "/baz");
3802             tp!("/foo/bar", r"\baz", r"\baz");
3803             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3804             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3805
3806             tp!("c:\\", "windows", "c:\\windows");
3807             tp!("c:", "windows", "c:windows");
3808
3809             tp!("a\\b\\c", "d", "a\\b\\c\\d");
3810             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3811             tp!("a\\b", "c\\d", "a\\b\\c\\d");
3812             tp!("a\\b", "\\c\\d", "\\c\\d");
3813             tp!("a\\b", ".", "a\\b\\.");
3814             tp!("a\\b", "..\\c", "a\\b\\..\\c");
3815             tp!("a\\b", "C:a.txt", "C:a.txt");
3816             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3817             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3818             tp!("C:\\a\\b\\c", "C:d", "C:d");
3819             tp!("C:a\\b\\c", "C:d", "C:d");
3820             tp!("C:", r"a\b\c", r"C:a\b\c");
3821             tp!("C:", r"..\a", r"C:..\a");
3822             tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
3823             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3824             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3825             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3826             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3827             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3828             tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
3829             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3830             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3831
3832             // Note: modified from old path API
3833             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3834
3835             tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
3836             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3837             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3838             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3839             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3840
3841             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3842         }
3843     }
3844
3845     #[test]
3846     pub fn test_pop() {
3847         macro_rules! tp(
3848             ($path:expr, $expected:expr, $output:expr) => ( {
3849                 let mut actual = PathBuf::from($path);
3850                 let output = actual.pop();
3851                 assert!(actual.to_str() == Some($expected) && output == $output,
3852                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3853                         $path, $expected, $output,
3854                         actual.to_str().unwrap(), output);
3855             });
3856         );
3857
3858         tp!("", "", false);
3859         tp!("/", "/", false);
3860         tp!("foo", "", true);
3861         tp!(".", "", true);
3862         tp!("/foo", "/", true);
3863         tp!("/foo/bar", "/foo", true);
3864         tp!("foo/bar", "foo", true);
3865         tp!("foo/.", "", true);
3866         tp!("foo//bar", "foo", true);
3867
3868         if cfg!(windows) {
3869             tp!("a\\b\\c", "a\\b", true);
3870             tp!("\\a", "\\", true);
3871             tp!("\\", "\\", false);
3872
3873             tp!("C:\\a\\b", "C:\\a", true);
3874             tp!("C:\\a", "C:\\", true);
3875             tp!("C:\\", "C:\\", false);
3876             tp!("C:a\\b", "C:a", true);
3877             tp!("C:a", "C:", true);
3878             tp!("C:", "C:", false);
3879             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3880             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3881             tp!("\\\\server\\share", "\\\\server\\share", false);
3882             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3883             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3884             tp!("\\\\?\\a", "\\\\?\\a", false);
3885             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3886             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3887             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3888             tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
3889             tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
3890             tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
3891             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3892             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3893             tp!("\\\\.\\a", "\\\\.\\a", false);
3894
3895             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3896         }
3897     }
3898
3899     #[test]
3900     pub fn test_set_file_name() {
3901         macro_rules! tfn(
3902                 ($path:expr, $file:expr, $expected:expr) => ( {
3903                 let mut p = PathBuf::from($path);
3904                 p.set_file_name($file);
3905                 assert!(p.to_str() == Some($expected),
3906                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3907                         $path, $file, $expected,
3908                         p.to_str().unwrap());
3909             });
3910         );
3911
3912         tfn!("foo", "foo", "foo");
3913         tfn!("foo", "bar", "bar");
3914         tfn!("foo", "", "");
3915         tfn!("", "foo", "foo");
3916         if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3917             tfn!(".", "foo", "./foo");
3918             tfn!("foo/", "bar", "bar");
3919             tfn!("foo/.", "bar", "bar");
3920             tfn!("..", "foo", "../foo");
3921             tfn!("foo/..", "bar", "foo/../bar");
3922             tfn!("/", "foo", "/foo");
3923         } else {
3924             tfn!(".", "foo", r".\foo");
3925             tfn!(r"foo\", "bar", r"bar");
3926             tfn!(r"foo\.", "bar", r"bar");
3927             tfn!("..", "foo", r"..\foo");
3928             tfn!(r"foo\..", "bar", r"foo\..\bar");
3929             tfn!(r"\", "foo", r"\foo");
3930         }
3931     }
3932
3933     #[test]
3934     pub fn test_set_extension() {
3935         macro_rules! tfe(
3936                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3937                 let mut p = PathBuf::from($path);
3938                 let output = p.set_extension($ext);
3939                 assert!(p.to_str() == Some($expected) && output == $output,
3940                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3941                         $path, $ext, $expected, $output,
3942                         p.to_str().unwrap(), output);
3943             });
3944         );
3945
3946         tfe!("foo", "txt", "foo.txt", true);
3947         tfe!("foo.bar", "txt", "foo.txt", true);
3948         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3949         tfe!(".test", "txt", ".test.txt", true);
3950         tfe!("foo.txt", "", "foo", true);
3951         tfe!("foo", "", "foo", true);
3952         tfe!("", "foo", "", false);
3953         tfe!(".", "foo", ".", false);
3954         tfe!("foo/", "bar", "foo.bar", true);
3955         tfe!("foo/.", "bar", "foo.bar", true);
3956         tfe!("..", "foo", "..", false);
3957         tfe!("foo/..", "bar", "foo/..", false);
3958         tfe!("/", "foo", "/", false);
3959     }
3960
3961     #[test]
3962     fn test_eq_receivers() {
3963         use crate::borrow::Cow;
3964
3965         let borrowed: &Path = Path::new("foo/bar");
3966         let mut owned: PathBuf = PathBuf::new();
3967         owned.push("foo");
3968         owned.push("bar");
3969         let borrowed_cow: Cow<'_, Path> = borrowed.into();
3970         let owned_cow: Cow<'_, Path> = owned.clone().into();
3971
3972         macro_rules! t {
3973             ($($current:expr),+) => {
3974                 $(
3975                     assert_eq!($current, borrowed);
3976                     assert_eq!($current, owned);
3977                     assert_eq!($current, borrowed_cow);
3978                     assert_eq!($current, owned_cow);
3979                 )+
3980             }
3981         }
3982
3983         t!(borrowed, owned, borrowed_cow, owned_cow);
3984     }
3985
3986     #[test]
3987     pub fn test_compare() {
3988         use crate::collections::hash_map::DefaultHasher;
3989         use crate::hash::{Hash, Hasher};
3990
3991         fn hash<T: Hash>(t: T) -> u64 {
3992             let mut s = DefaultHasher::new();
3993             t.hash(&mut s);
3994             s.finish()
3995         }
3996
3997         macro_rules! tc(
3998             ($path1:expr, $path2:expr, eq: $eq:expr,
3999              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4000              relative_from: $relative_from:expr) => ({
4001                  let path1 = Path::new($path1);
4002                  let path2 = Path::new($path2);
4003
4004                  let eq = path1 == path2;
4005                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4006                          $path1, $path2, $eq, eq);
4007                  assert!($eq == (hash(path1) == hash(path2)),
4008                          "{:?} == {:?}, expected {:?}, got {} and {}",
4009                          $path1, $path2, $eq, hash(path1), hash(path2));
4010
4011                  let starts_with = path1.starts_with(path2);
4012                  assert!(starts_with == $starts_with,
4013                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4014                          $starts_with, starts_with);
4015
4016                  let ends_with = path1.ends_with(path2);
4017                  assert!(ends_with == $ends_with,
4018                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4019                          $ends_with, ends_with);
4020
4021                  let relative_from = path1.strip_prefix(path2)
4022                                           .map(|p| p.to_str().unwrap())
4023                                           .ok();
4024                  let exp: Option<&str> = $relative_from;
4025                  assert!(relative_from == exp,
4026                          "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4027                          $path1, $path2, exp, relative_from);
4028             });
4029         );
4030
4031         tc!("", "",
4032         eq: true,
4033         starts_with: true,
4034         ends_with: true,
4035         relative_from: Some("")
4036         );
4037
4038         tc!("foo", "",
4039         eq: false,
4040         starts_with: true,
4041         ends_with: true,
4042         relative_from: Some("foo")
4043         );
4044
4045         tc!("", "foo",
4046         eq: false,
4047         starts_with: false,
4048         ends_with: false,
4049         relative_from: None
4050         );
4051
4052         tc!("foo", "foo",
4053         eq: true,
4054         starts_with: true,
4055         ends_with: true,
4056         relative_from: Some("")
4057         );
4058
4059         tc!("foo/", "foo",
4060         eq: true,
4061         starts_with: true,
4062         ends_with: true,
4063         relative_from: Some("")
4064         );
4065
4066         tc!("foo/bar", "foo",
4067         eq: false,
4068         starts_with: true,
4069         ends_with: false,
4070         relative_from: Some("bar")
4071         );
4072
4073         tc!("foo/bar/baz", "foo/bar",
4074         eq: false,
4075         starts_with: true,
4076         ends_with: false,
4077         relative_from: Some("baz")
4078         );
4079
4080         tc!("foo/bar", "foo/bar/baz",
4081         eq: false,
4082         starts_with: false,
4083         ends_with: false,
4084         relative_from: None
4085         );
4086
4087         tc!("./foo/bar/", ".",
4088         eq: false,
4089         starts_with: true,
4090         ends_with: false,
4091         relative_from: Some("foo/bar")
4092         );
4093
4094         if cfg!(windows) {
4095             tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4096             r"c:\src\rust\cargo-test\test",
4097             eq: false,
4098             starts_with: true,
4099             ends_with: false,
4100             relative_from: Some("Cargo.toml")
4101             );
4102
4103             tc!(r"c:\foo", r"C:\foo",
4104             eq: true,
4105             starts_with: true,
4106             ends_with: true,
4107             relative_from: Some("")
4108             );
4109         }
4110     }
4111
4112     #[test]
4113     fn test_components_debug() {
4114         let path = Path::new("/tmp");
4115
4116         let mut components = path.components();
4117
4118         let expected = "Components([RootDir, Normal(\"tmp\")])";
4119         let actual = format!("{:?}", components);
4120         assert_eq!(expected, actual);
4121
4122         let _ = components.next().unwrap();
4123         let expected = "Components([Normal(\"tmp\")])";
4124         let actual = format!("{:?}", components);
4125         assert_eq!(expected, actual);
4126
4127         let _ = components.next().unwrap();
4128         let expected = "Components([])";
4129         let actual = format!("{:?}", components);
4130         assert_eq!(expected, actual);
4131     }
4132
4133     #[cfg(unix)]
4134     #[test]
4135     fn test_iter_debug() {
4136         let path = Path::new("/tmp");
4137
4138         let mut iter = path.iter();
4139
4140         let expected = "Iter([\"/\", \"tmp\"])";
4141         let actual = format!("{:?}", iter);
4142         assert_eq!(expected, actual);
4143
4144         let _ = iter.next().unwrap();
4145         let expected = "Iter([\"tmp\"])";
4146         let actual = format!("{:?}", iter);
4147         assert_eq!(expected, actual);
4148
4149         let _ = iter.next().unwrap();
4150         let expected = "Iter([])";
4151         let actual = format!("{:?}", iter);
4152         assert_eq!(expected, actual);
4153     }
4154
4155     #[test]
4156     fn into_boxed() {
4157         let orig: &str = "some/sort/of/path";
4158         let path = Path::new(orig);
4159         let boxed: Box<Path> = Box::from(path);
4160         let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4161         assert_eq!(path, &*boxed);
4162         assert_eq!(&*boxed, &*path_buf);
4163         assert_eq!(&*path_buf, path);
4164     }
4165
4166     #[test]
4167     fn test_clone_into() {
4168         let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4169         let path = Path::new("short");
4170         path.clone_into(&mut path_buf);
4171         assert_eq!(path, path_buf);
4172         assert!(path_buf.into_os_string().capacity() >= 15);
4173     }
4174
4175     #[test]
4176     fn display_format_flags() {
4177         assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4178         assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4179     }
4180
4181     #[test]
4182     fn into_rc() {
4183         let orig = "hello/world";
4184         let path = Path::new(orig);
4185         let rc: Rc<Path> = Rc::from(path);
4186         let arc: Arc<Path> = Arc::from(path);
4187
4188         assert_eq!(&*rc, path);
4189         assert_eq!(&*arc, path);
4190
4191         let rc2: Rc<Path> = Rc::from(path.to_owned());
4192         let arc2: Arc<Path> = Arc::from(path.to_owned());
4193
4194         assert_eq!(&*rc2, path);
4195         assert_eq!(&*arc2, path);
4196     }
4197 }