]> git.lizzy.rs Git - rust.git/blob - src/libstd/path.rs
Auto merge of #60763 - matklad:tt-parser, r=petrochenkov
[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.split(|b| *b == b'/').next().unwrap_or(b"").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     #[inline]
893     fn last(mut self) -> Option<&'a OsStr> {
894         self.next_back()
895     }
896 }
897
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<'a> DoubleEndedIterator for Iter<'a> {
900     fn next_back(&mut self) -> Option<&'a OsStr> {
901         self.inner.next_back().map(Component::as_os_str)
902     }
903 }
904
905 #[stable(feature = "fused", since = "1.26.0")]
906 impl FusedIterator for Iter<'_> {}
907
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<'a> Iterator for Components<'a> {
910     type Item = Component<'a>;
911
912     fn next(&mut self) -> Option<Component<'a>> {
913         while !self.finished() {
914             match self.front {
915                 State::Prefix if self.prefix_len() > 0 => {
916                     self.front = State::StartDir;
917                     debug_assert!(self.prefix_len() <= self.path.len());
918                     let raw = &self.path[..self.prefix_len()];
919                     self.path = &self.path[self.prefix_len()..];
920                     return Some(Component::Prefix(PrefixComponent {
921                         raw: unsafe { u8_slice_as_os_str(raw) },
922                         parsed: self.prefix.unwrap(),
923                     }));
924                 }
925                 State::Prefix => {
926                     self.front = State::StartDir;
927                 }
928                 State::StartDir => {
929                     self.front = State::Body;
930                     if self.has_physical_root {
931                         debug_assert!(!self.path.is_empty());
932                         self.path = &self.path[1..];
933                         return Some(Component::RootDir);
934                     } else if let Some(p) = self.prefix {
935                         if p.has_implicit_root() && !p.is_verbatim() {
936                             return Some(Component::RootDir);
937                         }
938                     } else if self.include_cur_dir() {
939                         debug_assert!(!self.path.is_empty());
940                         self.path = &self.path[1..];
941                         return Some(Component::CurDir);
942                     }
943                 }
944                 State::Body if !self.path.is_empty() => {
945                     let (size, comp) = self.parse_next_component();
946                     self.path = &self.path[size..];
947                     if comp.is_some() {
948                         return comp;
949                     }
950                 }
951                 State::Body => {
952                     self.front = State::Done;
953                 }
954                 State::Done => unreachable!(),
955             }
956         }
957         None
958     }
959
960     #[inline]
961     fn last(mut self) -> Option<Self::Item> {
962         self.next_back()
963     }
964 }
965
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<'a> DoubleEndedIterator for Components<'a> {
968     fn next_back(&mut self) -> Option<Component<'a>> {
969         while !self.finished() {
970             match self.back {
971                 State::Body if self.path.len() > self.len_before_body() => {
972                     let (size, comp) = self.parse_next_component_back();
973                     self.path = &self.path[..self.path.len() - size];
974                     if comp.is_some() {
975                         return comp;
976                     }
977                 }
978                 State::Body => {
979                     self.back = State::StartDir;
980                 }
981                 State::StartDir => {
982                     self.back = State::Prefix;
983                     if self.has_physical_root {
984                         self.path = &self.path[..self.path.len() - 1];
985                         return Some(Component::RootDir);
986                     } else if let Some(p) = self.prefix {
987                         if p.has_implicit_root() && !p.is_verbatim() {
988                             return Some(Component::RootDir);
989                         }
990                     } else if self.include_cur_dir() {
991                         self.path = &self.path[..self.path.len() - 1];
992                         return Some(Component::CurDir);
993                     }
994                 }
995                 State::Prefix if self.prefix_len() > 0 => {
996                     self.back = State::Done;
997                     return Some(Component::Prefix(PrefixComponent {
998                         raw: unsafe { u8_slice_as_os_str(self.path) },
999                         parsed: self.prefix.unwrap(),
1000                     }));
1001                 }
1002                 State::Prefix => {
1003                     self.back = State::Done;
1004                     return None;
1005                 }
1006                 State::Done => unreachable!(),
1007             }
1008         }
1009         None
1010     }
1011 }
1012
1013 #[stable(feature = "fused", since = "1.26.0")]
1014 impl FusedIterator for Components<'_> {}
1015
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<'a> cmp::PartialEq for Components<'a> {
1018     fn eq(&self, other: &Components<'a>) -> bool {
1019         Iterator::eq(self.clone(), other.clone())
1020     }
1021 }
1022
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 impl cmp::Eq for Components<'_> {}
1025
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<'a> cmp::PartialOrd for Components<'a> {
1028     fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1029         Iterator::partial_cmp(self.clone(), other.clone())
1030     }
1031 }
1032
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl cmp::Ord for Components<'_> {
1035     fn cmp(&self, other: &Self) -> cmp::Ordering {
1036         Iterator::cmp(self.clone(), other.clone())
1037     }
1038 }
1039
1040 /// An iterator over [`Path`] and its ancestors.
1041 ///
1042 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1043 /// See its documentation for more.
1044 ///
1045 /// # Examples
1046 ///
1047 /// ```
1048 /// use std::path::Path;
1049 ///
1050 /// let path = Path::new("/foo/bar");
1051 ///
1052 /// for ancestor in path.ancestors() {
1053 ///     println!("{}", ancestor.display());
1054 /// }
1055 /// ```
1056 ///
1057 /// [`ancestors`]: struct.Path.html#method.ancestors
1058 /// [`Path`]: struct.Path.html
1059 #[derive(Copy, Clone, Debug)]
1060 #[stable(feature = "path_ancestors", since = "1.28.0")]
1061 pub struct Ancestors<'a> {
1062     next: Option<&'a Path>,
1063 }
1064
1065 #[stable(feature = "path_ancestors", since = "1.28.0")]
1066 impl<'a> Iterator for Ancestors<'a> {
1067     type Item = &'a Path;
1068
1069     fn next(&mut self) -> Option<Self::Item> {
1070         let next = self.next;
1071         self.next = next.and_then(Path::parent);
1072         next
1073     }
1074 }
1075
1076 #[stable(feature = "path_ancestors", since = "1.28.0")]
1077 impl FusedIterator for Ancestors<'_> {}
1078
1079 ////////////////////////////////////////////////////////////////////////////////
1080 // Basic types and traits
1081 ////////////////////////////////////////////////////////////////////////////////
1082
1083 /// An owned, mutable path (akin to [`String`]).
1084 ///
1085 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1086 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1087 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1088 ///
1089 /// [`String`]: ../string/struct.String.html
1090 /// [`Path`]: struct.Path.html
1091 /// [`push`]: struct.PathBuf.html#method.push
1092 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1093 /// [`Deref`]: ../ops/trait.Deref.html
1094 ///
1095 /// More details about the overall approach can be found in
1096 /// the [module documentation](index.html).
1097 ///
1098 /// # Examples
1099 ///
1100 /// You can use [`push`] to build up a `PathBuf` from
1101 /// components:
1102 ///
1103 /// ```
1104 /// use std::path::PathBuf;
1105 ///
1106 /// let mut path = PathBuf::new();
1107 ///
1108 /// path.push(r"C:\");
1109 /// path.push("windows");
1110 /// path.push("system32");
1111 ///
1112 /// path.set_extension("dll");
1113 /// ```
1114 ///
1115 /// However, [`push`] is best used for dynamic situations. This is a better way
1116 /// to do this when you know all of the components ahead of time:
1117 ///
1118 /// ```
1119 /// use std::path::PathBuf;
1120 ///
1121 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1122 /// ```
1123 ///
1124 /// We can still do better than this! Since these are all strings, we can use
1125 /// `From::from`:
1126 ///
1127 /// ```
1128 /// use std::path::PathBuf;
1129 ///
1130 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1131 /// ```
1132 ///
1133 /// Which method works best depends on what kind of situation you're in.
1134 #[derive(Clone)]
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 pub struct PathBuf {
1137     inner: OsString,
1138 }
1139
1140 impl PathBuf {
1141     fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1142         unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1143     }
1144
1145     /// Allocates an empty `PathBuf`.
1146     ///
1147     /// # Examples
1148     ///
1149     /// ```
1150     /// use std::path::PathBuf;
1151     ///
1152     /// let path = PathBuf::new();
1153     /// ```
1154     #[stable(feature = "rust1", since = "1.0.0")]
1155     pub fn new() -> PathBuf {
1156         PathBuf { inner: OsString::new() }
1157     }
1158
1159     /// Creates a new `PathBuf` with a given capacity used to create the
1160     /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1161     ///
1162     /// # Examples
1163     ///
1164     /// ```
1165     /// #![feature(path_buf_capacity)]
1166     /// use std::path::PathBuf;
1167     ///
1168     /// let mut path = PathBuf::with_capacity(10);
1169     /// let capacity = path.capacity();
1170     ///
1171     /// // This push is done without reallocating
1172     /// path.push(r"C:\");
1173     ///
1174     /// assert_eq!(capacity, path.capacity());
1175     /// ```
1176     ///
1177     /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1178     /// [`OsString`]: ../ffi/struct.OsString.html
1179     #[unstable(feature = "path_buf_capacity", issue = "58234")]
1180     pub fn with_capacity(capacity: usize) -> PathBuf {
1181         PathBuf {
1182             inner: OsString::with_capacity(capacity)
1183         }
1184     }
1185
1186     /// Coerces to a [`Path`] slice.
1187     ///
1188     /// [`Path`]: struct.Path.html
1189     ///
1190     /// # Examples
1191     ///
1192     /// ```
1193     /// use std::path::{Path, PathBuf};
1194     ///
1195     /// let p = PathBuf::from("/test");
1196     /// assert_eq!(Path::new("/test"), p.as_path());
1197     /// ```
1198     #[stable(feature = "rust1", since = "1.0.0")]
1199     pub fn as_path(&self) -> &Path {
1200         self
1201     }
1202
1203     /// Extends `self` with `path`.
1204     ///
1205     /// If `path` is absolute, it replaces the current path.
1206     ///
1207     /// On Windows:
1208     ///
1209     /// * if `path` has a root but no prefix (e.g., `\windows`), it
1210     ///   replaces everything except for the prefix (if any) of `self`.
1211     /// * if `path` has a prefix but no root, it replaces `self`.
1212     ///
1213     /// # Examples
1214     ///
1215     /// Pushing a relative path extends the existing path:
1216     ///
1217     /// ```
1218     /// use std::path::PathBuf;
1219     ///
1220     /// let mut path = PathBuf::from("/tmp");
1221     /// path.push("file.bk");
1222     /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1223     /// ```
1224     ///
1225     /// Pushing an absolute path replaces the existing path:
1226     ///
1227     /// ```
1228     /// use std::path::PathBuf;
1229     ///
1230     /// let mut path = PathBuf::from("/tmp");
1231     /// path.push("/etc");
1232     /// assert_eq!(path, PathBuf::from("/etc"));
1233     /// ```
1234     #[stable(feature = "rust1", since = "1.0.0")]
1235     pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1236         self._push(path.as_ref())
1237     }
1238
1239     fn _push(&mut self, path: &Path) {
1240         // in general, a separator is needed if the rightmost byte is not a separator
1241         let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1242
1243         // in the special case of `C:` on Windows, do *not* add a separator
1244         {
1245             let comps = self.components();
1246             if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1247                comps.prefix.unwrap().is_drive() {
1248                 need_sep = false
1249             }
1250         }
1251
1252         // absolute `path` replaces `self`
1253         if path.is_absolute() || path.prefix().is_some() {
1254             self.as_mut_vec().truncate(0);
1255
1256         // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1257         } else if path.has_root() {
1258             let prefix_len = self.components().prefix_remaining();
1259             self.as_mut_vec().truncate(prefix_len);
1260
1261         // `path` is a pure relative path
1262         } else if need_sep {
1263             self.inner.push(MAIN_SEP_STR);
1264         }
1265
1266         self.inner.push(path);
1267     }
1268
1269     /// Truncates `self` to [`self.parent`].
1270     ///
1271     /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1272     /// Otherwise, returns `true`.
1273     ///
1274     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1275     /// [`self.parent`]: struct.PathBuf.html#method.parent
1276     ///
1277     /// # Examples
1278     ///
1279     /// ```
1280     /// use std::path::{Path, PathBuf};
1281     ///
1282     /// let mut p = PathBuf::from("/test/test.rs");
1283     ///
1284     /// p.pop();
1285     /// assert_eq!(Path::new("/test"), p);
1286     /// p.pop();
1287     /// assert_eq!(Path::new("/"), p);
1288     /// ```
1289     #[stable(feature = "rust1", since = "1.0.0")]
1290     pub fn pop(&mut self) -> bool {
1291         match self.parent().map(|p| p.as_u8_slice().len()) {
1292             Some(len) => {
1293                 self.as_mut_vec().truncate(len);
1294                 true
1295             }
1296             None => false,
1297         }
1298     }
1299
1300     /// Updates [`self.file_name`] to `file_name`.
1301     ///
1302     /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1303     /// `file_name`.
1304     ///
1305     /// Otherwise it is equivalent to calling [`pop`] and then pushing
1306     /// `file_name`. The new path will be a sibling of the original path.
1307     /// (That is, it will have the same parent.)
1308     ///
1309     /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1310     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1311     /// [`pop`]: struct.PathBuf.html#method.pop
1312     ///
1313     /// # Examples
1314     ///
1315     /// ```
1316     /// use std::path::PathBuf;
1317     ///
1318     /// let mut buf = PathBuf::from("/");
1319     /// assert!(buf.file_name() == None);
1320     /// buf.set_file_name("bar");
1321     /// assert!(buf == PathBuf::from("/bar"));
1322     /// assert!(buf.file_name().is_some());
1323     /// buf.set_file_name("baz.txt");
1324     /// assert!(buf == PathBuf::from("/baz.txt"));
1325     /// ```
1326     #[stable(feature = "rust1", since = "1.0.0")]
1327     pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1328         self._set_file_name(file_name.as_ref())
1329     }
1330
1331     fn _set_file_name(&mut self, file_name: &OsStr) {
1332         if self.file_name().is_some() {
1333             let popped = self.pop();
1334             debug_assert!(popped);
1335         }
1336         self.push(file_name);
1337     }
1338
1339     /// Updates [`self.extension`] to `extension`.
1340     ///
1341     /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1342     /// returns `true` and updates the extension otherwise.
1343     ///
1344     /// If [`self.extension`] is [`None`], the extension is added; otherwise
1345     /// it is replaced.
1346     ///
1347     /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1348     /// [`self.extension`]: struct.PathBuf.html#method.extension
1349     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1350     ///
1351     /// # Examples
1352     ///
1353     /// ```
1354     /// use std::path::{Path, PathBuf};
1355     ///
1356     /// let mut p = PathBuf::from("/feel/the");
1357     ///
1358     /// p.set_extension("force");
1359     /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1360     ///
1361     /// p.set_extension("dark_side");
1362     /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1363     /// ```
1364     #[stable(feature = "rust1", since = "1.0.0")]
1365     pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1366         self._set_extension(extension.as_ref())
1367     }
1368
1369     fn _set_extension(&mut self, extension: &OsStr) -> bool {
1370         if self.file_name().is_none() {
1371             return false;
1372         }
1373
1374         let mut stem = match self.file_stem() {
1375             Some(stem) => stem.to_os_string(),
1376             None => OsString::new(),
1377         };
1378
1379         if !os_str_as_u8_slice(extension).is_empty() {
1380             stem.push(".");
1381             stem.push(extension);
1382         }
1383         self.set_file_name(&stem);
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 Path into a Rc by copying the Path data into a new Rc 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 a Rc by copying the Path data into a new Rc 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 Path into a Rc by copying the Path 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 a 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 pub struct Path {
1759     inner: OsStr,
1760 }
1761
1762 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1763 /// was not found.
1764 ///
1765 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1766 /// See its documentation for more.
1767 ///
1768 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1769 /// [`Path`]: struct.Path.html
1770 #[derive(Debug, Clone, PartialEq, Eq)]
1771 #[stable(since = "1.7.0", feature = "strip_prefix")]
1772 pub struct StripPrefixError(());
1773
1774 impl Path {
1775     // The following (private!) function allows construction of a path from a u8
1776     // slice, which is only safe when it is known to follow the OsStr encoding.
1777     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1778         Path::new(u8_slice_as_os_str(s))
1779     }
1780     // The following (private!) function reveals the byte encoding used for OsStr.
1781     fn as_u8_slice(&self) -> &[u8] {
1782         os_str_as_u8_slice(&self.inner)
1783     }
1784
1785     /// Directly wraps a string slice as a `Path` slice.
1786     ///
1787     /// This is a cost-free conversion.
1788     ///
1789     /// # Examples
1790     ///
1791     /// ```
1792     /// use std::path::Path;
1793     ///
1794     /// Path::new("foo.txt");
1795     /// ```
1796     ///
1797     /// You can create `Path`s from `String`s, or even other `Path`s:
1798     ///
1799     /// ```
1800     /// use std::path::Path;
1801     ///
1802     /// let string = String::from("foo.txt");
1803     /// let from_string = Path::new(&string);
1804     /// let from_path = Path::new(&from_string);
1805     /// assert_eq!(from_string, from_path);
1806     /// ```
1807     #[stable(feature = "rust1", since = "1.0.0")]
1808     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1809         unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1810     }
1811
1812     /// Yields the underlying [`OsStr`] slice.
1813     ///
1814     /// [`OsStr`]: ../ffi/struct.OsStr.html
1815     ///
1816     /// # Examples
1817     ///
1818     /// ```
1819     /// use std::path::Path;
1820     ///
1821     /// let os_str = Path::new("foo.txt").as_os_str();
1822     /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1823     /// ```
1824     #[stable(feature = "rust1", since = "1.0.0")]
1825     pub fn as_os_str(&self) -> &OsStr {
1826         &self.inner
1827     }
1828
1829     /// Yields a [`&str`] slice if the `Path` is valid unicode.
1830     ///
1831     /// This conversion may entail doing a check for UTF-8 validity.
1832     ///
1833     /// [`&str`]: ../primitive.str.html
1834     ///
1835     /// # Examples
1836     ///
1837     /// ```
1838     /// use std::path::Path;
1839     ///
1840     /// let path = Path::new("foo.txt");
1841     /// assert_eq!(path.to_str(), Some("foo.txt"));
1842     /// ```
1843     #[stable(feature = "rust1", since = "1.0.0")]
1844     pub fn to_str(&self) -> Option<&str> {
1845         self.inner.to_str()
1846     }
1847
1848     /// Converts a `Path` to a [`Cow<str>`].
1849     ///
1850     /// Any non-Unicode sequences are replaced with
1851     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1852     ///
1853     /// [`Cow<str>`]: ../borrow/enum.Cow.html
1854     /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1855     ///
1856     /// # Examples
1857     ///
1858     /// Calling `to_string_lossy` on a `Path` with valid unicode:
1859     ///
1860     /// ```
1861     /// use std::path::Path;
1862     ///
1863     /// let path = Path::new("foo.txt");
1864     /// assert_eq!(path.to_string_lossy(), "foo.txt");
1865     /// ```
1866     ///
1867     /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1868     /// have returned `"fo�.txt"`.
1869     #[stable(feature = "rust1", since = "1.0.0")]
1870     pub fn to_string_lossy(&self) -> Cow<'_, str> {
1871         self.inner.to_string_lossy()
1872     }
1873
1874     /// Converts a `Path` to an owned [`PathBuf`].
1875     ///
1876     /// [`PathBuf`]: struct.PathBuf.html
1877     ///
1878     /// # Examples
1879     ///
1880     /// ```
1881     /// use std::path::Path;
1882     ///
1883     /// let path_buf = Path::new("foo.txt").to_path_buf();
1884     /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1885     /// ```
1886     #[rustc_conversion_suggestion]
1887     #[stable(feature = "rust1", since = "1.0.0")]
1888     pub fn to_path_buf(&self) -> PathBuf {
1889         PathBuf::from(self.inner.to_os_string())
1890     }
1891
1892     /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1893     /// the current directory.
1894     ///
1895     /// * On Unix, a path is absolute if it starts with the root, so
1896     /// `is_absolute` and [`has_root`] are equivalent.
1897     ///
1898     /// * On Windows, a path is absolute if it has a prefix and starts with the
1899     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1900     ///
1901     /// # Examples
1902     ///
1903     /// ```
1904     /// use std::path::Path;
1905     ///
1906     /// assert!(!Path::new("foo.txt").is_absolute());
1907     /// ```
1908     ///
1909     /// [`has_root`]: #method.has_root
1910     #[stable(feature = "rust1", since = "1.0.0")]
1911     #[allow(deprecated)]
1912     pub fn is_absolute(&self) -> bool {
1913         if cfg!(target_os = "redox") {
1914             // FIXME: Allow Redox prefixes
1915             self.has_root() || has_redox_scheme(self.as_u8_slice())
1916         } else {
1917             self.has_root() && (cfg!(unix) || self.prefix().is_some())
1918         }
1919     }
1920
1921     /// Returns `true` if the `Path` is relative, i.e., not absolute.
1922     ///
1923     /// See [`is_absolute`]'s documentation for more details.
1924     ///
1925     /// # Examples
1926     ///
1927     /// ```
1928     /// use std::path::Path;
1929     ///
1930     /// assert!(Path::new("foo.txt").is_relative());
1931     /// ```
1932     ///
1933     /// [`is_absolute`]: #method.is_absolute
1934     #[stable(feature = "rust1", since = "1.0.0")]
1935     pub fn is_relative(&self) -> bool {
1936         !self.is_absolute()
1937     }
1938
1939     fn prefix(&self) -> Option<Prefix<'_>> {
1940         self.components().prefix
1941     }
1942
1943     /// Returns `true` if the `Path` has a root.
1944     ///
1945     /// * On Unix, a path has a root if it begins with `/`.
1946     ///
1947     /// * On Windows, a path has a root if it:
1948     ///     * has no prefix and begins with a separator, e.g., `\windows`
1949     ///     * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1950     ///     * has any non-disk prefix, e.g., `\\server\share`
1951     ///
1952     /// # Examples
1953     ///
1954     /// ```
1955     /// use std::path::Path;
1956     ///
1957     /// assert!(Path::new("/etc/passwd").has_root());
1958     /// ```
1959     #[stable(feature = "rust1", since = "1.0.0")]
1960     pub fn has_root(&self) -> bool {
1961         self.components().has_root()
1962     }
1963
1964     /// Returns the `Path` without its final component, if there is one.
1965     ///
1966     /// Returns [`None`] if the path terminates in a root or prefix.
1967     ///
1968     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1969     ///
1970     /// # Examples
1971     ///
1972     /// ```
1973     /// use std::path::Path;
1974     ///
1975     /// let path = Path::new("/foo/bar");
1976     /// let parent = path.parent().unwrap();
1977     /// assert_eq!(parent, Path::new("/foo"));
1978     ///
1979     /// let grand_parent = parent.parent().unwrap();
1980     /// assert_eq!(grand_parent, Path::new("/"));
1981     /// assert_eq!(grand_parent.parent(), None);
1982     /// ```
1983     #[stable(feature = "rust1", since = "1.0.0")]
1984     pub fn parent(&self) -> Option<&Path> {
1985         let mut comps = self.components();
1986         let comp = comps.next_back();
1987         comp.and_then(|p| {
1988             match p {
1989                 Component::Normal(_) |
1990                 Component::CurDir |
1991                 Component::ParentDir => Some(comps.as_path()),
1992                 _ => None,
1993             }
1994         })
1995     }
1996
1997     /// Produces an iterator over `Path` and its ancestors.
1998     ///
1999     /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2000     /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2001     /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2002     /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2003     /// namely `&self`.
2004     ///
2005     /// # Examples
2006     ///
2007     /// ```
2008     /// use std::path::Path;
2009     ///
2010     /// let mut ancestors = Path::new("/foo/bar").ancestors();
2011     /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2012     /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2013     /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2014     /// assert_eq!(ancestors.next(), None);
2015     /// ```
2016     ///
2017     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2018     /// [`parent`]: struct.Path.html#method.parent
2019     #[stable(feature = "path_ancestors", since = "1.28.0")]
2020     pub fn ancestors(&self) -> Ancestors<'_> {
2021         Ancestors {
2022             next: Some(&self),
2023         }
2024     }
2025
2026     /// Returns the final component of the `Path`, if there is one.
2027     ///
2028     /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2029     /// is the directory name.
2030     ///
2031     /// Returns [`None`] if the path terminates in `..`.
2032     ///
2033     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2034     ///
2035     /// # Examples
2036     ///
2037     /// ```
2038     /// use std::path::Path;
2039     /// use std::ffi::OsStr;
2040     ///
2041     /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2042     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2043     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2044     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2045     /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2046     /// assert_eq!(None, Path::new("/").file_name());
2047     /// ```
2048     #[stable(feature = "rust1", since = "1.0.0")]
2049     pub fn file_name(&self) -> Option<&OsStr> {
2050         self.components().next_back().and_then(|p| {
2051             match p {
2052                 Component::Normal(p) => Some(p.as_ref()),
2053                 _ => None,
2054             }
2055         })
2056     }
2057
2058     /// Returns a path that, when joined onto `base`, yields `self`.
2059     ///
2060     /// # Errors
2061     ///
2062     /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2063     /// returns `false`), returns [`Err`].
2064     ///
2065     /// [`starts_with`]: #method.starts_with
2066     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2067     ///
2068     /// # Examples
2069     ///
2070     /// ```
2071     /// use std::path::{Path, PathBuf};
2072     ///
2073     /// let path = Path::new("/test/haha/foo.txt");
2074     ///
2075     /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2076     /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2077     /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2078     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2079     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2080     /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2081     /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2082     ///
2083     /// let prefix = PathBuf::from("/test/");
2084     /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2085     /// ```
2086     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2087     pub fn strip_prefix<P>(&self, base: P)
2088                            -> Result<&Path, StripPrefixError>
2089         where P: AsRef<Path>
2090     {
2091         self._strip_prefix(base.as_ref())
2092     }
2093
2094     fn _strip_prefix(&self, base: &Path)
2095                      -> Result<&Path, StripPrefixError> {
2096         iter_after(self.components(), base.components())
2097             .map(|c| c.as_path())
2098             .ok_or(StripPrefixError(()))
2099     }
2100
2101     /// Determines whether `base` is a prefix of `self`.
2102     ///
2103     /// Only considers whole path components to match.
2104     ///
2105     /// # Examples
2106     ///
2107     /// ```
2108     /// use std::path::Path;
2109     ///
2110     /// let path = Path::new("/etc/passwd");
2111     ///
2112     /// assert!(path.starts_with("/etc"));
2113     /// assert!(path.starts_with("/etc/"));
2114     /// assert!(path.starts_with("/etc/passwd"));
2115     /// assert!(path.starts_with("/etc/passwd/"));
2116     ///
2117     /// assert!(!path.starts_with("/e"));
2118     /// ```
2119     #[stable(feature = "rust1", since = "1.0.0")]
2120     pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2121         self._starts_with(base.as_ref())
2122     }
2123
2124     fn _starts_with(&self, base: &Path) -> bool {
2125         iter_after(self.components(), base.components()).is_some()
2126     }
2127
2128     /// Determines whether `child` is a suffix of `self`.
2129     ///
2130     /// Only considers whole path components to match.
2131     ///
2132     /// # Examples
2133     ///
2134     /// ```
2135     /// use std::path::Path;
2136     ///
2137     /// let path = Path::new("/etc/passwd");
2138     ///
2139     /// assert!(path.ends_with("passwd"));
2140     /// ```
2141     #[stable(feature = "rust1", since = "1.0.0")]
2142     pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2143         self._ends_with(child.as_ref())
2144     }
2145
2146     fn _ends_with(&self, child: &Path) -> bool {
2147         iter_after(self.components().rev(), child.components().rev()).is_some()
2148     }
2149
2150     /// Extracts the stem (non-extension) portion of [`self.file_name`].
2151     ///
2152     /// [`self.file_name`]: struct.Path.html#method.file_name
2153     ///
2154     /// The stem is:
2155     ///
2156     /// * [`None`], if there is no file name;
2157     /// * The entire file name if there is no embedded `.`;
2158     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2159     /// * Otherwise, the portion of the file name before the final `.`
2160     ///
2161     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2162     ///
2163     /// # Examples
2164     ///
2165     /// ```
2166     /// use std::path::Path;
2167     ///
2168     /// let path = Path::new("foo.rs");
2169     ///
2170     /// assert_eq!("foo", path.file_stem().unwrap());
2171     /// ```
2172     #[stable(feature = "rust1", since = "1.0.0")]
2173     pub fn file_stem(&self) -> Option<&OsStr> {
2174         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2175     }
2176
2177     /// Extracts the extension of [`self.file_name`], if possible.
2178     ///
2179     /// The extension is:
2180     ///
2181     /// * [`None`], if there is no file name;
2182     /// * [`None`], if there is no embedded `.`;
2183     /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2184     /// * Otherwise, the portion of the file name after the final `.`
2185     ///
2186     /// [`self.file_name`]: struct.Path.html#method.file_name
2187     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2188     ///
2189     /// # Examples
2190     ///
2191     /// ```
2192     /// use std::path::Path;
2193     ///
2194     /// let path = Path::new("foo.rs");
2195     ///
2196     /// assert_eq!("rs", path.extension().unwrap());
2197     /// ```
2198     #[stable(feature = "rust1", since = "1.0.0")]
2199     pub fn extension(&self) -> Option<&OsStr> {
2200         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2201     }
2202
2203     /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2204     ///
2205     /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2206     ///
2207     /// [`PathBuf`]: struct.PathBuf.html
2208     /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2209     ///
2210     /// # Examples
2211     ///
2212     /// ```
2213     /// use std::path::{Path, PathBuf};
2214     ///
2215     /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2216     /// ```
2217     #[stable(feature = "rust1", since = "1.0.0")]
2218     pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2219         self._join(path.as_ref())
2220     }
2221
2222     fn _join(&self, path: &Path) -> PathBuf {
2223         let mut buf = self.to_path_buf();
2224         buf.push(path);
2225         buf
2226     }
2227
2228     /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2229     ///
2230     /// See [`PathBuf::set_file_name`] for more details.
2231     ///
2232     /// [`PathBuf`]: struct.PathBuf.html
2233     /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2234     ///
2235     /// # Examples
2236     ///
2237     /// ```
2238     /// use std::path::{Path, PathBuf};
2239     ///
2240     /// let path = Path::new("/tmp/foo.txt");
2241     /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2242     ///
2243     /// let path = Path::new("/tmp");
2244     /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2245     /// ```
2246     #[stable(feature = "rust1", since = "1.0.0")]
2247     pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2248         self._with_file_name(file_name.as_ref())
2249     }
2250
2251     fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2252         let mut buf = self.to_path_buf();
2253         buf.set_file_name(file_name);
2254         buf
2255     }
2256
2257     /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2258     ///
2259     /// See [`PathBuf::set_extension`] for more details.
2260     ///
2261     /// [`PathBuf`]: struct.PathBuf.html
2262     /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2263     ///
2264     /// # Examples
2265     ///
2266     /// ```
2267     /// use std::path::{Path, PathBuf};
2268     ///
2269     /// let path = Path::new("foo.rs");
2270     /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2271     /// ```
2272     #[stable(feature = "rust1", since = "1.0.0")]
2273     pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2274         self._with_extension(extension.as_ref())
2275     }
2276
2277     fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2278         let mut buf = self.to_path_buf();
2279         buf.set_extension(extension);
2280         buf
2281     }
2282
2283     /// Produces an iterator over the [`Component`]s of the path.
2284     ///
2285     /// When parsing the path, there is a small amount of normalization:
2286     ///
2287     /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2288     ///   `a` and `b` as components.
2289     ///
2290     /// * Occurrences of `.` are normalized away, except if they are at the
2291     ///   beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2292     ///   `a/b` all have `a` and `b` as components, but `./a/b` starts with
2293     ///   an additional [`CurDir`] component.
2294     ///
2295     /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2296     ///
2297     /// Note that no other normalization takes place; in particular, `a/c`
2298     /// and `a/b/../c` are distinct, to account for the possibility that `b`
2299     /// is a symbolic link (so its parent isn't `a`).
2300     ///
2301     /// # Examples
2302     ///
2303     /// ```
2304     /// use std::path::{Path, Component};
2305     /// use std::ffi::OsStr;
2306     ///
2307     /// let mut components = Path::new("/tmp/foo.txt").components();
2308     ///
2309     /// assert_eq!(components.next(), Some(Component::RootDir));
2310     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2311     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2312     /// assert_eq!(components.next(), None)
2313     /// ```
2314     ///
2315     /// [`Component`]: enum.Component.html
2316     /// [`CurDir`]: enum.Component.html#variant.CurDir
2317     #[stable(feature = "rust1", since = "1.0.0")]
2318     pub fn components(&self) -> Components<'_> {
2319         let prefix = parse_prefix(self.as_os_str());
2320         Components {
2321             path: self.as_u8_slice(),
2322             prefix,
2323             has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2324                                has_redox_scheme(self.as_u8_slice()),
2325             front: State::Prefix,
2326             back: State::Body,
2327         }
2328     }
2329
2330     /// Produces an iterator over the path's components viewed as [`OsStr`]
2331     /// slices.
2332     ///
2333     /// For more information about the particulars of how the path is separated
2334     /// into components, see [`components`].
2335     ///
2336     /// [`components`]: #method.components
2337     /// [`OsStr`]: ../ffi/struct.OsStr.html
2338     ///
2339     /// # Examples
2340     ///
2341     /// ```
2342     /// use std::path::{self, Path};
2343     /// use std::ffi::OsStr;
2344     ///
2345     /// let mut it = Path::new("/tmp/foo.txt").iter();
2346     /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2347     /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2348     /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2349     /// assert_eq!(it.next(), None)
2350     /// ```
2351     #[stable(feature = "rust1", since = "1.0.0")]
2352     pub fn iter(&self) -> Iter<'_> {
2353         Iter { inner: self.components() }
2354     }
2355
2356     /// Returns an object that implements [`Display`] for safely printing paths
2357     /// that may contain non-Unicode data.
2358     ///
2359     /// [`Display`]: ../fmt/trait.Display.html
2360     ///
2361     /// # Examples
2362     ///
2363     /// ```
2364     /// use std::path::Path;
2365     ///
2366     /// let path = Path::new("/tmp/foo.rs");
2367     ///
2368     /// println!("{}", path.display());
2369     /// ```
2370     #[stable(feature = "rust1", since = "1.0.0")]
2371     pub fn display(&self) -> Display<'_> {
2372         Display { path: self }
2373     }
2374
2375     /// Queries the file system to get information about a file, directory, etc.
2376     ///
2377     /// This function will traverse symbolic links to query information about the
2378     /// destination file.
2379     ///
2380     /// This is an alias to [`fs::metadata`].
2381     ///
2382     /// [`fs::metadata`]: ../fs/fn.metadata.html
2383     ///
2384     /// # Examples
2385     ///
2386     /// ```no_run
2387     /// use std::path::Path;
2388     ///
2389     /// let path = Path::new("/Minas/tirith");
2390     /// let metadata = path.metadata().expect("metadata call failed");
2391     /// println!("{:?}", metadata.file_type());
2392     /// ```
2393     #[stable(feature = "path_ext", since = "1.5.0")]
2394     pub fn metadata(&self) -> io::Result<fs::Metadata> {
2395         fs::metadata(self)
2396     }
2397
2398     /// Queries the metadata about a file without following symlinks.
2399     ///
2400     /// This is an alias to [`fs::symlink_metadata`].
2401     ///
2402     /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2403     ///
2404     /// # Examples
2405     ///
2406     /// ```no_run
2407     /// use std::path::Path;
2408     ///
2409     /// let path = Path::new("/Minas/tirith");
2410     /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2411     /// println!("{:?}", metadata.file_type());
2412     /// ```
2413     #[stable(feature = "path_ext", since = "1.5.0")]
2414     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2415         fs::symlink_metadata(self)
2416     }
2417
2418     /// Returns the canonical, absolute form of the path with all intermediate
2419     /// components normalized and symbolic links resolved.
2420     ///
2421     /// This is an alias to [`fs::canonicalize`].
2422     ///
2423     /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2424     ///
2425     /// # Examples
2426     ///
2427     /// ```no_run
2428     /// use std::path::{Path, PathBuf};
2429     ///
2430     /// let path = Path::new("/foo/test/../test/bar.rs");
2431     /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2432     /// ```
2433     #[stable(feature = "path_ext", since = "1.5.0")]
2434     pub fn canonicalize(&self) -> io::Result<PathBuf> {
2435         fs::canonicalize(self)
2436     }
2437
2438     /// Reads a symbolic link, returning the file that the link points to.
2439     ///
2440     /// This is an alias to [`fs::read_link`].
2441     ///
2442     /// [`fs::read_link`]: ../fs/fn.read_link.html
2443     ///
2444     /// # Examples
2445     ///
2446     /// ```no_run
2447     /// use std::path::Path;
2448     ///
2449     /// let path = Path::new("/laputa/sky_castle.rs");
2450     /// let path_link = path.read_link().expect("read_link call failed");
2451     /// ```
2452     #[stable(feature = "path_ext", since = "1.5.0")]
2453     pub fn read_link(&self) -> io::Result<PathBuf> {
2454         fs::read_link(self)
2455     }
2456
2457     /// Returns an iterator over the entries within a directory.
2458     ///
2459     /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2460     /// errors may be encountered after an iterator is initially constructed.
2461     ///
2462     /// This is an alias to [`fs::read_dir`].
2463     ///
2464     /// [`io::Result`]: ../io/type.Result.html
2465     /// [`DirEntry`]: ../fs/struct.DirEntry.html
2466     /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2467     ///
2468     /// # Examples
2469     ///
2470     /// ```no_run
2471     /// use std::path::Path;
2472     ///
2473     /// let path = Path::new("/laputa");
2474     /// for entry in path.read_dir().expect("read_dir call failed") {
2475     ///     if let Ok(entry) = entry {
2476     ///         println!("{:?}", entry.path());
2477     ///     }
2478     /// }
2479     /// ```
2480     #[stable(feature = "path_ext", since = "1.5.0")]
2481     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2482         fs::read_dir(self)
2483     }
2484
2485     /// Returns `true` if the path points at an existing entity.
2486     ///
2487     /// This function will traverse symbolic links to query information about the
2488     /// destination file. In case of broken symbolic links this will return `false`.
2489     ///
2490     /// If you cannot access the directory containing the file, e.g., because of a
2491     /// permission error, this will return `false`.
2492     ///
2493     /// # Examples
2494     ///
2495     /// ```no_run
2496     /// use std::path::Path;
2497     /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2498     /// ```
2499     ///
2500     /// # See Also
2501     ///
2502     /// This is a convenience function that coerces errors to false. If you want to
2503     /// check errors, call [fs::metadata].
2504     ///
2505     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2506     #[stable(feature = "path_ext", since = "1.5.0")]
2507     pub fn exists(&self) -> bool {
2508         fs::metadata(self).is_ok()
2509     }
2510
2511     /// Returns `true` if the path exists on disk and is pointing at a regular file.
2512     ///
2513     /// This function will traverse symbolic links to query information about the
2514     /// destination file. In case of broken symbolic links this will return `false`.
2515     ///
2516     /// If you cannot access the directory containing the file, e.g., because of a
2517     /// permission error, this will return `false`.
2518     ///
2519     /// # Examples
2520     ///
2521     /// ```no_run
2522     /// use std::path::Path;
2523     /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2524     /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2525     /// ```
2526     ///
2527     /// # See Also
2528     ///
2529     /// This is a convenience function that coerces errors to false. If you want to
2530     /// check errors, call [fs::metadata] and handle its Result. Then call
2531     /// [fs::Metadata::is_file] if it was Ok.
2532     ///
2533     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2534     /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2535     #[stable(feature = "path_ext", since = "1.5.0")]
2536     pub fn is_file(&self) -> bool {
2537         fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2538     }
2539
2540     /// Returns `true` if the path exists on disk and is pointing at a directory.
2541     ///
2542     /// This function will traverse symbolic links to query information about the
2543     /// destination file. In case of broken symbolic links this will return `false`.
2544     ///
2545     /// If you cannot access the directory containing the file, e.g., because of a
2546     /// permission error, this will return `false`.
2547     ///
2548     /// # Examples
2549     ///
2550     /// ```no_run
2551     /// use std::path::Path;
2552     /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2553     /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2554     /// ```
2555     ///
2556     /// # See Also
2557     ///
2558     /// This is a convenience function that coerces errors to false. If you want to
2559     /// check errors, call [fs::metadata] and handle its Result. Then call
2560     /// [fs::Metadata::is_dir] if it was Ok.
2561     ///
2562     /// [fs::metadata]: ../../std/fs/fn.metadata.html
2563     /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2564     #[stable(feature = "path_ext", since = "1.5.0")]
2565     pub fn is_dir(&self) -> bool {
2566         fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2567     }
2568
2569     /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2570     /// allocating.
2571     ///
2572     /// [`Box`]: ../../std/boxed/struct.Box.html
2573     /// [`PathBuf`]: struct.PathBuf.html
2574     #[stable(feature = "into_boxed_path", since = "1.20.0")]
2575     pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2576         let rw = Box::into_raw(self) as *mut OsStr;
2577         let inner = unsafe { Box::from_raw(rw) };
2578         PathBuf { inner: OsString::from(inner) }
2579     }
2580 }
2581
2582 #[stable(feature = "rust1", since = "1.0.0")]
2583 impl AsRef<OsStr> for Path {
2584     fn as_ref(&self) -> &OsStr {
2585         &self.inner
2586     }
2587 }
2588
2589 #[stable(feature = "rust1", since = "1.0.0")]
2590 impl fmt::Debug for Path {
2591     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2592         fmt::Debug::fmt(&self.inner, formatter)
2593     }
2594 }
2595
2596 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2597 ///
2598 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2599 /// [`Display`] trait in a way that mitigates that. It is created by the
2600 /// [`display`][`Path::display`] method on [`Path`].
2601 ///
2602 /// # Examples
2603 ///
2604 /// ```
2605 /// use std::path::Path;
2606 ///
2607 /// let path = Path::new("/tmp/foo.rs");
2608 ///
2609 /// println!("{}", path.display());
2610 /// ```
2611 ///
2612 /// [`Display`]: ../../std/fmt/trait.Display.html
2613 /// [`format!`]: ../../std/macro.format.html
2614 /// [`Path`]: struct.Path.html
2615 /// [`Path::display`]: struct.Path.html#method.display
2616 #[stable(feature = "rust1", since = "1.0.0")]
2617 pub struct Display<'a> {
2618     path: &'a Path,
2619 }
2620
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 impl fmt::Debug for Display<'_> {
2623     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2624         fmt::Debug::fmt(&self.path, f)
2625     }
2626 }
2627
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 impl fmt::Display for Display<'_> {
2630     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2631         self.path.inner.display(f)
2632     }
2633 }
2634
2635 #[stable(feature = "rust1", since = "1.0.0")]
2636 impl cmp::PartialEq for Path {
2637     fn eq(&self, other: &Path) -> bool {
2638         self.components().eq(other.components())
2639     }
2640 }
2641
2642 #[stable(feature = "rust1", since = "1.0.0")]
2643 impl Hash for Path {
2644     fn hash<H: Hasher>(&self, h: &mut H) {
2645         for component in self.components() {
2646             component.hash(h);
2647         }
2648     }
2649 }
2650
2651 #[stable(feature = "rust1", since = "1.0.0")]
2652 impl cmp::Eq for Path {}
2653
2654 #[stable(feature = "rust1", since = "1.0.0")]
2655 impl cmp::PartialOrd for Path {
2656     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2657         self.components().partial_cmp(other.components())
2658     }
2659 }
2660
2661 #[stable(feature = "rust1", since = "1.0.0")]
2662 impl cmp::Ord for Path {
2663     fn cmp(&self, other: &Path) -> cmp::Ordering {
2664         self.components().cmp(other.components())
2665     }
2666 }
2667
2668 #[stable(feature = "rust1", since = "1.0.0")]
2669 impl AsRef<Path> for Path {
2670     fn as_ref(&self) -> &Path {
2671         self
2672     }
2673 }
2674
2675 #[stable(feature = "rust1", since = "1.0.0")]
2676 impl AsRef<Path> for OsStr {
2677     fn as_ref(&self) -> &Path {
2678         Path::new(self)
2679     }
2680 }
2681
2682 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2683 impl AsRef<Path> for Cow<'_, OsStr> {
2684     fn as_ref(&self) -> &Path {
2685         Path::new(self)
2686     }
2687 }
2688
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 impl AsRef<Path> for OsString {
2691     fn as_ref(&self) -> &Path {
2692         Path::new(self)
2693     }
2694 }
2695
2696 #[stable(feature = "rust1", since = "1.0.0")]
2697 impl AsRef<Path> for str {
2698     fn as_ref(&self) -> &Path {
2699         Path::new(self)
2700     }
2701 }
2702
2703 #[stable(feature = "rust1", since = "1.0.0")]
2704 impl AsRef<Path> for String {
2705     fn as_ref(&self) -> &Path {
2706         Path::new(self)
2707     }
2708 }
2709
2710 #[stable(feature = "rust1", since = "1.0.0")]
2711 impl AsRef<Path> for PathBuf {
2712     fn as_ref(&self) -> &Path {
2713         self
2714     }
2715 }
2716
2717 #[stable(feature = "path_into_iter", since = "1.6.0")]
2718 impl<'a> IntoIterator for &'a PathBuf {
2719     type Item = &'a OsStr;
2720     type IntoIter = Iter<'a>;
2721     fn into_iter(self) -> Iter<'a> { self.iter() }
2722 }
2723
2724 #[stable(feature = "path_into_iter", since = "1.6.0")]
2725 impl<'a> IntoIterator for &'a Path {
2726     type Item = &'a OsStr;
2727     type IntoIter = Iter<'a>;
2728     fn into_iter(self) -> Iter<'a> { self.iter() }
2729 }
2730
2731 macro_rules! impl_cmp {
2732     ($lhs:ty, $rhs: ty) => {
2733         #[stable(feature = "partialeq_path", since = "1.6.0")]
2734         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2735             #[inline]
2736             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2737         }
2738
2739         #[stable(feature = "partialeq_path", since = "1.6.0")]
2740         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2741             #[inline]
2742             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2743         }
2744
2745         #[stable(feature = "cmp_path", since = "1.8.0")]
2746         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2747             #[inline]
2748             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2749                 <Path as PartialOrd>::partial_cmp(self, other)
2750             }
2751         }
2752
2753         #[stable(feature = "cmp_path", since = "1.8.0")]
2754         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2755             #[inline]
2756             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2757                 <Path as PartialOrd>::partial_cmp(self, other)
2758             }
2759         }
2760     }
2761 }
2762
2763 impl_cmp!(PathBuf, Path);
2764 impl_cmp!(PathBuf, &'a Path);
2765 impl_cmp!(Cow<'a, Path>, Path);
2766 impl_cmp!(Cow<'a, Path>, &'b Path);
2767 impl_cmp!(Cow<'a, Path>, PathBuf);
2768
2769 macro_rules! impl_cmp_os_str {
2770     ($lhs:ty, $rhs: ty) => {
2771         #[stable(feature = "cmp_path", since = "1.8.0")]
2772         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2773             #[inline]
2774             fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2775         }
2776
2777         #[stable(feature = "cmp_path", since = "1.8.0")]
2778         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2779             #[inline]
2780             fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2781         }
2782
2783         #[stable(feature = "cmp_path", since = "1.8.0")]
2784         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2785             #[inline]
2786             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2787                 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2788             }
2789         }
2790
2791         #[stable(feature = "cmp_path", since = "1.8.0")]
2792         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2793             #[inline]
2794             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2795                 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2796             }
2797         }
2798     }
2799 }
2800
2801 impl_cmp_os_str!(PathBuf, OsStr);
2802 impl_cmp_os_str!(PathBuf, &'a OsStr);
2803 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2804 impl_cmp_os_str!(PathBuf, OsString);
2805 impl_cmp_os_str!(Path, OsStr);
2806 impl_cmp_os_str!(Path, &'a OsStr);
2807 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2808 impl_cmp_os_str!(Path, OsString);
2809 impl_cmp_os_str!(&'a Path, OsStr);
2810 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2811 impl_cmp_os_str!(&'a Path, OsString);
2812 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2813 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2814 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2815
2816 #[stable(since = "1.7.0", feature = "strip_prefix")]
2817 impl fmt::Display for StripPrefixError {
2818     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2819         self.description().fmt(f)
2820     }
2821 }
2822
2823 #[stable(since = "1.7.0", feature = "strip_prefix")]
2824 impl Error for StripPrefixError {
2825     fn description(&self) -> &str { "prefix not found" }
2826 }
2827
2828 #[cfg(test)]
2829 mod tests {
2830     use super::*;
2831
2832     use crate::rc::Rc;
2833     use crate::sync::Arc;
2834
2835     macro_rules! t(
2836         ($path:expr, iter: $iter:expr) => (
2837             {
2838                 let path = Path::new($path);
2839
2840                 // Forward iteration
2841                 let comps = path.iter()
2842                     .map(|p| p.to_string_lossy().into_owned())
2843                     .collect::<Vec<String>>();
2844                 let exp: &[&str] = &$iter;
2845                 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2846                 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2847                         exps, comps);
2848
2849                 // Reverse iteration
2850                 let comps = Path::new($path).iter().rev()
2851                     .map(|p| p.to_string_lossy().into_owned())
2852                     .collect::<Vec<String>>();
2853                 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2854                 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2855                         exps, comps);
2856             }
2857         );
2858
2859         ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2860             {
2861                 let path = Path::new($path);
2862
2863                 let act_root = path.has_root();
2864                 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2865                         $has_root, act_root);
2866
2867                 let act_abs = path.is_absolute();
2868                 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2869                         $is_absolute, act_abs);
2870             }
2871         );
2872
2873         ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2874             {
2875                 let path = Path::new($path);
2876
2877                 let parent = path.parent().map(|p| p.to_str().unwrap());
2878                 let exp_parent: Option<&str> = $parent;
2879                 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2880                         exp_parent, parent);
2881
2882                 let file = path.file_name().map(|p| p.to_str().unwrap());
2883                 let exp_file: Option<&str> = $file;
2884                 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2885                         exp_file, file);
2886             }
2887         );
2888
2889         ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2890             {
2891                 let path = Path::new($path);
2892
2893                 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2894                 let exp_stem: Option<&str> = $file_stem;
2895                 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2896                         exp_stem, stem);
2897
2898                 let ext = path.extension().map(|p| p.to_str().unwrap());
2899                 let exp_ext: Option<&str> = $extension;
2900                 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2901                         exp_ext, ext);
2902             }
2903         );
2904
2905         ($path:expr, iter: $iter:expr,
2906                      has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2907                      parent: $parent:expr, file_name: $file:expr,
2908                      file_stem: $file_stem:expr, extension: $extension:expr) => (
2909             {
2910                 t!($path, iter: $iter);
2911                 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2912                 t!($path, parent: $parent, file_name: $file);
2913                 t!($path, file_stem: $file_stem, extension: $extension);
2914             }
2915         );
2916     );
2917
2918     #[test]
2919     fn into() {
2920         use crate::borrow::Cow;
2921
2922         let static_path = Path::new("/home/foo");
2923         let static_cow_path: Cow<'static, Path> = static_path.into();
2924         let pathbuf = PathBuf::from("/home/foo");
2925
2926         {
2927             let path: &Path = &pathbuf;
2928             let borrowed_cow_path: Cow<'_, Path> = path.into();
2929
2930             assert_eq!(static_cow_path, borrowed_cow_path);
2931         }
2932
2933         let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2934
2935         assert_eq!(static_cow_path, owned_cow_path);
2936     }
2937
2938     #[test]
2939     #[cfg(unix)]
2940     pub fn test_decompositions_unix() {
2941         t!("",
2942            iter: [],
2943            has_root: false,
2944            is_absolute: false,
2945            parent: None,
2946            file_name: None,
2947            file_stem: None,
2948            extension: None
2949            );
2950
2951         t!("foo",
2952            iter: ["foo"],
2953            has_root: false,
2954            is_absolute: false,
2955            parent: Some(""),
2956            file_name: Some("foo"),
2957            file_stem: Some("foo"),
2958            extension: None
2959            );
2960
2961         t!("/",
2962            iter: ["/"],
2963            has_root: true,
2964            is_absolute: true,
2965            parent: None,
2966            file_name: None,
2967            file_stem: None,
2968            extension: None
2969            );
2970
2971         t!("/foo",
2972            iter: ["/", "foo"],
2973            has_root: true,
2974            is_absolute: true,
2975            parent: Some("/"),
2976            file_name: Some("foo"),
2977            file_stem: Some("foo"),
2978            extension: None
2979            );
2980
2981         t!("foo/",
2982            iter: ["foo"],
2983            has_root: false,
2984            is_absolute: false,
2985            parent: Some(""),
2986            file_name: Some("foo"),
2987            file_stem: Some("foo"),
2988            extension: None
2989            );
2990
2991         t!("/foo/",
2992            iter: ["/", "foo"],
2993            has_root: true,
2994            is_absolute: true,
2995            parent: Some("/"),
2996            file_name: Some("foo"),
2997            file_stem: Some("foo"),
2998            extension: None
2999            );
3000
3001         t!("foo/bar",
3002            iter: ["foo", "bar"],
3003            has_root: false,
3004            is_absolute: false,
3005            parent: Some("foo"),
3006            file_name: Some("bar"),
3007            file_stem: Some("bar"),
3008            extension: None
3009            );
3010
3011         t!("/foo/bar",
3012            iter: ["/", "foo", "bar"],
3013            has_root: true,
3014            is_absolute: true,
3015            parent: Some("/foo"),
3016            file_name: Some("bar"),
3017            file_stem: Some("bar"),
3018            extension: None
3019            );
3020
3021         t!("///foo///",
3022            iter: ["/", "foo"],
3023            has_root: true,
3024            is_absolute: true,
3025            parent: Some("/"),
3026            file_name: Some("foo"),
3027            file_stem: Some("foo"),
3028            extension: None
3029            );
3030
3031         t!("///foo///bar",
3032            iter: ["/", "foo", "bar"],
3033            has_root: true,
3034            is_absolute: true,
3035            parent: Some("///foo"),
3036            file_name: Some("bar"),
3037            file_stem: Some("bar"),
3038            extension: None
3039            );
3040
3041         t!("./.",
3042            iter: ["."],
3043            has_root: false,
3044            is_absolute: false,
3045            parent: Some(""),
3046            file_name: None,
3047            file_stem: None,
3048            extension: None
3049            );
3050
3051         t!("/..",
3052            iter: ["/", ".."],
3053            has_root: true,
3054            is_absolute: true,
3055            parent: Some("/"),
3056            file_name: None,
3057            file_stem: None,
3058            extension: None
3059            );
3060
3061         t!("../",
3062            iter: [".."],
3063            has_root: false,
3064            is_absolute: false,
3065            parent: Some(""),
3066            file_name: None,
3067            file_stem: None,
3068            extension: None
3069            );
3070
3071         t!("foo/.",
3072            iter: ["foo"],
3073            has_root: false,
3074            is_absolute: false,
3075            parent: Some(""),
3076            file_name: Some("foo"),
3077            file_stem: Some("foo"),
3078            extension: None
3079            );
3080
3081         t!("foo/..",
3082            iter: ["foo", ".."],
3083            has_root: false,
3084            is_absolute: false,
3085            parent: Some("foo"),
3086            file_name: None,
3087            file_stem: None,
3088            extension: None
3089            );
3090
3091         t!("foo/./",
3092            iter: ["foo"],
3093            has_root: false,
3094            is_absolute: false,
3095            parent: Some(""),
3096            file_name: Some("foo"),
3097            file_stem: Some("foo"),
3098            extension: None
3099            );
3100
3101         t!("foo/./bar",
3102            iter: ["foo", "bar"],
3103            has_root: false,
3104            is_absolute: false,
3105            parent: Some("foo"),
3106            file_name: Some("bar"),
3107            file_stem: Some("bar"),
3108            extension: None
3109            );
3110
3111         t!("foo/../",
3112            iter: ["foo", ".."],
3113            has_root: false,
3114            is_absolute: false,
3115            parent: Some("foo"),
3116            file_name: None,
3117            file_stem: None,
3118            extension: None
3119            );
3120
3121         t!("foo/../bar",
3122            iter: ["foo", "..", "bar"],
3123            has_root: false,
3124            is_absolute: false,
3125            parent: Some("foo/.."),
3126            file_name: Some("bar"),
3127            file_stem: Some("bar"),
3128            extension: None
3129            );
3130
3131         t!("./a",
3132            iter: [".", "a"],
3133            has_root: false,
3134            is_absolute: false,
3135            parent: Some("."),
3136            file_name: Some("a"),
3137            file_stem: Some("a"),
3138            extension: None
3139            );
3140
3141         t!(".",
3142            iter: ["."],
3143            has_root: false,
3144            is_absolute: false,
3145            parent: Some(""),
3146            file_name: None,
3147            file_stem: None,
3148            extension: None
3149            );
3150
3151         t!("./",
3152            iter: ["."],
3153            has_root: false,
3154            is_absolute: false,
3155            parent: Some(""),
3156            file_name: None,
3157            file_stem: None,
3158            extension: None
3159            );
3160
3161         t!("a/b",
3162            iter: ["a", "b"],
3163            has_root: false,
3164            is_absolute: false,
3165            parent: Some("a"),
3166            file_name: Some("b"),
3167            file_stem: Some("b"),
3168            extension: None
3169            );
3170
3171         t!("a//b",
3172            iter: ["a", "b"],
3173            has_root: false,
3174            is_absolute: false,
3175            parent: Some("a"),
3176            file_name: Some("b"),
3177            file_stem: Some("b"),
3178            extension: None
3179            );
3180
3181         t!("a/./b",
3182            iter: ["a", "b"],
3183            has_root: false,
3184            is_absolute: false,
3185            parent: Some("a"),
3186            file_name: Some("b"),
3187            file_stem: Some("b"),
3188            extension: None
3189            );
3190
3191         t!("a/b/c",
3192            iter: ["a", "b", "c"],
3193            has_root: false,
3194            is_absolute: false,
3195            parent: Some("a/b"),
3196            file_name: Some("c"),
3197            file_stem: Some("c"),
3198            extension: None
3199            );
3200
3201         t!(".foo",
3202            iter: [".foo"],
3203            has_root: false,
3204            is_absolute: false,
3205            parent: Some(""),
3206            file_name: Some(".foo"),
3207            file_stem: Some(".foo"),
3208            extension: None
3209            );
3210     }
3211
3212     #[test]
3213     #[cfg(windows)]
3214     pub fn test_decompositions_windows() {
3215         t!("",
3216            iter: [],
3217            has_root: false,
3218            is_absolute: false,
3219            parent: None,
3220            file_name: None,
3221            file_stem: None,
3222            extension: None
3223            );
3224
3225         t!("foo",
3226            iter: ["foo"],
3227            has_root: false,
3228            is_absolute: false,
3229            parent: Some(""),
3230            file_name: Some("foo"),
3231            file_stem: Some("foo"),
3232            extension: None
3233            );
3234
3235         t!("/",
3236            iter: ["\\"],
3237            has_root: true,
3238            is_absolute: false,
3239            parent: None,
3240            file_name: None,
3241            file_stem: None,
3242            extension: None
3243            );
3244
3245         t!("\\",
3246            iter: ["\\"],
3247            has_root: true,
3248            is_absolute: false,
3249            parent: None,
3250            file_name: None,
3251            file_stem: None,
3252            extension: None
3253            );
3254
3255         t!("c:",
3256            iter: ["c:"],
3257            has_root: false,
3258            is_absolute: false,
3259            parent: None,
3260            file_name: None,
3261            file_stem: None,
3262            extension: None
3263            );
3264
3265         t!("c:\\",
3266            iter: ["c:", "\\"],
3267            has_root: true,
3268            is_absolute: true,
3269            parent: None,
3270            file_name: None,
3271            file_stem: None,
3272            extension: None
3273            );
3274
3275         t!("c:/",
3276            iter: ["c:", "\\"],
3277            has_root: true,
3278            is_absolute: true,
3279            parent: None,
3280            file_name: None,
3281            file_stem: None,
3282            extension: None
3283            );
3284
3285         t!("/foo",
3286            iter: ["\\", "foo"],
3287            has_root: true,
3288            is_absolute: false,
3289            parent: Some("/"),
3290            file_name: Some("foo"),
3291            file_stem: Some("foo"),
3292            extension: None
3293            );
3294
3295         t!("foo/",
3296            iter: ["foo"],
3297            has_root: false,
3298            is_absolute: false,
3299            parent: Some(""),
3300            file_name: Some("foo"),
3301            file_stem: Some("foo"),
3302            extension: None
3303            );
3304
3305         t!("/foo/",
3306            iter: ["\\", "foo"],
3307            has_root: true,
3308            is_absolute: false,
3309            parent: Some("/"),
3310            file_name: Some("foo"),
3311            file_stem: Some("foo"),
3312            extension: None
3313            );
3314
3315         t!("foo/bar",
3316            iter: ["foo", "bar"],
3317            has_root: false,
3318            is_absolute: false,
3319            parent: Some("foo"),
3320            file_name: Some("bar"),
3321            file_stem: Some("bar"),
3322            extension: None
3323            );
3324
3325         t!("/foo/bar",
3326            iter: ["\\", "foo", "bar"],
3327            has_root: true,
3328            is_absolute: false,
3329            parent: Some("/foo"),
3330            file_name: Some("bar"),
3331            file_stem: Some("bar"),
3332            extension: None
3333            );
3334
3335         t!("///foo///",
3336            iter: ["\\", "foo"],
3337            has_root: true,
3338            is_absolute: false,
3339            parent: Some("/"),
3340            file_name: Some("foo"),
3341            file_stem: Some("foo"),
3342            extension: None
3343            );
3344
3345         t!("///foo///bar",
3346            iter: ["\\", "foo", "bar"],
3347            has_root: true,
3348            is_absolute: false,
3349            parent: Some("///foo"),
3350            file_name: Some("bar"),
3351            file_stem: Some("bar"),
3352            extension: None
3353            );
3354
3355         t!("./.",
3356            iter: ["."],
3357            has_root: false,
3358            is_absolute: false,
3359            parent: Some(""),
3360            file_name: None,
3361            file_stem: None,
3362            extension: None
3363            );
3364
3365         t!("/..",
3366            iter: ["\\", ".."],
3367            has_root: true,
3368            is_absolute: false,
3369            parent: Some("/"),
3370            file_name: None,
3371            file_stem: None,
3372            extension: None
3373            );
3374
3375         t!("../",
3376            iter: [".."],
3377            has_root: false,
3378            is_absolute: false,
3379            parent: Some(""),
3380            file_name: None,
3381            file_stem: None,
3382            extension: None
3383            );
3384
3385         t!("foo/.",
3386            iter: ["foo"],
3387            has_root: false,
3388            is_absolute: false,
3389            parent: Some(""),
3390            file_name: Some("foo"),
3391            file_stem: Some("foo"),
3392            extension: None
3393            );
3394
3395         t!("foo/..",
3396            iter: ["foo", ".."],
3397            has_root: false,
3398            is_absolute: false,
3399            parent: Some("foo"),
3400            file_name: None,
3401            file_stem: None,
3402            extension: None
3403            );
3404
3405         t!("foo/./",
3406            iter: ["foo"],
3407            has_root: false,
3408            is_absolute: false,
3409            parent: Some(""),
3410            file_name: Some("foo"),
3411            file_stem: Some("foo"),
3412            extension: None
3413            );
3414
3415         t!("foo/./bar",
3416            iter: ["foo", "bar"],
3417            has_root: false,
3418            is_absolute: false,
3419            parent: Some("foo"),
3420            file_name: Some("bar"),
3421            file_stem: Some("bar"),
3422            extension: None
3423            );
3424
3425         t!("foo/../",
3426            iter: ["foo", ".."],
3427            has_root: false,
3428            is_absolute: false,
3429            parent: Some("foo"),
3430            file_name: None,
3431            file_stem: None,
3432            extension: None
3433            );
3434
3435         t!("foo/../bar",
3436            iter: ["foo", "..", "bar"],
3437            has_root: false,
3438            is_absolute: false,
3439            parent: Some("foo/.."),
3440            file_name: Some("bar"),
3441            file_stem: Some("bar"),
3442            extension: None
3443            );
3444
3445         t!("./a",
3446            iter: [".", "a"],
3447            has_root: false,
3448            is_absolute: false,
3449            parent: Some("."),
3450            file_name: Some("a"),
3451            file_stem: Some("a"),
3452            extension: None
3453            );
3454
3455         t!(".",
3456            iter: ["."],
3457            has_root: false,
3458            is_absolute: false,
3459            parent: Some(""),
3460            file_name: None,
3461            file_stem: None,
3462            extension: None
3463            );
3464
3465         t!("./",
3466            iter: ["."],
3467            has_root: false,
3468            is_absolute: false,
3469            parent: Some(""),
3470            file_name: None,
3471            file_stem: None,
3472            extension: None
3473            );
3474
3475         t!("a/b",
3476            iter: ["a", "b"],
3477            has_root: false,
3478            is_absolute: false,
3479            parent: Some("a"),
3480            file_name: Some("b"),
3481            file_stem: Some("b"),
3482            extension: None
3483            );
3484
3485         t!("a//b",
3486            iter: ["a", "b"],
3487            has_root: false,
3488            is_absolute: false,
3489            parent: Some("a"),
3490            file_name: Some("b"),
3491            file_stem: Some("b"),
3492            extension: None
3493            );
3494
3495         t!("a/./b",
3496            iter: ["a", "b"],
3497            has_root: false,
3498            is_absolute: false,
3499            parent: Some("a"),
3500            file_name: Some("b"),
3501            file_stem: Some("b"),
3502            extension: None
3503            );
3504
3505         t!("a/b/c",
3506            iter: ["a", "b", "c"],
3507            has_root: false,
3508            is_absolute: false,
3509            parent: Some("a/b"),
3510            file_name: Some("c"),
3511            file_stem: Some("c"),
3512            extension: None);
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
3524         t!("\\a",
3525            iter: ["\\", "a"],
3526            has_root: true,
3527            is_absolute: false,
3528            parent: Some("\\"),
3529            file_name: Some("a"),
3530            file_stem: Some("a"),
3531            extension: None
3532            );
3533
3534         t!("c:\\foo.txt",
3535            iter: ["c:", "\\", "foo.txt"],
3536            has_root: true,
3537            is_absolute: true,
3538            parent: Some("c:\\"),
3539            file_name: Some("foo.txt"),
3540            file_stem: Some("foo"),
3541            extension: Some("txt")
3542            );
3543
3544         t!("\\\\server\\share\\foo.txt",
3545            iter: ["\\\\server\\share", "\\", "foo.txt"],
3546            has_root: true,
3547            is_absolute: true,
3548            parent: Some("\\\\server\\share\\"),
3549            file_name: Some("foo.txt"),
3550            file_stem: Some("foo"),
3551            extension: Some("txt")
3552            );
3553
3554         t!("\\\\server\\share",
3555            iter: ["\\\\server\\share", "\\"],
3556            has_root: true,
3557            is_absolute: true,
3558            parent: None,
3559            file_name: None,
3560            file_stem: None,
3561            extension: None
3562            );
3563
3564         t!("\\\\server",
3565            iter: ["\\", "server"],
3566            has_root: true,
3567            is_absolute: false,
3568            parent: Some("\\"),
3569            file_name: Some("server"),
3570            file_stem: Some("server"),
3571            extension: None
3572            );
3573
3574         t!("\\\\?\\bar\\foo.txt",
3575            iter: ["\\\\?\\bar", "\\", "foo.txt"],
3576            has_root: true,
3577            is_absolute: true,
3578            parent: Some("\\\\?\\bar\\"),
3579            file_name: Some("foo.txt"),
3580            file_stem: Some("foo"),
3581            extension: Some("txt")
3582            );
3583
3584         t!("\\\\?\\bar",
3585            iter: ["\\\\?\\bar"],
3586            has_root: true,
3587            is_absolute: true,
3588            parent: None,
3589            file_name: None,
3590            file_stem: None,
3591            extension: None
3592            );
3593
3594         t!("\\\\?\\",
3595            iter: ["\\\\?\\"],
3596            has_root: true,
3597            is_absolute: true,
3598            parent: None,
3599            file_name: None,
3600            file_stem: None,
3601            extension: None
3602            );
3603
3604         t!("\\\\?\\UNC\\server\\share\\foo.txt",
3605            iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3606            has_root: true,
3607            is_absolute: true,
3608            parent: Some("\\\\?\\UNC\\server\\share\\"),
3609            file_name: Some("foo.txt"),
3610            file_stem: Some("foo"),
3611            extension: Some("txt")
3612            );
3613
3614         t!("\\\\?\\UNC\\server",
3615            iter: ["\\\\?\\UNC\\server"],
3616            has_root: true,
3617            is_absolute: true,
3618            parent: None,
3619            file_name: None,
3620            file_stem: None,
3621            extension: None
3622            );
3623
3624         t!("\\\\?\\UNC\\",
3625            iter: ["\\\\?\\UNC\\"],
3626            has_root: true,
3627            is_absolute: true,
3628            parent: None,
3629            file_name: None,
3630            file_stem: None,
3631            extension: None
3632            );
3633
3634         t!("\\\\?\\C:\\foo.txt",
3635            iter: ["\\\\?\\C:", "\\", "foo.txt"],
3636            has_root: true,
3637            is_absolute: true,
3638            parent: Some("\\\\?\\C:\\"),
3639            file_name: Some("foo.txt"),
3640            file_stem: Some("foo"),
3641            extension: Some("txt")
3642            );
3643
3644
3645         t!("\\\\?\\C:\\",
3646            iter: ["\\\\?\\C:", "\\"],
3647            has_root: true,
3648            is_absolute: true,
3649            parent: None,
3650            file_name: None,
3651            file_stem: None,
3652            extension: None
3653            );
3654
3655
3656         t!("\\\\?\\C:",
3657            iter: ["\\\\?\\C:"],
3658            has_root: true,
3659            is_absolute: true,
3660            parent: None,
3661            file_name: None,
3662            file_stem: None,
3663            extension: None
3664            );
3665
3666
3667         t!("\\\\?\\foo/bar",
3668            iter: ["\\\\?\\foo/bar"],
3669            has_root: true,
3670            is_absolute: true,
3671            parent: None,
3672            file_name: None,
3673            file_stem: None,
3674            extension: None
3675            );
3676
3677
3678         t!("\\\\?\\C:/foo",
3679            iter: ["\\\\?\\C:/foo"],
3680            has_root: true,
3681            is_absolute: true,
3682            parent: None,
3683            file_name: None,
3684            file_stem: None,
3685            extension: None
3686            );
3687
3688
3689         t!("\\\\.\\foo\\bar",
3690            iter: ["\\\\.\\foo", "\\", "bar"],
3691            has_root: true,
3692            is_absolute: true,
3693            parent: Some("\\\\.\\foo\\"),
3694            file_name: Some("bar"),
3695            file_stem: Some("bar"),
3696            extension: None
3697            );
3698
3699
3700         t!("\\\\.\\foo",
3701            iter: ["\\\\.\\foo", "\\"],
3702            has_root: true,
3703            is_absolute: true,
3704            parent: None,
3705            file_name: None,
3706            file_stem: None,
3707            extension: None
3708            );
3709
3710
3711         t!("\\\\.\\foo/bar",
3712            iter: ["\\\\.\\foo/bar", "\\"],
3713            has_root: true,
3714            is_absolute: true,
3715            parent: None,
3716            file_name: None,
3717            file_stem: None,
3718            extension: None
3719            );
3720
3721
3722         t!("\\\\.\\foo\\bar/baz",
3723            iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3724            has_root: true,
3725            is_absolute: true,
3726            parent: Some("\\\\.\\foo\\bar"),
3727            file_name: Some("baz"),
3728            file_stem: Some("baz"),
3729            extension: None
3730            );
3731
3732
3733         t!("\\\\.\\",
3734            iter: ["\\\\.\\", "\\"],
3735            has_root: true,
3736            is_absolute: true,
3737            parent: None,
3738            file_name: None,
3739            file_stem: None,
3740            extension: None
3741            );
3742
3743         t!("\\\\?\\a\\b\\",
3744            iter: ["\\\\?\\a", "\\", "b"],
3745            has_root: true,
3746            is_absolute: true,
3747            parent: Some("\\\\?\\a\\"),
3748            file_name: Some("b"),
3749            file_stem: Some("b"),
3750            extension: None
3751            );
3752     }
3753
3754     #[test]
3755     pub fn test_stem_ext() {
3756         t!("foo",
3757            file_stem: Some("foo"),
3758            extension: None
3759            );
3760
3761         t!("foo.",
3762            file_stem: Some("foo"),
3763            extension: Some("")
3764            );
3765
3766         t!(".foo",
3767            file_stem: Some(".foo"),
3768            extension: None
3769            );
3770
3771         t!("foo.txt",
3772            file_stem: Some("foo"),
3773            extension: Some("txt")
3774            );
3775
3776         t!("foo.bar.txt",
3777            file_stem: Some("foo.bar"),
3778            extension: Some("txt")
3779            );
3780
3781         t!("foo.bar.",
3782            file_stem: Some("foo.bar"),
3783            extension: Some("")
3784            );
3785
3786         t!(".",
3787            file_stem: None,
3788            extension: None
3789            );
3790
3791         t!("..",
3792            file_stem: None,
3793            extension: None
3794            );
3795
3796         t!("",
3797            file_stem: None,
3798            extension: None
3799            );
3800     }
3801
3802     #[test]
3803     pub fn test_push() {
3804         macro_rules! tp(
3805             ($path:expr, $push:expr, $expected:expr) => ( {
3806                 let mut actual = PathBuf::from($path);
3807                 actual.push($push);
3808                 assert!(actual.to_str() == Some($expected),
3809                         "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3810                         $push, $path, $expected, actual.to_str().unwrap());
3811             });
3812         );
3813
3814         if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3815             tp!("", "foo", "foo");
3816             tp!("foo", "bar", "foo/bar");
3817             tp!("foo/", "bar", "foo/bar");
3818             tp!("foo//", "bar", "foo//bar");
3819             tp!("foo/.", "bar", "foo/./bar");
3820             tp!("foo./.", "bar", "foo././bar");
3821             tp!("foo", "", "foo/");
3822             tp!("foo", ".", "foo/.");
3823             tp!("foo", "..", "foo/..");
3824             tp!("foo", "/", "/");
3825             tp!("/foo/bar", "/", "/");
3826             tp!("/foo/bar", "/baz", "/baz");
3827             tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3828         } else {
3829             tp!("", "foo", "foo");
3830             tp!("foo", "bar", r"foo\bar");
3831             tp!("foo/", "bar", r"foo/bar");
3832             tp!(r"foo\", "bar", r"foo\bar");
3833             tp!("foo//", "bar", r"foo//bar");
3834             tp!(r"foo\\", "bar", r"foo\\bar");
3835             tp!("foo/.", "bar", r"foo/.\bar");
3836             tp!("foo./.", "bar", r"foo./.\bar");
3837             tp!(r"foo\.", "bar", r"foo\.\bar");
3838             tp!(r"foo.\.", "bar", r"foo.\.\bar");
3839             tp!("foo", "", "foo\\");
3840             tp!("foo", ".", r"foo\.");
3841             tp!("foo", "..", r"foo\..");
3842             tp!("foo", "/", "/");
3843             tp!("foo", r"\", r"\");
3844             tp!("/foo/bar", "/", "/");
3845             tp!(r"\foo\bar", r"\", r"\");
3846             tp!("/foo/bar", "/baz", "/baz");
3847             tp!("/foo/bar", r"\baz", r"\baz");
3848             tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3849             tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3850
3851             tp!("c:\\", "windows", "c:\\windows");
3852             tp!("c:", "windows", "c:windows");
3853
3854             tp!("a\\b\\c", "d", "a\\b\\c\\d");
3855             tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3856             tp!("a\\b", "c\\d", "a\\b\\c\\d");
3857             tp!("a\\b", "\\c\\d", "\\c\\d");
3858             tp!("a\\b", ".", "a\\b\\.");
3859             tp!("a\\b", "..\\c", "a\\b\\..\\c");
3860             tp!("a\\b", "C:a.txt", "C:a.txt");
3861             tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3862             tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3863             tp!("C:\\a\\b\\c", "C:d", "C:d");
3864             tp!("C:a\\b\\c", "C:d", "C:d");
3865             tp!("C:", r"a\b\c", r"C:a\b\c");
3866             tp!("C:", r"..\a", r"C:..\a");
3867             tp!("\\\\server\\share\\foo",
3868                 "bar",
3869                 "\\\\server\\share\\foo\\bar");
3870             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3871             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3872             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3873             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3874             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3875             tp!("\\\\?\\UNC\\server\\share\\foo",
3876                 "bar",
3877                 "\\\\?\\UNC\\server\\share\\foo\\bar");
3878             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3879             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3880
3881             // Note: modified from old path API
3882             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3883
3884             tp!("C:\\a",
3885                 "\\\\?\\UNC\\server\\share",
3886                 "\\\\?\\UNC\\server\\share");
3887             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3888             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3889             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3890             tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3891
3892             tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3893         }
3894     }
3895
3896     #[test]
3897     pub fn test_pop() {
3898         macro_rules! tp(
3899             ($path:expr, $expected:expr, $output:expr) => ( {
3900                 let mut actual = PathBuf::from($path);
3901                 let output = actual.pop();
3902                 assert!(actual.to_str() == Some($expected) && output == $output,
3903                         "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3904                         $path, $expected, $output,
3905                         actual.to_str().unwrap(), output);
3906             });
3907         );
3908
3909         tp!("", "", false);
3910         tp!("/", "/", false);
3911         tp!("foo", "", true);
3912         tp!(".", "", true);
3913         tp!("/foo", "/", true);
3914         tp!("/foo/bar", "/foo", true);
3915         tp!("foo/bar", "foo", true);
3916         tp!("foo/.", "", true);
3917         tp!("foo//bar", "foo", true);
3918
3919         if cfg!(windows) {
3920             tp!("a\\b\\c", "a\\b", true);
3921             tp!("\\a", "\\", true);
3922             tp!("\\", "\\", false);
3923
3924             tp!("C:\\a\\b", "C:\\a", true);
3925             tp!("C:\\a", "C:\\", true);
3926             tp!("C:\\", "C:\\", false);
3927             tp!("C:a\\b", "C:a", true);
3928             tp!("C:a", "C:", true);
3929             tp!("C:", "C:", false);
3930             tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3931             tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3932             tp!("\\\\server\\share", "\\\\server\\share", false);
3933             tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3934             tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3935             tp!("\\\\?\\a", "\\\\?\\a", false);
3936             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3937             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3938             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3939             tp!("\\\\?\\UNC\\server\\share\\a\\b",
3940                 "\\\\?\\UNC\\server\\share\\a",
3941                 true);
3942             tp!("\\\\?\\UNC\\server\\share\\a",
3943                 "\\\\?\\UNC\\server\\share\\",
3944                 true);
3945             tp!("\\\\?\\UNC\\server\\share",
3946                 "\\\\?\\UNC\\server\\share",
3947                 false);
3948             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3949             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3950             tp!("\\\\.\\a", "\\\\.\\a", false);
3951
3952             tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3953         }
3954     }
3955
3956     #[test]
3957     pub fn test_set_file_name() {
3958         macro_rules! tfn(
3959                 ($path:expr, $file:expr, $expected:expr) => ( {
3960                 let mut p = PathBuf::from($path);
3961                 p.set_file_name($file);
3962                 assert!(p.to_str() == Some($expected),
3963                         "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3964                         $path, $file, $expected,
3965                         p.to_str().unwrap());
3966             });
3967         );
3968
3969         tfn!("foo", "foo", "foo");
3970         tfn!("foo", "bar", "bar");
3971         tfn!("foo", "", "");
3972         tfn!("", "foo", "foo");
3973         if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3974             tfn!(".", "foo", "./foo");
3975             tfn!("foo/", "bar", "bar");
3976             tfn!("foo/.", "bar", "bar");
3977             tfn!("..", "foo", "../foo");
3978             tfn!("foo/..", "bar", "foo/../bar");
3979             tfn!("/", "foo", "/foo");
3980         } else {
3981             tfn!(".", "foo", r".\foo");
3982             tfn!(r"foo\", "bar", r"bar");
3983             tfn!(r"foo\.", "bar", r"bar");
3984             tfn!("..", "foo", r"..\foo");
3985             tfn!(r"foo\..", "bar", r"foo\..\bar");
3986             tfn!(r"\", "foo", r"\foo");
3987         }
3988     }
3989
3990     #[test]
3991     pub fn test_set_extension() {
3992         macro_rules! tfe(
3993                 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3994                 let mut p = PathBuf::from($path);
3995                 let output = p.set_extension($ext);
3996                 assert!(p.to_str() == Some($expected) && output == $output,
3997                         "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3998                         $path, $ext, $expected, $output,
3999                         p.to_str().unwrap(), output);
4000             });
4001         );
4002
4003         tfe!("foo", "txt", "foo.txt", true);
4004         tfe!("foo.bar", "txt", "foo.txt", true);
4005         tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
4006         tfe!(".test", "txt", ".test.txt", true);
4007         tfe!("foo.txt", "", "foo", true);
4008         tfe!("foo", "", "foo", true);
4009         tfe!("", "foo", "", false);
4010         tfe!(".", "foo", ".", false);
4011         tfe!("foo/", "bar", "foo.bar", true);
4012         tfe!("foo/.", "bar", "foo.bar", true);
4013         tfe!("..", "foo", "..", false);
4014         tfe!("foo/..", "bar", "foo/..", false);
4015         tfe!("/", "foo", "/", false);
4016     }
4017
4018     #[test]
4019     fn test_eq_receivers() {
4020         use crate::borrow::Cow;
4021
4022         let borrowed: &Path = Path::new("foo/bar");
4023         let mut owned: PathBuf = PathBuf::new();
4024         owned.push("foo");
4025         owned.push("bar");
4026         let borrowed_cow: Cow<'_, Path> = borrowed.into();
4027         let owned_cow: Cow<'_, Path> = owned.clone().into();
4028
4029         macro_rules! t {
4030             ($($current:expr),+) => {
4031                 $(
4032                     assert_eq!($current, borrowed);
4033                     assert_eq!($current, owned);
4034                     assert_eq!($current, borrowed_cow);
4035                     assert_eq!($current, owned_cow);
4036                 )+
4037             }
4038         }
4039
4040         t!(borrowed, owned, borrowed_cow, owned_cow);
4041     }
4042
4043     #[test]
4044     pub fn test_compare() {
4045         use crate::hash::{Hash, Hasher};
4046         use crate::collections::hash_map::DefaultHasher;
4047
4048         fn hash<T: Hash>(t: T) -> u64 {
4049             let mut s = DefaultHasher::new();
4050             t.hash(&mut s);
4051             s.finish()
4052         }
4053
4054         macro_rules! tc(
4055             ($path1:expr, $path2:expr, eq: $eq:expr,
4056              starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4057              relative_from: $relative_from:expr) => ({
4058                  let path1 = Path::new($path1);
4059                  let path2 = Path::new($path2);
4060
4061                  let eq = path1 == path2;
4062                  assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4063                          $path1, $path2, $eq, eq);
4064                  assert!($eq == (hash(path1) == hash(path2)),
4065                          "{:?} == {:?}, expected {:?}, got {} and {}",
4066                          $path1, $path2, $eq, hash(path1), hash(path2));
4067
4068                  let starts_with = path1.starts_with(path2);
4069                  assert!(starts_with == $starts_with,
4070                          "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4071                          $starts_with, starts_with);
4072
4073                  let ends_with = path1.ends_with(path2);
4074                  assert!(ends_with == $ends_with,
4075                          "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4076                          $ends_with, ends_with);
4077
4078                  let relative_from = path1.strip_prefix(path2)
4079                                           .map(|p| p.to_str().unwrap())
4080                                           .ok();
4081                  let exp: Option<&str> = $relative_from;
4082                  assert!(relative_from == exp,
4083                          "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4084                          $path1, $path2, exp, relative_from);
4085             });
4086         );
4087
4088         tc!("", "",
4089             eq: true,
4090             starts_with: true,
4091             ends_with: true,
4092             relative_from: Some("")
4093             );
4094
4095         tc!("foo", "",
4096             eq: false,
4097             starts_with: true,
4098             ends_with: true,
4099             relative_from: Some("foo")
4100             );
4101
4102         tc!("", "foo",
4103             eq: false,
4104             starts_with: false,
4105             ends_with: false,
4106             relative_from: None
4107             );
4108
4109         tc!("foo", "foo",
4110             eq: true,
4111             starts_with: true,
4112             ends_with: true,
4113             relative_from: Some("")
4114             );
4115
4116         tc!("foo/", "foo",
4117             eq: true,
4118             starts_with: true,
4119             ends_with: true,
4120             relative_from: Some("")
4121             );
4122
4123         tc!("foo/bar", "foo",
4124             eq: false,
4125             starts_with: true,
4126             ends_with: false,
4127             relative_from: Some("bar")
4128             );
4129
4130         tc!("foo/bar/baz", "foo/bar",
4131             eq: false,
4132             starts_with: true,
4133             ends_with: false,
4134             relative_from: Some("baz")
4135             );
4136
4137         tc!("foo/bar", "foo/bar/baz",
4138             eq: false,
4139             starts_with: false,
4140             ends_with: false,
4141             relative_from: None
4142             );
4143
4144         tc!("./foo/bar/", ".",
4145             eq: false,
4146             starts_with: true,
4147             ends_with: false,
4148             relative_from: Some("foo/bar")
4149             );
4150
4151         if cfg!(windows) {
4152             tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4153                 r"c:\src\rust\cargo-test\test",
4154                 eq: false,
4155                 starts_with: true,
4156                 ends_with: false,
4157                 relative_from: Some("Cargo.toml")
4158                 );
4159
4160             tc!(r"c:\foo", r"C:\foo",
4161                 eq: true,
4162                 starts_with: true,
4163                 ends_with: true,
4164                 relative_from: Some("")
4165                 );
4166         }
4167     }
4168
4169     #[test]
4170     fn test_components_debug() {
4171         let path = Path::new("/tmp");
4172
4173         let mut components = path.components();
4174
4175         let expected = "Components([RootDir, Normal(\"tmp\")])";
4176         let actual = format!("{:?}", components);
4177         assert_eq!(expected, actual);
4178
4179         let _ = components.next().unwrap();
4180         let expected = "Components([Normal(\"tmp\")])";
4181         let actual = format!("{:?}", components);
4182         assert_eq!(expected, actual);
4183
4184         let _ = components.next().unwrap();
4185         let expected = "Components([])";
4186         let actual = format!("{:?}", components);
4187         assert_eq!(expected, actual);
4188     }
4189
4190     #[cfg(unix)]
4191     #[test]
4192     fn test_iter_debug() {
4193         let path = Path::new("/tmp");
4194
4195         let mut iter = path.iter();
4196
4197         let expected = "Iter([\"/\", \"tmp\"])";
4198         let actual = format!("{:?}", iter);
4199         assert_eq!(expected, actual);
4200
4201         let _ = iter.next().unwrap();
4202         let expected = "Iter([\"tmp\"])";
4203         let actual = format!("{:?}", iter);
4204         assert_eq!(expected, actual);
4205
4206         let _ = iter.next().unwrap();
4207         let expected = "Iter([])";
4208         let actual = format!("{:?}", iter);
4209         assert_eq!(expected, actual);
4210     }
4211
4212     #[test]
4213     fn into_boxed() {
4214         let orig: &str = "some/sort/of/path";
4215         let path = Path::new(orig);
4216         let boxed: Box<Path> = Box::from(path);
4217         let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4218         assert_eq!(path, &*boxed);
4219         assert_eq!(&*boxed, &*path_buf);
4220         assert_eq!(&*path_buf, path);
4221     }
4222
4223     #[test]
4224     fn test_clone_into() {
4225         let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4226         let path = Path::new("short");
4227         path.clone_into(&mut path_buf);
4228         assert_eq!(path, path_buf);
4229         assert!(path_buf.into_os_string().capacity() >= 15);
4230     }
4231
4232     #[test]
4233     fn display_format_flags() {
4234         assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4235         assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4236     }
4237
4238     #[test]
4239     fn into_rc() {
4240         let orig = "hello/world";
4241         let path = Path::new(orig);
4242         let rc: Rc<Path> = Rc::from(path);
4243         let arc: Arc<Path> = Arc::from(path);
4244
4245         assert_eq!(&*rc, path);
4246         assert_eq!(&*arc, path);
4247
4248         let rc2: Rc<Path> = Rc::from(path.to_owned());
4249         let arc2: Arc<Path> = Arc::from(path.to_owned());
4250
4251         assert_eq!(&*rc2, path);
4252         assert_eq!(&*arc2, path);
4253     }
4254 }