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