]> git.lizzy.rs Git - rust.git/blob - library/std/src/path.rs
Auto merge of #79115 - cuviper:rust-description, r=Mark-Simulacrum
[rust.git] / library / std / src / path.rs
1 //! Cross-platform path manipulation.
2 //!
3 //! This module provides two types, [`PathBuf`] and [`Path`] (akin to [`String`]
4 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
5 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
6 //! on strings according to the local platform's path syntax.
7 //!
8 //! Paths can be parsed into [`Component`]s by iterating over the structure
9 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
10 //! correspond to the substrings between path separators (`/` or `\`). You can
11 //! reconstruct an equivalent path from components with the [`push`] method on
12 //! [`PathBuf`]; note that the paths may differ syntactically by the
13 //! normalization described in the documentation for the [`components`] method.
14 //!
15 //! ## Simple usage
16 //!
17 //! Path manipulation includes both parsing components from slices and building
18 //! new owned paths.
19 //!
20 //! To parse a path, you can create a [`Path`] slice from a [`str`]
21 //! slice and start asking questions:
22 //!
23 //! ```
24 //! use std::path::Path;
25 //! use std::ffi::OsStr;
26 //!
27 //! let path = Path::new("/tmp/foo/bar.txt");
28 //!
29 //! let parent = path.parent();
30 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
31 //!
32 //! let file_stem = path.file_stem();
33 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
34 //!
35 //! let extension = path.extension();
36 //! assert_eq!(extension, Some(OsStr::new("txt")));
37 //! ```
38 //!
39 //! To build or modify paths, use [`PathBuf`]:
40 //!
41 //! ```
42 //! use std::path::PathBuf;
43 //!
44 //! // This way works...
45 //! let mut path = PathBuf::from("c:\\");
46 //!
47 //! path.push("windows");
48 //! path.push("system32");
49 //!
50 //! path.set_extension("dll");
51 //!
52 //! // ... but push is best used if you don't know everything up
53 //! // front. If you do, this way is better:
54 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
55 //! ```
56 //!
57 //! [`components`]: Path::components
58 //! [`push`]: PathBuf::push
59
60 #![stable(feature = "rust1", since = "1.0.0")]
61 #![deny(unsafe_op_in_unsafe_fn)]
62
63 #[cfg(test)]
64 mod tests;
65
66 use crate::borrow::{Borrow, Cow};
67 use crate::cmp;
68 use crate::error::Error;
69 use crate::fmt;
70 use crate::fs;
71 use crate::hash::{Hash, Hasher};
72 use crate::io;
73 use crate::iter::{self, FusedIterator};
74 use crate::ops::{self, Deref};
75 use crate::rc::Rc;
76 use crate::str::FromStr;
77 use crate::sync::Arc;
78
79 use crate::ffi::{OsStr, OsString};
80
81 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
82
83 ////////////////////////////////////////////////////////////////////////////////
84 // GENERAL NOTES
85 ////////////////////////////////////////////////////////////////////////////////
86 //
87 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
88 // taking advantage of the fact that OsStr always encodes ASCII characters
89 // as-is.  Eventually, this transmutation should be replaced by direct uses of
90 // OsStr APIs for parsing, but it will take a while for those to become
91 // available.
92
93 ////////////////////////////////////////////////////////////////////////////////
94 // Windows Prefixes
95 ////////////////////////////////////////////////////////////////////////////////
96
97 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
98 ///
99 /// Windows uses a variety of path prefix styles, including references to drive
100 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
101 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
102 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
103 /// no normalization is performed.
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// use std::path::{Component, Path, Prefix};
109 /// use std::path::Prefix::*;
110 /// use std::ffi::OsStr;
111 ///
112 /// fn get_path_prefix(s: &str) -> Prefix {
113 ///     let path = Path::new(s);
114 ///     match path.components().next().unwrap() {
115 ///         Component::Prefix(prefix_component) => prefix_component.kind(),
116 ///         _ => panic!(),
117 ///     }
118 /// }
119 ///
120 /// # if cfg!(windows) {
121 /// assert_eq!(Verbatim(OsStr::new("pictures")),
122 ///            get_path_prefix(r"\\?\pictures\kittens"));
123 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
124 ///            get_path_prefix(r"\\?\UNC\server\share"));
125 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
126 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
127 ///            get_path_prefix(r"\\.\BrainInterface"));
128 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
129 ///            get_path_prefix(r"\\server\share"));
130 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
131 /// # }
132 /// ```
133 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub enum Prefix<'a> {
136     /// Verbatim prefix, e.g., `\\?\cat_pics`.
137     ///
138     /// Verbatim prefixes consist of `\\?\` immediately followed by the given
139     /// component.
140     #[stable(feature = "rust1", since = "1.0.0")]
141     Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
142
143     /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
144     /// e.g., `\\?\UNC\server\share`.
145     ///
146     /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
147     /// server's hostname and a share name.
148     #[stable(feature = "rust1", since = "1.0.0")]
149     VerbatimUNC(
150         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
151         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
152     ),
153
154     /// Verbatim disk prefix, e.g., `\\?\C:`.
155     ///
156     /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
157     /// drive letter and `:`.
158     #[stable(feature = "rust1", since = "1.0.0")]
159     VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
160
161     /// Device namespace prefix, e.g., `\\.\COM42`.
162     ///
163     /// Device namespace prefixes consist of `\\.\` immediately followed by the
164     /// device name.
165     #[stable(feature = "rust1", since = "1.0.0")]
166     DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
167
168     /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
169     /// `\\server\share`.
170     ///
171     /// UNC prefixes consist of the server's hostname and a share name.
172     #[stable(feature = "rust1", since = "1.0.0")]
173     UNC(
174         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
175         #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
176     ),
177
178     /// Prefix `C:` for the given disk drive.
179     #[stable(feature = "rust1", since = "1.0.0")]
180     Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
181 }
182
183 impl<'a> Prefix<'a> {
184     #[inline]
185     fn len(&self) -> usize {
186         use self::Prefix::*;
187         fn os_str_len(s: &OsStr) -> usize {
188             os_str_as_u8_slice(s).len()
189         }
190         match *self {
191             Verbatim(x) => 4 + os_str_len(x),
192             VerbatimUNC(x, y) => {
193                 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
194             }
195             VerbatimDisk(_) => 6,
196             UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
197             DeviceNS(x) => 4 + os_str_len(x),
198             Disk(_) => 2,
199         }
200     }
201
202     /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
203     ///
204     /// # Examples
205     ///
206     /// ```
207     /// use std::path::Prefix::*;
208     /// use std::ffi::OsStr;
209     ///
210     /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
211     /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
212     /// assert!(VerbatimDisk(b'C').is_verbatim());
213     /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
214     /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
215     /// assert!(!Disk(b'C').is_verbatim());
216     /// ```
217     #[inline]
218     #[stable(feature = "rust1", since = "1.0.0")]
219     pub fn is_verbatim(&self) -> bool {
220         use self::Prefix::*;
221         matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
222     }
223
224     #[inline]
225     fn is_drive(&self) -> bool {
226         matches!(*self, Prefix::Disk(_))
227     }
228
229     #[inline]
230     fn has_implicit_root(&self) -> bool {
231         !self.is_drive()
232     }
233 }
234
235 ////////////////////////////////////////////////////////////////////////////////
236 // Exposed parsing helpers
237 ////////////////////////////////////////////////////////////////////////////////
238
239 /// Determines whether the character is one of the permitted path
240 /// separators for the current platform.
241 ///
242 /// # Examples
243 ///
244 /// ```
245 /// use std::path;
246 ///
247 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
248 /// assert!(!path::is_separator('❤'));
249 /// ```
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn is_separator(c: char) -> bool {
252     c.is_ascii() && is_sep_byte(c as u8)
253 }
254
255 /// The primary separator of path components for the current platform.
256 ///
257 /// For example, `/` on Unix and `\` on Windows.
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
260
261 ////////////////////////////////////////////////////////////////////////////////
262 // Misc helpers
263 ////////////////////////////////////////////////////////////////////////////////
264
265 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
266 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
267 // `iter` after having exhausted `prefix`.
268 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
269 where
270     I: Iterator<Item = Component<'a>> + Clone,
271     J: Iterator<Item = Component<'b>>,
272 {
273     loop {
274         let mut iter_next = iter.clone();
275         match (iter_next.next(), prefix.next()) {
276             (Some(ref x), Some(ref y)) if x == y => (),
277             (Some(_), Some(_)) => return None,
278             (Some(_), None) => return Some(iter),
279             (None, None) => return Some(iter),
280             (None, Some(_)) => return None,
281         }
282         iter = iter_next;
283     }
284 }
285
286 // See note at the top of this module to understand why these are used:
287 //
288 // These casts are safe as OsStr is internally a wrapper around [u8] on all
289 // platforms.
290 //
291 // Note that currently this relies on the special knowledge that libstd has;
292 // these types are single-element structs but are not marked repr(transparent)
293 // or repr(C) which would make these casts allowable outside std.
294 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
295     unsafe { &*(s as *const OsStr as *const [u8]) }
296 }
297 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
298     // SAFETY: see the comment of `os_str_as_u8_slice`
299     unsafe { &*(s as *const [u8] as *const OsStr) }
300 }
301
302 // Detect scheme on Redox
303 fn has_redox_scheme(s: &[u8]) -> bool {
304     cfg!(target_os = "redox") && s.contains(&b':')
305 }
306
307 ////////////////////////////////////////////////////////////////////////////////
308 // Cross-platform, iterator-independent parsing
309 ////////////////////////////////////////////////////////////////////////////////
310
311 /// Says whether the first byte after the prefix is a separator.
312 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
313     let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
314     !path.is_empty() && is_sep_byte(path[0])
315 }
316
317 // basic workhorse for splitting stem and extension
318 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
319     if os_str_as_u8_slice(file) == b".." {
320         return (Some(file), None);
321     }
322
323     // The unsafety here stems from converting between &OsStr and &[u8]
324     // and back. This is safe to do because (1) we only look at ASCII
325     // contents of the encoding and (2) new &OsStr values are produced
326     // only from ASCII-bounded slices of existing &OsStr values.
327     let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
328     let after = iter.next();
329     let before = iter.next();
330     if before == Some(b"") {
331         (Some(file), None)
332     } else {
333         unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
334     }
335 }
336
337 ////////////////////////////////////////////////////////////////////////////////
338 // The core iterators
339 ////////////////////////////////////////////////////////////////////////////////
340
341 /// Component parsing works by a double-ended state machine; the cursors at the
342 /// front and back of the path each keep track of what parts of the path have
343 /// been consumed so far.
344 ///
345 /// Going front to back, a path is made up of a prefix, a starting
346 /// directory component, and a body (of normal components)
347 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
348 enum State {
349     Prefix = 0,   // c:
350     StartDir = 1, // / or . or nothing
351     Body = 2,     // foo/bar/baz
352     Done = 3,
353 }
354
355 /// A structure wrapping a Windows path prefix as well as its unparsed string
356 /// representation.
357 ///
358 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
359 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
360 /// returned by [`as_os_str`].
361 ///
362 /// Instances of this `struct` can be obtained by matching against the
363 /// [`Prefix` variant] on [`Component`].
364 ///
365 /// Does not occur on Unix.
366 ///
367 /// # Examples
368 ///
369 /// ```
370 /// # if cfg!(windows) {
371 /// use std::path::{Component, Path, Prefix};
372 /// use std::ffi::OsStr;
373 ///
374 /// let path = Path::new(r"c:\you\later\");
375 /// match path.components().next().unwrap() {
376 ///     Component::Prefix(prefix_component) => {
377 ///         assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
378 ///         assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
379 ///     }
380 ///     _ => unreachable!(),
381 /// }
382 /// # }
383 /// ```
384 ///
385 /// [`as_os_str`]: PrefixComponent::as_os_str
386 /// [`kind`]: PrefixComponent::kind
387 /// [`Prefix` variant]: Component::Prefix
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[derive(Copy, Clone, Eq, Debug)]
390 pub struct PrefixComponent<'a> {
391     /// The prefix as an unparsed `OsStr` slice.
392     raw: &'a OsStr,
393
394     /// The parsed prefix data.
395     parsed: Prefix<'a>,
396 }
397
398 impl<'a> PrefixComponent<'a> {
399     /// Returns the parsed prefix data.
400     ///
401     /// See [`Prefix`]'s documentation for more information on the different
402     /// kinds of prefixes.
403     #[stable(feature = "rust1", since = "1.0.0")]
404     pub fn kind(&self) -> Prefix<'a> {
405         self.parsed
406     }
407
408     /// Returns the raw [`OsStr`] slice for this prefix.
409     #[stable(feature = "rust1", since = "1.0.0")]
410     pub fn as_os_str(&self) -> &'a OsStr {
411         self.raw
412     }
413 }
414
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
417     fn eq(&self, other: &PrefixComponent<'a>) -> bool {
418         cmp::PartialEq::eq(&self.parsed, &other.parsed)
419     }
420 }
421
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
424     fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
425         cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
426     }
427 }
428
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl cmp::Ord for PrefixComponent<'_> {
431     fn cmp(&self, other: &Self) -> cmp::Ordering {
432         cmp::Ord::cmp(&self.parsed, &other.parsed)
433     }
434 }
435
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl Hash for PrefixComponent<'_> {
438     fn hash<H: Hasher>(&self, h: &mut H) {
439         self.parsed.hash(h);
440     }
441 }
442
443 /// A single component of a path.
444 ///
445 /// A `Component` roughly corresponds to a substring between path separators
446 /// (`/` or `\`).
447 ///
448 /// This `enum` is created by iterating over [`Components`], which in turn is
449 /// created by the [`components`](Path::components) method on [`Path`].
450 ///
451 /// # Examples
452 ///
453 /// ```rust
454 /// use std::path::{Component, Path};
455 ///
456 /// let path = Path::new("/tmp/foo/bar.txt");
457 /// let components = path.components().collect::<Vec<_>>();
458 /// assert_eq!(&components, &[
459 ///     Component::RootDir,
460 ///     Component::Normal("tmp".as_ref()),
461 ///     Component::Normal("foo".as_ref()),
462 ///     Component::Normal("bar.txt".as_ref()),
463 /// ]);
464 /// ```
465 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub enum Component<'a> {
468     /// A Windows path prefix, e.g., `C:` or `\\server\share`.
469     ///
470     /// There is a large variety of prefix types, see [`Prefix`]'s documentation
471     /// for more.
472     ///
473     /// Does not occur on Unix.
474     #[stable(feature = "rust1", since = "1.0.0")]
475     Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
476
477     /// The root directory component, appears after any prefix and before anything else.
478     ///
479     /// It represents a separator that designates that a path starts from root.
480     #[stable(feature = "rust1", since = "1.0.0")]
481     RootDir,
482
483     /// A reference to the current directory, i.e., `.`.
484     #[stable(feature = "rust1", since = "1.0.0")]
485     CurDir,
486
487     /// A reference to the parent directory, i.e., `..`.
488     #[stable(feature = "rust1", since = "1.0.0")]
489     ParentDir,
490
491     /// A normal component, e.g., `a` and `b` in `a/b`.
492     ///
493     /// This variant is the most common one, it represents references to files
494     /// or directories.
495     #[stable(feature = "rust1", since = "1.0.0")]
496     Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
497 }
498
499 impl<'a> Component<'a> {
500     /// Extracts the underlying [`OsStr`] slice.
501     ///
502     /// # Examples
503     ///
504     /// ```
505     /// use std::path::Path;
506     ///
507     /// let path = Path::new("./tmp/foo/bar.txt");
508     /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
509     /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
510     /// ```
511     #[stable(feature = "rust1", since = "1.0.0")]
512     pub fn as_os_str(self) -> &'a OsStr {
513         match self {
514             Component::Prefix(p) => p.as_os_str(),
515             Component::RootDir => OsStr::new(MAIN_SEP_STR),
516             Component::CurDir => OsStr::new("."),
517             Component::ParentDir => OsStr::new(".."),
518             Component::Normal(path) => path,
519         }
520     }
521 }
522
523 #[stable(feature = "rust1", since = "1.0.0")]
524 impl AsRef<OsStr> for Component<'_> {
525     fn as_ref(&self) -> &OsStr {
526         self.as_os_str()
527     }
528 }
529
530 #[stable(feature = "path_component_asref", since = "1.25.0")]
531 impl AsRef<Path> for Component<'_> {
532     fn as_ref(&self) -> &Path {
533         self.as_os_str().as_ref()
534     }
535 }
536
537 /// An iterator over the [`Component`]s of a [`Path`].
538 ///
539 /// This `struct` is created by the [`components`] method on [`Path`].
540 /// See its documentation for more.
541 ///
542 /// # Examples
543 ///
544 /// ```
545 /// use std::path::Path;
546 ///
547 /// let path = Path::new("/tmp/foo/bar.txt");
548 ///
549 /// for component in path.components() {
550 ///     println!("{:?}", component);
551 /// }
552 /// ```
553 ///
554 /// [`components`]: Path::components
555 #[derive(Clone)]
556 #[stable(feature = "rust1", since = "1.0.0")]
557 pub struct Components<'a> {
558     // The path left to parse components from
559     path: &'a [u8],
560
561     // The prefix as it was originally parsed, if any
562     prefix: Option<Prefix<'a>>,
563
564     // true if path *physically* has a root separator; for most Windows
565     // prefixes, it may have a "logical" rootseparator for the purposes of
566     // normalization, e.g.,  \\server\share == \\server\share\.
567     has_physical_root: bool,
568
569     // The iterator is double-ended, and these two states keep track of what has
570     // been produced from either end
571     front: State,
572     back: State,
573 }
574
575 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
576 ///
577 /// This `struct` is created by the [`iter`] method on [`Path`].
578 /// See its documentation for more.
579 ///
580 /// [`iter`]: Path::iter
581 #[derive(Clone)]
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub struct Iter<'a> {
584     inner: Components<'a>,
585 }
586
587 #[stable(feature = "path_components_debug", since = "1.13.0")]
588 impl fmt::Debug for Components<'_> {
589     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590         struct DebugHelper<'a>(&'a Path);
591
592         impl fmt::Debug for DebugHelper<'_> {
593             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594                 f.debug_list().entries(self.0.components()).finish()
595             }
596         }
597
598         f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
599     }
600 }
601
602 impl<'a> Components<'a> {
603     // how long is the prefix, if any?
604     #[inline]
605     fn prefix_len(&self) -> usize {
606         self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
607     }
608
609     #[inline]
610     fn prefix_verbatim(&self) -> bool {
611         self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
612     }
613
614     /// how much of the prefix is left from the point of view of iteration?
615     #[inline]
616     fn prefix_remaining(&self) -> usize {
617         if self.front == State::Prefix { self.prefix_len() } else { 0 }
618     }
619
620     // Given the iteration so far, how much of the pre-State::Body path is left?
621     #[inline]
622     fn len_before_body(&self) -> usize {
623         let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
624         let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
625         self.prefix_remaining() + root + cur_dir
626     }
627
628     // is the iteration complete?
629     #[inline]
630     fn finished(&self) -> bool {
631         self.front == State::Done || self.back == State::Done || self.front > self.back
632     }
633
634     #[inline]
635     fn is_sep_byte(&self, b: u8) -> bool {
636         if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
637     }
638
639     /// Extracts a slice corresponding to the portion of the path remaining for iteration.
640     ///
641     /// # Examples
642     ///
643     /// ```
644     /// use std::path::Path;
645     ///
646     /// let mut components = Path::new("/tmp/foo/bar.txt").components();
647     /// components.next();
648     /// components.next();
649     ///
650     /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
651     /// ```
652     #[stable(feature = "rust1", since = "1.0.0")]
653     pub fn as_path(&self) -> &'a Path {
654         let mut comps = self.clone();
655         if comps.front == State::Body {
656             comps.trim_left();
657         }
658         if comps.back == State::Body {
659             comps.trim_right();
660         }
661         unsafe { Path::from_u8_slice(comps.path) }
662     }
663
664     /// Is the *original* path rooted?
665     fn has_root(&self) -> bool {
666         if self.has_physical_root {
667             return true;
668         }
669         if let Some(p) = self.prefix {
670             if p.has_implicit_root() {
671                 return true;
672             }
673         }
674         false
675     }
676
677     /// Should the normalized path include a leading . ?
678     fn include_cur_dir(&self) -> bool {
679         if self.has_root() {
680             return false;
681         }
682         let mut iter = self.path[self.prefix_len()..].iter();
683         match (iter.next(), iter.next()) {
684             (Some(&b'.'), None) => true,
685             (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
686             _ => false,
687         }
688     }
689
690     // parse a given byte sequence into the corresponding path component
691     fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
692         match comp {
693             b"." if self.prefix_verbatim() => Some(Component::CurDir),
694             b"." => None, // . components are normalized away, except at
695             // the beginning of a path, which is treated
696             // separately via `include_cur_dir`
697             b".." => Some(Component::ParentDir),
698             b"" => None,
699             _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
700         }
701     }
702
703     // parse a component from the left, saying how many bytes to consume to
704     // remove the component
705     fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
706         debug_assert!(self.front == State::Body);
707         let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
708             None => (0, self.path),
709             Some(i) => (1, &self.path[..i]),
710         };
711         (comp.len() + extra, self.parse_single_component(comp))
712     }
713
714     // parse a component from the right, saying how many bytes to consume to
715     // remove the component
716     fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
717         debug_assert!(self.back == State::Body);
718         let start = self.len_before_body();
719         let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
720             None => (0, &self.path[start..]),
721             Some(i) => (1, &self.path[start + i + 1..]),
722         };
723         (comp.len() + extra, self.parse_single_component(comp))
724     }
725
726     // trim away repeated separators (i.e., empty components) on the left
727     fn trim_left(&mut self) {
728         while !self.path.is_empty() {
729             let (size, comp) = self.parse_next_component();
730             if comp.is_some() {
731                 return;
732             } else {
733                 self.path = &self.path[size..];
734             }
735         }
736     }
737
738     // trim away repeated separators (i.e., empty components) on the right
739     fn trim_right(&mut self) {
740         while self.path.len() > self.len_before_body() {
741             let (size, comp) = self.parse_next_component_back();
742             if comp.is_some() {
743                 return;
744             } else {
745                 self.path = &self.path[..self.path.len() - size];
746             }
747         }
748     }
749 }
750
751 #[stable(feature = "rust1", since = "1.0.0")]
752 impl AsRef<Path> for Components<'_> {
753     fn as_ref(&self) -> &Path {
754         self.as_path()
755     }
756 }
757
758 #[stable(feature = "rust1", since = "1.0.0")]
759 impl AsRef<OsStr> for Components<'_> {
760     fn as_ref(&self) -> &OsStr {
761         self.as_path().as_os_str()
762     }
763 }
764
765 #[stable(feature = "path_iter_debug", since = "1.13.0")]
766 impl fmt::Debug for Iter<'_> {
767     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
768         struct DebugHelper<'a>(&'a Path);
769
770         impl fmt::Debug for DebugHelper<'_> {
771             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772                 f.debug_list().entries(self.0.iter()).finish()
773             }
774         }
775
776         f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
777     }
778 }
779
780 impl<'a> Iter<'a> {
781     /// Extracts a slice corresponding to the portion of the path remaining for iteration.
782     ///
783     /// # Examples
784     ///
785     /// ```
786     /// use std::path::Path;
787     ///
788     /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
789     /// iter.next();
790     /// iter.next();
791     ///
792     /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
793     /// ```
794     #[stable(feature = "rust1", since = "1.0.0")]
795     pub fn as_path(&self) -> &'a Path {
796         self.inner.as_path()
797     }
798 }
799
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl AsRef<Path> for Iter<'_> {
802     fn as_ref(&self) -> &Path {
803         self.as_path()
804     }
805 }
806
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl AsRef<OsStr> for Iter<'_> {
809     fn as_ref(&self) -> &OsStr {
810         self.as_path().as_os_str()
811     }
812 }
813
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a> Iterator for Iter<'a> {
816     type Item = &'a OsStr;
817
818     fn next(&mut self) -> Option<&'a OsStr> {
819         self.inner.next().map(Component::as_os_str)
820     }
821 }
822
823 #[stable(feature = "rust1", since = "1.0.0")]
824 impl<'a> DoubleEndedIterator for Iter<'a> {
825     fn next_back(&mut self) -> Option<&'a OsStr> {
826         self.inner.next_back().map(Component::as_os_str)
827     }
828 }
829
830 #[stable(feature = "fused", since = "1.26.0")]
831 impl FusedIterator for Iter<'_> {}
832
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<'a> Iterator for Components<'a> {
835     type Item = Component<'a>;
836
837     fn next(&mut self) -> Option<Component<'a>> {
838         while !self.finished() {
839             match self.front {
840                 State::Prefix if self.prefix_len() > 0 => {
841                     self.front = State::StartDir;
842                     debug_assert!(self.prefix_len() <= self.path.len());
843                     let raw = &self.path[..self.prefix_len()];
844                     self.path = &self.path[self.prefix_len()..];
845                     return Some(Component::Prefix(PrefixComponent {
846                         raw: unsafe { u8_slice_as_os_str(raw) },
847                         parsed: self.prefix.unwrap(),
848                     }));
849                 }
850                 State::Prefix => {
851                     self.front = State::StartDir;
852                 }
853                 State::StartDir => {
854                     self.front = State::Body;
855                     if self.has_physical_root {
856                         debug_assert!(!self.path.is_empty());
857                         self.path = &self.path[1..];
858                         return Some(Component::RootDir);
859                     } else if let Some(p) = self.prefix {
860                         if p.has_implicit_root() && !p.is_verbatim() {
861                             return Some(Component::RootDir);
862                         }
863                     } else if self.include_cur_dir() {
864                         debug_assert!(!self.path.is_empty());
865                         self.path = &self.path[1..];
866                         return Some(Component::CurDir);
867                     }
868                 }
869                 State::Body if !self.path.is_empty() => {
870                     let (size, comp) = self.parse_next_component();
871                     self.path = &self.path[size..];
872                     if comp.is_some() {
873                         return comp;
874                     }
875                 }
876                 State::Body => {
877                     self.front = State::Done;
878                 }
879                 State::Done => unreachable!(),
880             }
881         }
882         None
883     }
884 }
885
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<'a> DoubleEndedIterator for Components<'a> {
888     fn next_back(&mut self) -> Option<Component<'a>> {
889         while !self.finished() {
890             match self.back {
891                 State::Body if self.path.len() > self.len_before_body() => {
892                     let (size, comp) = self.parse_next_component_back();
893                     self.path = &self.path[..self.path.len() - size];
894                     if comp.is_some() {
895                         return comp;
896                     }
897                 }
898                 State::Body => {
899                     self.back = State::StartDir;
900                 }
901                 State::StartDir => {
902                     self.back = State::Prefix;
903                     if self.has_physical_root {
904                         self.path = &self.path[..self.path.len() - 1];
905                         return Some(Component::RootDir);
906                     } else if let Some(p) = self.prefix {
907                         if p.has_implicit_root() && !p.is_verbatim() {
908                             return Some(Component::RootDir);
909                         }
910                     } else if self.include_cur_dir() {
911                         self.path = &self.path[..self.path.len() - 1];
912                         return Some(Component::CurDir);
913                     }
914                 }
915                 State::Prefix if self.prefix_len() > 0 => {
916                     self.back = State::Done;
917                     return Some(Component::Prefix(PrefixComponent {
918                         raw: unsafe { u8_slice_as_os_str(self.path) },
919                         parsed: self.prefix.unwrap(),
920                     }));
921                 }
922                 State::Prefix => {
923                     self.back = State::Done;
924                     return None;
925                 }
926                 State::Done => unreachable!(),
927             }
928         }
929         None
930     }
931 }
932
933 #[stable(feature = "fused", since = "1.26.0")]
934 impl FusedIterator for Components<'_> {}
935
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<'a> cmp::PartialEq for Components<'a> {
938     fn eq(&self, other: &Components<'a>) -> bool {
939         Iterator::eq(self.clone(), other.clone())
940     }
941 }
942
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl cmp::Eq for Components<'_> {}
945
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<'a> cmp::PartialOrd for Components<'a> {
948     fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
949         Iterator::partial_cmp(self.clone(), other.clone())
950     }
951 }
952
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl cmp::Ord for Components<'_> {
955     fn cmp(&self, other: &Self) -> cmp::Ordering {
956         Iterator::cmp(self.clone(), other.clone())
957     }
958 }
959
960 /// An iterator over [`Path`] and its ancestors.
961 ///
962 /// This `struct` is created by the [`ancestors`] method on [`Path`].
963 /// See its documentation for more.
964 ///
965 /// # Examples
966 ///
967 /// ```
968 /// use std::path::Path;
969 ///
970 /// let path = Path::new("/foo/bar");
971 ///
972 /// for ancestor in path.ancestors() {
973 ///     println!("{}", ancestor.display());
974 /// }
975 /// ```
976 ///
977 /// [`ancestors`]: Path::ancestors
978 #[derive(Copy, Clone, Debug)]
979 #[stable(feature = "path_ancestors", since = "1.28.0")]
980 pub struct Ancestors<'a> {
981     next: Option<&'a Path>,
982 }
983
984 #[stable(feature = "path_ancestors", since = "1.28.0")]
985 impl<'a> Iterator for Ancestors<'a> {
986     type Item = &'a Path;
987
988     fn next(&mut self) -> Option<Self::Item> {
989         let next = self.next;
990         self.next = next.and_then(Path::parent);
991         next
992     }
993 }
994
995 #[stable(feature = "path_ancestors", since = "1.28.0")]
996 impl FusedIterator for Ancestors<'_> {}
997
998 ////////////////////////////////////////////////////////////////////////////////
999 // Basic types and traits
1000 ////////////////////////////////////////////////////////////////////////////////
1001
1002 /// An owned, mutable path (akin to [`String`]).
1003 ///
1004 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1005 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1006 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1007 ///
1008 /// [`push`]: PathBuf::push
1009 /// [`set_extension`]: PathBuf::set_extension
1010 ///
1011 /// More details about the overall approach can be found in
1012 /// the [module documentation](self).
1013 ///
1014 /// # Examples
1015 ///
1016 /// You can use [`push`] to build up a `PathBuf` from
1017 /// components:
1018 ///
1019 /// ```
1020 /// use std::path::PathBuf;
1021 ///
1022 /// let mut path = PathBuf::new();
1023 ///
1024 /// path.push(r"C:\");
1025 /// path.push("windows");
1026 /// path.push("system32");
1027 ///
1028 /// path.set_extension("dll");
1029 /// ```
1030 ///
1031 /// However, [`push`] is best used for dynamic situations. This is a better way
1032 /// to do this when you know all of the components ahead of time:
1033 ///
1034 /// ```
1035 /// use std::path::PathBuf;
1036 ///
1037 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1038 /// ```
1039 ///
1040 /// We can still do better than this! Since these are all strings, we can use
1041 /// `From::from`:
1042 ///
1043 /// ```
1044 /// use std::path::PathBuf;
1045 ///
1046 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1047 /// ```
1048 ///
1049 /// Which method works best depends on what kind of situation you're in.
1050 #[derive(Clone)]
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 // FIXME:
1053 // `PathBuf::as_mut_vec` current implementation relies
1054 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1055 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1056 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1057 // not documented and must not be relied upon.
1058 pub struct PathBuf {
1059     inner: OsString,
1060 }
1061
1062 impl PathBuf {
1063     fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1064         unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1065     }
1066
1067     /// Allocates an empty `PathBuf`.
1068     ///
1069     /// # Examples
1070     ///
1071     /// ```
1072     /// use std::path::PathBuf;
1073     ///
1074     /// let path = PathBuf::new();
1075     /// ```
1076     #[stable(feature = "rust1", since = "1.0.0")]
1077     pub fn new() -> PathBuf {
1078         PathBuf { inner: OsString::new() }
1079     }
1080
1081     /// Creates a new `PathBuf` with a given capacity used to create the
1082     /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1083     ///
1084     /// # Examples
1085     ///
1086     /// ```
1087     /// use std::path::PathBuf;
1088     ///
1089     /// let mut path = PathBuf::with_capacity(10);
1090     /// let capacity = path.capacity();
1091     ///
1092     /// // This push is done without reallocating
1093     /// path.push(r"C:\");
1094     ///
1095     /// assert_eq!(capacity, path.capacity());
1096     /// ```
1097     ///
1098     /// [`with_capacity`]: OsString::with_capacity
1099     #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1100     pub fn with_capacity(capacity: usize) -> PathBuf {
1101         PathBuf { inner: OsString::with_capacity(capacity) }
1102     }
1103
1104     /// Coerces to a [`Path`] slice.
1105     ///
1106     /// # Examples
1107     ///
1108     /// ```
1109     /// use std::path::{Path, PathBuf};
1110     ///
1111     /// let p = PathBuf::from("/test");
1112     /// assert_eq!(Path::new("/test"), p.as_path());
1113     /// ```
1114     #[stable(feature = "rust1", since = "1.0.0")]
1115     pub fn as_path(&self) -> &Path {
1116         self
1117     }
1118
1119     /// Extends `self` with `path`.
1120     ///
1121     /// If `path` is absolute, it replaces the current path.
1122     ///
1123     /// On Windows:
1124     ///
1125     /// * if `path` has a root but no prefix (e.g., `\windows`), it
1126     ///   replaces everything except for the prefix (if any) of `self`.
1127     /// * if `path` has a prefix but no root, it replaces `self`.
1128     ///
1129     /// # Examples
1130     ///
1131     /// Pushing a relative path extends the existing path:
1132     ///
1133     /// ```
1134     /// use std::path::PathBuf;
1135     ///
1136     /// let mut path = PathBuf::from("/tmp");
1137     /// path.push("file.bk");
1138     /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1139     /// ```
1140     ///
1141     /// Pushing an absolute path replaces the existing path:
1142     ///
1143     /// ```
1144     /// use std::path::PathBuf;
1145     ///
1146     /// let mut path = PathBuf::from("/tmp");
1147     /// path.push("/etc");
1148     /// assert_eq!(path, PathBuf::from("/etc"));
1149     /// ```
1150     #[stable(feature = "rust1", since = "1.0.0")]
1151     pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1152         self._push(path.as_ref())
1153     }
1154
1155     fn _push(&mut self, path: &Path) {
1156         // in general, a separator is needed if the rightmost byte is not a separator
1157         let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1158
1159         // in the special case of `C:` on Windows, do *not* add a separator
1160         {
1161             let comps = self.components();
1162             if comps.prefix_len() > 0
1163                 && comps.prefix_len() == comps.path.len()
1164                 && comps.prefix.unwrap().is_drive()
1165             {
1166                 need_sep = false
1167             }
1168         }
1169
1170         // absolute `path` replaces `self`
1171         if path.is_absolute() || path.prefix().is_some() {
1172             self.as_mut_vec().truncate(0);
1173
1174         // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1175         } else if path.has_root() {
1176             let prefix_len = self.components().prefix_remaining();
1177             self.as_mut_vec().truncate(prefix_len);
1178
1179         // `path` is a pure relative path
1180         } else if need_sep {
1181             self.inner.push(MAIN_SEP_STR);
1182         }
1183
1184         self.inner.push(path);
1185     }
1186
1187     /// Truncates `self` to [`self.parent`].
1188     ///
1189     /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1190     /// Otherwise, returns `true`.
1191     ///
1192     /// [`self.parent`]: Path::parent
1193     ///
1194     /// # Examples
1195     ///
1196     /// ```
1197     /// use std::path::{Path, PathBuf};
1198     ///
1199     /// let mut p = PathBuf::from("/spirited/away.rs");
1200     ///
1201     /// p.pop();
1202     /// assert_eq!(Path::new("/spirited"), p);
1203     /// p.pop();
1204     /// assert_eq!(Path::new("/"), p);
1205     /// ```
1206     #[stable(feature = "rust1", since = "1.0.0")]
1207     pub fn pop(&mut self) -> bool {
1208         match self.parent().map(|p| p.as_u8_slice().len()) {
1209             Some(len) => {
1210                 self.as_mut_vec().truncate(len);
1211                 true
1212             }
1213             None => false,
1214         }
1215     }
1216
1217     /// Updates [`self.file_name`] to `file_name`.
1218     ///
1219     /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1220     /// `file_name`.
1221     ///
1222     /// Otherwise it is equivalent to calling [`pop`] and then pushing
1223     /// `file_name`. The new path will be a sibling of the original path.
1224     /// (That is, it will have the same parent.)
1225     ///
1226     /// [`self.file_name`]: Path::file_name
1227     /// [`pop`]: PathBuf::pop
1228     ///
1229     /// # Examples
1230     ///
1231     /// ```
1232     /// use std::path::PathBuf;
1233     ///
1234     /// let mut buf = PathBuf::from("/");
1235     /// assert!(buf.file_name() == None);
1236     /// buf.set_file_name("bar");
1237     /// assert!(buf == PathBuf::from("/bar"));
1238     /// assert!(buf.file_name().is_some());
1239     /// buf.set_file_name("baz.txt");
1240     /// assert!(buf == PathBuf::from("/baz.txt"));
1241     /// ```
1242     #[stable(feature = "rust1", since = "1.0.0")]
1243     pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1244         self._set_file_name(file_name.as_ref())
1245     }
1246
1247     fn _set_file_name(&mut self, file_name: &OsStr) {
1248         if self.file_name().is_some() {
1249             let popped = self.pop();
1250             debug_assert!(popped);
1251         }
1252         self.push(file_name);
1253     }
1254
1255     /// Updates [`self.extension`] to `extension`.
1256     ///
1257     /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1258     /// returns `true` and updates the extension otherwise.
1259     ///
1260     /// If [`self.extension`] is [`None`], the extension is added; otherwise
1261     /// it is replaced.
1262     ///
1263     /// [`self.file_name`]: Path::file_name
1264     /// [`self.extension`]: Path::extension
1265     ///
1266     /// # Examples
1267     ///
1268     /// ```
1269     /// use std::path::{Path, PathBuf};
1270     ///
1271     /// let mut p = PathBuf::from("/feel/the");
1272     ///
1273     /// p.set_extension("force");
1274     /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1275     ///
1276     /// p.set_extension("dark_side");
1277     /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1278     /// ```
1279     #[stable(feature = "rust1", since = "1.0.0")]
1280     pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1281         self._set_extension(extension.as_ref())
1282     }
1283
1284     fn _set_extension(&mut self, extension: &OsStr) -> bool {
1285         let file_stem = match self.file_stem() {
1286             None => return false,
1287             Some(f) => os_str_as_u8_slice(f),
1288         };
1289
1290         // truncate until right after the file stem
1291         let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1292         let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1293         let v = self.as_mut_vec();
1294         v.truncate(end_file_stem.wrapping_sub(start));
1295
1296         // add the new extension, if any
1297         let new = os_str_as_u8_slice(extension);
1298         if !new.is_empty() {
1299             v.reserve_exact(new.len() + 1);
1300             v.push(b'.');
1301             v.extend_from_slice(new);
1302         }
1303
1304         true
1305     }
1306
1307     /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1308     ///
1309     /// # Examples
1310     ///
1311     /// ```
1312     /// use std::path::PathBuf;
1313     ///
1314     /// let p = PathBuf::from("/the/head");
1315     /// let os_str = p.into_os_string();
1316     /// ```
1317     #[stable(feature = "rust1", since = "1.0.0")]
1318     pub fn into_os_string(self) -> OsString {
1319         self.inner
1320     }
1321
1322     /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1323     #[stable(feature = "into_boxed_path", since = "1.20.0")]
1324     pub fn into_boxed_path(self) -> Box<Path> {
1325         let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1326         unsafe { Box::from_raw(rw) }
1327     }
1328
1329     /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1330     ///
1331     /// [`capacity`]: OsString::capacity
1332     #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1333     pub fn capacity(&self) -> usize {
1334         self.inner.capacity()
1335     }
1336
1337     /// Invokes [`clear`] on the underlying instance of [`OsString`].
1338     ///
1339     /// [`clear`]: OsString::clear
1340     #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1341     pub fn clear(&mut self) {
1342         self.inner.clear()
1343     }
1344
1345     /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1346     ///
1347     /// [`reserve`]: OsString::reserve
1348     #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1349     pub fn reserve(&mut self, additional: usize) {
1350         self.inner.reserve(additional)
1351     }
1352
1353     /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1354     ///
1355     /// [`reserve_exact`]: OsString::reserve_exact
1356     #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1357     pub fn reserve_exact(&mut self, additional: usize) {
1358         self.inner.reserve_exact(additional)
1359     }
1360
1361     /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1362     ///
1363     /// [`shrink_to_fit`]: OsString::shrink_to_fit
1364     #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1365     pub fn shrink_to_fit(&mut self) {
1366         self.inner.shrink_to_fit()
1367     }
1368
1369     /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1370     ///
1371     /// [`shrink_to`]: OsString::shrink_to
1372     #[unstable(feature = "shrink_to", issue = "56431")]
1373     pub fn shrink_to(&mut self, min_capacity: usize) {
1374         self.inner.shrink_to(min_capacity)
1375     }
1376 }
1377
1378 #[stable(feature = "box_from_path", since = "1.17.0")]
1379 impl From<&Path> for Box<Path> {
1380     fn from(path: &Path) -> Box<Path> {
1381         let boxed: Box<OsStr> = path.inner.into();
1382         let rw = Box::into_raw(boxed) as *mut Path;
1383         unsafe { Box::from_raw(rw) }
1384     }
1385 }
1386
1387 #[stable(feature = "box_from_cow", since = "1.45.0")]
1388 impl From<Cow<'_, Path>> for Box<Path> {
1389     #[inline]
1390     fn from(cow: Cow<'_, Path>) -> Box<Path> {
1391         match cow {
1392             Cow::Borrowed(path) => Box::from(path),
1393             Cow::Owned(path) => Box::from(path),
1394         }
1395     }
1396 }
1397
1398 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1399 impl From<Box<Path>> for PathBuf {
1400     /// Converts a `Box<Path>` into a `PathBuf`
1401     ///
1402     /// This conversion does not allocate or copy memory.
1403     fn from(boxed: Box<Path>) -> PathBuf {
1404         boxed.into_path_buf()
1405     }
1406 }
1407
1408 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1409 impl From<PathBuf> for Box<Path> {
1410     /// Converts a `PathBuf` into a `Box<Path>`
1411     ///
1412     /// This conversion currently should not allocate memory,
1413     /// but this behavior is not guaranteed on all platforms or in all future versions.
1414     fn from(p: PathBuf) -> Box<Path> {
1415         p.into_boxed_path()
1416     }
1417 }
1418
1419 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1420 impl Clone for Box<Path> {
1421     #[inline]
1422     fn clone(&self) -> Self {
1423         self.to_path_buf().into_boxed_path()
1424     }
1425 }
1426
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1429     fn from(s: &T) -> PathBuf {
1430         PathBuf::from(s.as_ref().to_os_string())
1431     }
1432 }
1433
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl From<OsString> for PathBuf {
1436     /// Converts a `OsString` into a `PathBuf`
1437     ///
1438     /// This conversion does not allocate or copy memory.
1439     #[inline]
1440     fn from(s: OsString) -> PathBuf {
1441         PathBuf { inner: s }
1442     }
1443 }
1444
1445 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1446 impl From<PathBuf> for OsString {
1447     /// Converts a `PathBuf` into a `OsString`
1448     ///
1449     /// This conversion does not allocate or copy memory.
1450     fn from(path_buf: PathBuf) -> OsString {
1451         path_buf.inner
1452     }
1453 }
1454
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl From<String> for PathBuf {
1457     /// Converts a `String` into a `PathBuf`
1458     ///
1459     /// This conversion does not allocate or copy memory.
1460     fn from(s: String) -> PathBuf {
1461         PathBuf::from(OsString::from(s))
1462     }
1463 }
1464
1465 #[stable(feature = "path_from_str", since = "1.32.0")]
1466 impl FromStr for PathBuf {
1467     type Err = core::convert::Infallible;
1468
1469     fn from_str(s: &str) -> Result<Self, Self::Err> {
1470         Ok(PathBuf::from(s))
1471     }
1472 }
1473
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1476     fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1477         let mut buf = PathBuf::new();
1478         buf.extend(iter);
1479         buf
1480     }
1481 }
1482
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1485     fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1486         iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1487     }
1488
1489     #[inline]
1490     fn extend_one(&mut self, p: P) {
1491         self.push(p.as_ref());
1492     }
1493 }
1494
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl fmt::Debug for PathBuf {
1497     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1498         fmt::Debug::fmt(&**self, formatter)
1499     }
1500 }
1501
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl ops::Deref for PathBuf {
1504     type Target = Path;
1505     #[inline]
1506     fn deref(&self) -> &Path {
1507         Path::new(&self.inner)
1508     }
1509 }
1510
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl Borrow<Path> for PathBuf {
1513     fn borrow(&self) -> &Path {
1514         self.deref()
1515     }
1516 }
1517
1518 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1519 impl Default for PathBuf {
1520     fn default() -> Self {
1521         PathBuf::new()
1522     }
1523 }
1524
1525 #[stable(feature = "cow_from_path", since = "1.6.0")]
1526 impl<'a> From<&'a Path> for Cow<'a, Path> {
1527     #[inline]
1528     fn from(s: &'a Path) -> Cow<'a, Path> {
1529         Cow::Borrowed(s)
1530     }
1531 }
1532
1533 #[stable(feature = "cow_from_path", since = "1.6.0")]
1534 impl<'a> From<PathBuf> for Cow<'a, Path> {
1535     #[inline]
1536     fn from(s: PathBuf) -> Cow<'a, Path> {
1537         Cow::Owned(s)
1538     }
1539 }
1540
1541 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1542 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1543     #[inline]
1544     fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1545         Cow::Borrowed(p.as_path())
1546     }
1547 }
1548
1549 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1550 impl<'a> From<Cow<'a, Path>> for PathBuf {
1551     #[inline]
1552     fn from(p: Cow<'a, Path>) -> Self {
1553         p.into_owned()
1554     }
1555 }
1556
1557 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1558 impl From<PathBuf> for Arc<Path> {
1559     /// Converts a `PathBuf` into an `Arc` by moving the `PathBuf` data into a new `Arc` buffer.
1560     #[inline]
1561     fn from(s: PathBuf) -> Arc<Path> {
1562         let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1563         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1564     }
1565 }
1566
1567 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1568 impl From<&Path> for Arc<Path> {
1569     /// Converts a `Path` into an `Arc` by copying the `Path` data into a new `Arc` buffer.
1570     #[inline]
1571     fn from(s: &Path) -> Arc<Path> {
1572         let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1573         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1574     }
1575 }
1576
1577 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1578 impl From<PathBuf> for Rc<Path> {
1579     /// Converts a `PathBuf` into an `Rc` by moving the `PathBuf` data into a new `Rc` buffer.
1580     #[inline]
1581     fn from(s: PathBuf) -> Rc<Path> {
1582         let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1583         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1584     }
1585 }
1586
1587 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1588 impl From<&Path> for Rc<Path> {
1589     /// Converts a `Path` into an `Rc` by copying the `Path` data into a new `Rc` buffer.
1590     #[inline]
1591     fn from(s: &Path) -> Rc<Path> {
1592         let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1593         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1594     }
1595 }
1596
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl ToOwned for Path {
1599     type Owned = PathBuf;
1600     fn to_owned(&self) -> PathBuf {
1601         self.to_path_buf()
1602     }
1603     fn clone_into(&self, target: &mut PathBuf) {
1604         self.inner.clone_into(&mut target.inner);
1605     }
1606 }
1607
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl cmp::PartialEq for PathBuf {
1610     fn eq(&self, other: &PathBuf) -> bool {
1611         self.components() == other.components()
1612     }
1613 }
1614
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl Hash for PathBuf {
1617     fn hash<H: Hasher>(&self, h: &mut H) {
1618         self.as_path().hash(h)
1619     }
1620 }
1621
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 impl cmp::Eq for PathBuf {}
1624
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl cmp::PartialOrd for PathBuf {
1627     fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1628         self.components().partial_cmp(other.components())
1629     }
1630 }
1631
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 impl cmp::Ord for PathBuf {
1634     fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1635         self.components().cmp(other.components())
1636     }
1637 }
1638
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl AsRef<OsStr> for PathBuf {
1641     fn as_ref(&self) -> &OsStr {
1642         &self.inner[..]
1643     }
1644 }
1645
1646 /// A slice of a path (akin to [`str`]).
1647 ///
1648 /// This type supports a number of operations for inspecting a path, including
1649 /// breaking the path into its components (separated by `/` on Unix and by either
1650 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1651 /// is absolute, and so on.
1652 ///
1653 /// This is an *unsized* type, meaning that it must always be used behind a
1654 /// pointer like `&` or [`Box`]. For an owned version of this type,
1655 /// see [`PathBuf`].
1656 ///
1657 /// More details about the overall approach can be found in
1658 /// the [module documentation](self).
1659 ///
1660 /// # Examples
1661 ///
1662 /// ```
1663 /// use std::path::Path;
1664 /// use std::ffi::OsStr;
1665 ///
1666 /// // Note: this example does work on Windows
1667 /// let path = Path::new("./foo/bar.txt");
1668 ///
1669 /// let parent = path.parent();
1670 /// assert_eq!(parent, Some(Path::new("./foo")));
1671 ///
1672 /// let file_stem = path.file_stem();
1673 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1674 ///
1675 /// let extension = path.extension();
1676 /// assert_eq!(extension, Some(OsStr::new("txt")));
1677 /// ```
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 // FIXME:
1680 // `Path::new` current implementation relies
1681 // on `Path` being layout-compatible with `OsStr`.
1682 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1683 // Anyway, `Path` representation and layout are considered implementation detail, are
1684 // not documented and must not be relied upon.
1685 pub struct Path {
1686     inner: OsStr,
1687 }
1688
1689 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1690 ///
1691 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1692 /// See its documentation for more.
1693 ///
1694 /// [`strip_prefix`]: Path::strip_prefix
1695 #[derive(Debug, Clone, PartialEq, Eq)]
1696 #[stable(since = "1.7.0", feature = "strip_prefix")]
1697 pub struct StripPrefixError(());
1698
1699 impl Path {
1700     // The following (private!) function allows construction of a path from a u8
1701     // slice, which is only safe when it is known to follow the OsStr encoding.
1702     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1703         unsafe { Path::new(u8_slice_as_os_str(s)) }
1704     }
1705     // The following (private!) function reveals the byte encoding used for OsStr.
1706     fn as_u8_slice(&self) -> &[u8] {
1707         os_str_as_u8_slice(&self.inner)
1708     }
1709
1710     /// Directly wraps a string slice as a `Path` slice.
1711     ///
1712     /// This is a cost-free conversion.
1713     ///
1714     /// # Examples
1715     ///
1716     /// ```
1717     /// use std::path::Path;
1718     ///
1719     /// Path::new("foo.txt");
1720     /// ```
1721     ///
1722     /// You can create `Path`s from `String`s, or even other `Path`s:
1723     ///
1724     /// ```
1725     /// use std::path::Path;
1726     ///
1727     /// let string = String::from("foo.txt");
1728     /// let from_string = Path::new(&string);
1729     /// let from_path = Path::new(&from_string);
1730     /// assert_eq!(from_string, from_path);
1731     /// ```
1732     #[stable(feature = "rust1", since = "1.0.0")]
1733     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1734         unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1735     }
1736
1737     /// Yields the underlying [`OsStr`] slice.
1738     ///
1739     /// # Examples
1740     ///
1741     /// ```
1742     /// use std::path::Path;
1743     ///
1744     /// let os_str = Path::new("foo.txt").as_os_str();
1745     /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1746     /// ```
1747     #[stable(feature = "rust1", since = "1.0.0")]
1748     pub fn as_os_str(&self) -> &OsStr {
1749         &self.inner
1750     }
1751
1752     /// Yields a [`&str`] slice if the `Path` is valid unicode.
1753     ///
1754     /// This conversion may entail doing a check for UTF-8 validity.
1755     /// Note that validation is performed because non-UTF-8 strings are
1756     /// perfectly valid for some OS.
1757     ///
1758     /// [`&str`]: str
1759     ///
1760     /// # Examples
1761     ///
1762     /// ```
1763     /// use std::path::Path;
1764     ///
1765     /// let path = Path::new("foo.txt");
1766     /// assert_eq!(path.to_str(), Some("foo.txt"));
1767     /// ```
1768     #[stable(feature = "rust1", since = "1.0.0")]
1769     pub fn to_str(&self) -> Option<&str> {
1770         self.inner.to_str()
1771     }
1772
1773     /// Converts a `Path` to a [`Cow<str>`].
1774     ///
1775     /// Any non-Unicode sequences are replaced with
1776     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1777     ///
1778     /// [`Cow<str>`]: Cow
1779     /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1780     ///
1781     /// # Examples
1782     ///
1783     /// Calling `to_string_lossy` on a `Path` with valid unicode:
1784     ///
1785     /// ```
1786     /// use std::path::Path;
1787     ///
1788     /// let path = Path::new("foo.txt");
1789     /// assert_eq!(path.to_string_lossy(), "foo.txt");
1790     /// ```
1791     ///
1792     /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1793     /// have returned `"fo�.txt"`.
1794     #[stable(feature = "rust1", since = "1.0.0")]
1795     pub fn to_string_lossy(&self) -> Cow<'_, str> {
1796         self.inner.to_string_lossy()
1797     }
1798
1799     /// Converts a `Path` to an owned [`PathBuf`].
1800     ///
1801     /// # Examples
1802     ///
1803     /// ```
1804     /// use std::path::Path;
1805     ///
1806     /// let path_buf = Path::new("foo.txt").to_path_buf();
1807     /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1808     /// ```
1809     #[rustc_conversion_suggestion]
1810     #[stable(feature = "rust1", since = "1.0.0")]
1811     pub fn to_path_buf(&self) -> PathBuf {
1812         PathBuf::from(self.inner.to_os_string())
1813     }
1814
1815     /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1816     /// the current directory.
1817     ///
1818     /// * On Unix, a path is absolute if it starts with the root, so
1819     /// `is_absolute` and [`has_root`] are equivalent.
1820     ///
1821     /// * On Windows, a path is absolute if it has a prefix and starts with the
1822     /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1823     ///
1824     /// # Examples
1825     ///
1826     /// ```
1827     /// use std::path::Path;
1828     ///
1829     /// assert!(!Path::new("foo.txt").is_absolute());
1830     /// ```
1831     ///
1832     /// [`has_root`]: Path::has_root
1833     #[stable(feature = "rust1", since = "1.0.0")]
1834     #[allow(deprecated)]
1835     pub fn is_absolute(&self) -> bool {
1836         if cfg!(target_os = "redox") {
1837             // FIXME: Allow Redox prefixes
1838             self.has_root() || has_redox_scheme(self.as_u8_slice())
1839         } else {
1840             self.has_root() && (cfg!(any(unix, target_os = "wasi")) || self.prefix().is_some())
1841         }
1842     }
1843
1844     /// Returns `true` if the `Path` is relative, i.e., not absolute.
1845     ///
1846     /// See [`is_absolute`]'s documentation for more details.
1847     ///
1848     /// # Examples
1849     ///
1850     /// ```
1851     /// use std::path::Path;
1852     ///
1853     /// assert!(Path::new("foo.txt").is_relative());
1854     /// ```
1855     ///
1856     /// [`is_absolute`]: Path::is_absolute
1857     #[stable(feature = "rust1", since = "1.0.0")]
1858     pub fn is_relative(&self) -> bool {
1859         !self.is_absolute()
1860     }
1861
1862     fn prefix(&self) -> Option<Prefix<'_>> {
1863         self.components().prefix
1864     }
1865
1866     /// Returns `true` if the `Path` has a root.
1867     ///
1868     /// * On Unix, a path has a root if it begins with `/`.
1869     ///
1870     /// * On Windows, a path has a root if it:
1871     ///     * has no prefix and begins with a separator, e.g., `\windows`
1872     ///     * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1873     ///     * has any non-disk prefix, e.g., `\\server\share`
1874     ///
1875     /// # Examples
1876     ///
1877     /// ```
1878     /// use std::path::Path;
1879     ///
1880     /// assert!(Path::new("/etc/passwd").has_root());
1881     /// ```
1882     #[stable(feature = "rust1", since = "1.0.0")]
1883     pub fn has_root(&self) -> bool {
1884         self.components().has_root()
1885     }
1886
1887     /// Returns the `Path` without its final component, if there is one.
1888     ///
1889     /// Returns [`None`] if the path terminates in a root or prefix.
1890     ///
1891     /// # Examples
1892     ///
1893     /// ```
1894     /// use std::path::Path;
1895     ///
1896     /// let path = Path::new("/foo/bar");
1897     /// let parent = path.parent().unwrap();
1898     /// assert_eq!(parent, Path::new("/foo"));
1899     ///
1900     /// let grand_parent = parent.parent().unwrap();
1901     /// assert_eq!(grand_parent, Path::new("/"));
1902     /// assert_eq!(grand_parent.parent(), None);
1903     /// ```
1904     #[stable(feature = "rust1", since = "1.0.0")]
1905     pub fn parent(&self) -> Option<&Path> {
1906         let mut comps = self.components();
1907         let comp = comps.next_back();
1908         comp.and_then(|p| match p {
1909             Component::Normal(_) | Component::CurDir | Component::ParentDir => {
1910                 Some(comps.as_path())
1911             }
1912             _ => None,
1913         })
1914     }
1915
1916     /// Produces an iterator over `Path` and its ancestors.
1917     ///
1918     /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1919     /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1920     /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1921     /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1922     /// namely `&self`.
1923     ///
1924     /// # Examples
1925     ///
1926     /// ```
1927     /// use std::path::Path;
1928     ///
1929     /// let mut ancestors = Path::new("/foo/bar").ancestors();
1930     /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1931     /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1932     /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1933     /// assert_eq!(ancestors.next(), None);
1934     ///
1935     /// let mut ancestors = Path::new("../foo/bar").ancestors();
1936     /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
1937     /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
1938     /// assert_eq!(ancestors.next(), Some(Path::new("..")));
1939     /// assert_eq!(ancestors.next(), Some(Path::new("")));
1940     /// assert_eq!(ancestors.next(), None);
1941     /// ```
1942     ///
1943     /// [`parent`]: Path::parent
1944     #[stable(feature = "path_ancestors", since = "1.28.0")]
1945     pub fn ancestors(&self) -> Ancestors<'_> {
1946         Ancestors { next: Some(&self) }
1947     }
1948
1949     /// Returns the final component of the `Path`, if there is one.
1950     ///
1951     /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1952     /// is the directory name.
1953     ///
1954     /// Returns [`None`] if the path terminates in `..`.
1955     ///
1956     /// # Examples
1957     ///
1958     /// ```
1959     /// use std::path::Path;
1960     /// use std::ffi::OsStr;
1961     ///
1962     /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1963     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1964     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1965     /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1966     /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1967     /// assert_eq!(None, Path::new("/").file_name());
1968     /// ```
1969     #[stable(feature = "rust1", since = "1.0.0")]
1970     pub fn file_name(&self) -> Option<&OsStr> {
1971         self.components().next_back().and_then(|p| match p {
1972             Component::Normal(p) => Some(p),
1973             _ => None,
1974         })
1975     }
1976
1977     /// Returns a path that, when joined onto `base`, yields `self`.
1978     ///
1979     /// # Errors
1980     ///
1981     /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
1982     /// returns `false`), returns [`Err`].
1983     ///
1984     /// [`starts_with`]: Path::starts_with
1985     ///
1986     /// # Examples
1987     ///
1988     /// ```
1989     /// use std::path::{Path, PathBuf};
1990     ///
1991     /// let path = Path::new("/test/haha/foo.txt");
1992     ///
1993     /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
1994     /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1995     /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
1996     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
1997     /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
1998     ///
1999     /// assert!(path.strip_prefix("test").is_err());
2000     /// assert!(path.strip_prefix("/haha").is_err());
2001     ///
2002     /// let prefix = PathBuf::from("/test/");
2003     /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2004     /// ```
2005     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2006     pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2007     where
2008         P: AsRef<Path>,
2009     {
2010         self._strip_prefix(base.as_ref())
2011     }
2012
2013     fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2014         iter_after(self.components(), base.components())
2015             .map(|c| c.as_path())
2016             .ok_or(StripPrefixError(()))
2017     }
2018
2019     /// Determines whether `base` is a prefix of `self`.
2020     ///
2021     /// Only considers whole path components to match.
2022     ///
2023     /// # Examples
2024     ///
2025     /// ```
2026     /// use std::path::Path;
2027     ///
2028     /// let path = Path::new("/etc/passwd");
2029     ///
2030     /// assert!(path.starts_with("/etc"));
2031     /// assert!(path.starts_with("/etc/"));
2032     /// assert!(path.starts_with("/etc/passwd"));
2033     /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2034     /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2035     ///
2036     /// assert!(!path.starts_with("/e"));
2037     /// assert!(!path.starts_with("/etc/passwd.txt"));
2038     ///
2039     /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2040     /// ```
2041     #[stable(feature = "rust1", since = "1.0.0")]
2042     pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2043         self._starts_with(base.as_ref())
2044     }
2045
2046     fn _starts_with(&self, base: &Path) -> bool {
2047         iter_after(self.components(), base.components()).is_some()
2048     }
2049
2050     /// Determines whether `child` is a suffix of `self`.
2051     ///
2052     /// Only considers whole path components to match.
2053     ///
2054     /// # Examples
2055     ///
2056     /// ```
2057     /// use std::path::Path;
2058     ///
2059     /// let path = Path::new("/etc/resolv.conf");
2060     ///
2061     /// assert!(path.ends_with("resolv.conf"));
2062     /// assert!(path.ends_with("etc/resolv.conf"));
2063     /// assert!(path.ends_with("/etc/resolv.conf"));
2064     ///
2065     /// assert!(!path.ends_with("/resolv.conf"));
2066     /// assert!(!path.ends_with("conf")); // use .extension() instead
2067     /// ```
2068     #[stable(feature = "rust1", since = "1.0.0")]
2069     pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2070         self._ends_with(child.as_ref())
2071     }
2072
2073     fn _ends_with(&self, child: &Path) -> bool {
2074         iter_after(self.components().rev(), child.components().rev()).is_some()
2075     }
2076
2077     /// Extracts the stem (non-extension) portion of [`self.file_name`].
2078     ///
2079     /// [`self.file_name`]: Path::file_name
2080     ///
2081     /// The stem is:
2082     ///
2083     /// * [`None`], if there is no file name;
2084     /// * The entire file name if there is no embedded `.`;
2085     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2086     /// * Otherwise, the portion of the file name before the final `.`
2087     ///
2088     /// # Examples
2089     ///
2090     /// ```
2091     /// use std::path::Path;
2092     ///
2093     /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2094     /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2095     /// ```
2096     #[stable(feature = "rust1", since = "1.0.0")]
2097     pub fn file_stem(&self) -> Option<&OsStr> {
2098         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2099     }
2100
2101     /// Extracts the extension of [`self.file_name`], if possible.
2102     ///
2103     /// The extension is:
2104     ///
2105     /// * [`None`], if there is no file name;
2106     /// * [`None`], if there is no embedded `.`;
2107     /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2108     /// * Otherwise, the portion of the file name after the final `.`
2109     ///
2110     /// [`self.file_name`]: Path::file_name
2111     ///
2112     /// # Examples
2113     ///
2114     /// ```
2115     /// use std::path::Path;
2116     ///
2117     /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2118     /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2119     /// ```
2120     #[stable(feature = "rust1", since = "1.0.0")]
2121     pub fn extension(&self) -> Option<&OsStr> {
2122         self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2123     }
2124
2125     /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2126     ///
2127     /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2128     ///
2129     /// # Examples
2130     ///
2131     /// ```
2132     /// use std::path::{Path, PathBuf};
2133     ///
2134     /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2135     /// ```
2136     #[stable(feature = "rust1", since = "1.0.0")]
2137     #[must_use]
2138     pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2139         self._join(path.as_ref())
2140     }
2141
2142     fn _join(&self, path: &Path) -> PathBuf {
2143         let mut buf = self.to_path_buf();
2144         buf.push(path);
2145         buf
2146     }
2147
2148     /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2149     ///
2150     /// See [`PathBuf::set_file_name`] for more details.
2151     ///
2152     /// # Examples
2153     ///
2154     /// ```
2155     /// use std::path::{Path, PathBuf};
2156     ///
2157     /// let path = Path::new("/tmp/foo.txt");
2158     /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2159     ///
2160     /// let path = Path::new("/tmp");
2161     /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2162     /// ```
2163     #[stable(feature = "rust1", since = "1.0.0")]
2164     pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2165         self._with_file_name(file_name.as_ref())
2166     }
2167
2168     fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2169         let mut buf = self.to_path_buf();
2170         buf.set_file_name(file_name);
2171         buf
2172     }
2173
2174     /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2175     ///
2176     /// See [`PathBuf::set_extension`] for more details.
2177     ///
2178     /// # Examples
2179     ///
2180     /// ```
2181     /// use std::path::{Path, PathBuf};
2182     ///
2183     /// let path = Path::new("foo.rs");
2184     /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2185     ///
2186     /// let path = Path::new("foo.tar.gz");
2187     /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2188     /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2189     /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2190     /// ```
2191     #[stable(feature = "rust1", since = "1.0.0")]
2192     pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2193         self._with_extension(extension.as_ref())
2194     }
2195
2196     fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2197         let mut buf = self.to_path_buf();
2198         buf.set_extension(extension);
2199         buf
2200     }
2201
2202     /// Produces an iterator over the [`Component`]s of the path.
2203     ///
2204     /// When parsing the path, there is a small amount of normalization:
2205     ///
2206     /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2207     ///   `a` and `b` as components.
2208     ///
2209     /// * Occurrences of `.` are normalized away, except if they are at the
2210     ///   beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2211     ///   `a/b` all have `a` and `b` as components, but `./a/b` starts with
2212     ///   an additional [`CurDir`] component.
2213     ///
2214     /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2215     ///
2216     /// Note that no other normalization takes place; in particular, `a/c`
2217     /// and `a/b/../c` are distinct, to account for the possibility that `b`
2218     /// is a symbolic link (so its parent isn't `a`).
2219     ///
2220     /// # Examples
2221     ///
2222     /// ```
2223     /// use std::path::{Path, Component};
2224     /// use std::ffi::OsStr;
2225     ///
2226     /// let mut components = Path::new("/tmp/foo.txt").components();
2227     ///
2228     /// assert_eq!(components.next(), Some(Component::RootDir));
2229     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2230     /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2231     /// assert_eq!(components.next(), None)
2232     /// ```
2233     ///
2234     /// [`CurDir`]: Component::CurDir
2235     #[stable(feature = "rust1", since = "1.0.0")]
2236     pub fn components(&self) -> Components<'_> {
2237         let prefix = parse_prefix(self.as_os_str());
2238         Components {
2239             path: self.as_u8_slice(),
2240             prefix,
2241             has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2242                 || has_redox_scheme(self.as_u8_slice()),
2243             front: State::Prefix,
2244             back: State::Body,
2245         }
2246     }
2247
2248     /// Produces an iterator over the path's components viewed as [`OsStr`]
2249     /// slices.
2250     ///
2251     /// For more information about the particulars of how the path is separated
2252     /// into components, see [`components`].
2253     ///
2254     /// [`components`]: Path::components
2255     ///
2256     /// # Examples
2257     ///
2258     /// ```
2259     /// use std::path::{self, Path};
2260     /// use std::ffi::OsStr;
2261     ///
2262     /// let mut it = Path::new("/tmp/foo.txt").iter();
2263     /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2264     /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2265     /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2266     /// assert_eq!(it.next(), None)
2267     /// ```
2268     #[stable(feature = "rust1", since = "1.0.0")]
2269     pub fn iter(&self) -> Iter<'_> {
2270         Iter { inner: self.components() }
2271     }
2272
2273     /// Returns an object that implements [`Display`] for safely printing paths
2274     /// that may contain non-Unicode data.
2275     ///
2276     /// [`Display`]: fmt::Display
2277     ///
2278     /// # Examples
2279     ///
2280     /// ```
2281     /// use std::path::Path;
2282     ///
2283     /// let path = Path::new("/tmp/foo.rs");
2284     ///
2285     /// println!("{}", path.display());
2286     /// ```
2287     #[stable(feature = "rust1", since = "1.0.0")]
2288     pub fn display(&self) -> Display<'_> {
2289         Display { path: self }
2290     }
2291
2292     /// Queries the file system to get information about a file, directory, etc.
2293     ///
2294     /// This function will traverse symbolic links to query information about the
2295     /// destination file.
2296     ///
2297     /// This is an alias to [`fs::metadata`].
2298     ///
2299     /// # Examples
2300     ///
2301     /// ```no_run
2302     /// use std::path::Path;
2303     ///
2304     /// let path = Path::new("/Minas/tirith");
2305     /// let metadata = path.metadata().expect("metadata call failed");
2306     /// println!("{:?}", metadata.file_type());
2307     /// ```
2308     #[stable(feature = "path_ext", since = "1.5.0")]
2309     pub fn metadata(&self) -> io::Result<fs::Metadata> {
2310         fs::metadata(self)
2311     }
2312
2313     /// Queries the metadata about a file without following symlinks.
2314     ///
2315     /// This is an alias to [`fs::symlink_metadata`].
2316     ///
2317     /// # Examples
2318     ///
2319     /// ```no_run
2320     /// use std::path::Path;
2321     ///
2322     /// let path = Path::new("/Minas/tirith");
2323     /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2324     /// println!("{:?}", metadata.file_type());
2325     /// ```
2326     #[stable(feature = "path_ext", since = "1.5.0")]
2327     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2328         fs::symlink_metadata(self)
2329     }
2330
2331     /// Returns the canonical, absolute form of the path with all intermediate
2332     /// components normalized and symbolic links resolved.
2333     ///
2334     /// This is an alias to [`fs::canonicalize`].
2335     ///
2336     /// # Examples
2337     ///
2338     /// ```no_run
2339     /// use std::path::{Path, PathBuf};
2340     ///
2341     /// let path = Path::new("/foo/test/../test/bar.rs");
2342     /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2343     /// ```
2344     #[stable(feature = "path_ext", since = "1.5.0")]
2345     pub fn canonicalize(&self) -> io::Result<PathBuf> {
2346         fs::canonicalize(self)
2347     }
2348
2349     /// Reads a symbolic link, returning the file that the link points to.
2350     ///
2351     /// This is an alias to [`fs::read_link`].
2352     ///
2353     /// # Examples
2354     ///
2355     /// ```no_run
2356     /// use std::path::Path;
2357     ///
2358     /// let path = Path::new("/laputa/sky_castle.rs");
2359     /// let path_link = path.read_link().expect("read_link call failed");
2360     /// ```
2361     #[stable(feature = "path_ext", since = "1.5.0")]
2362     pub fn read_link(&self) -> io::Result<PathBuf> {
2363         fs::read_link(self)
2364     }
2365
2366     /// Returns an iterator over the entries within a directory.
2367     ///
2368     /// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New
2369     /// errors may be encountered after an iterator is initially constructed.
2370     ///
2371     /// This is an alias to [`fs::read_dir`].
2372     ///
2373     /// # Examples
2374     ///
2375     /// ```no_run
2376     /// use std::path::Path;
2377     ///
2378     /// let path = Path::new("/laputa");
2379     /// for entry in path.read_dir().expect("read_dir call failed") {
2380     ///     if let Ok(entry) = entry {
2381     ///         println!("{:?}", entry.path());
2382     ///     }
2383     /// }
2384     /// ```
2385     #[stable(feature = "path_ext", since = "1.5.0")]
2386     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2387         fs::read_dir(self)
2388     }
2389
2390     /// Returns `true` if the path points at an existing entity.
2391     ///
2392     /// This function will traverse symbolic links to query information about the
2393     /// destination file. In case of broken symbolic links this will return `false`.
2394     ///
2395     /// If you cannot access the directory containing the file, e.g., because of a
2396     /// permission error, this will return `false`.
2397     ///
2398     /// # Examples
2399     ///
2400     /// ```no_run
2401     /// use std::path::Path;
2402     /// assert!(!Path::new("does_not_exist.txt").exists());
2403     /// ```
2404     ///
2405     /// # See Also
2406     ///
2407     /// This is a convenience function that coerces errors to false. If you want to
2408     /// check errors, call [`fs::metadata`].
2409     #[stable(feature = "path_ext", since = "1.5.0")]
2410     pub fn exists(&self) -> bool {
2411         fs::metadata(self).is_ok()
2412     }
2413
2414     /// Returns `true` if the path exists on disk and is pointing at a regular file.
2415     ///
2416     /// This function will traverse symbolic links to query information about the
2417     /// destination file. In case of broken symbolic links this will return `false`.
2418     ///
2419     /// If you cannot access the directory containing the file, e.g., because of a
2420     /// permission error, this will return `false`.
2421     ///
2422     /// # Examples
2423     ///
2424     /// ```no_run
2425     /// use std::path::Path;
2426     /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2427     /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2428     /// ```
2429     ///
2430     /// # See Also
2431     ///
2432     /// This is a convenience function that coerces errors to false. If you want to
2433     /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2434     /// [`fs::Metadata::is_file`] if it was [`Ok`].
2435     ///
2436     /// When the goal is simply to read from (or write to) the source, the most
2437     /// reliable way to test the source can be read (or written to) is to open
2438     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2439     /// a Unix-like system for example. See [`fs::File::open`] or
2440     /// [`fs::OpenOptions::open`] for more information.
2441     #[stable(feature = "path_ext", since = "1.5.0")]
2442     pub fn is_file(&self) -> bool {
2443         fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2444     }
2445
2446     /// Returns `true` if the path exists on disk and is pointing at a directory.
2447     ///
2448     /// This function will traverse symbolic links to query information about the
2449     /// destination file. In case of broken symbolic links this will return `false`.
2450     ///
2451     /// If you cannot access the directory containing the file, e.g., because of a
2452     /// permission error, this will return `false`.
2453     ///
2454     /// # Examples
2455     ///
2456     /// ```no_run
2457     /// use std::path::Path;
2458     /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2459     /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2460     /// ```
2461     ///
2462     /// # See Also
2463     ///
2464     /// This is a convenience function that coerces errors to false. If you want to
2465     /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2466     /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2467     #[stable(feature = "path_ext", since = "1.5.0")]
2468     pub fn is_dir(&self) -> bool {
2469         fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2470     }
2471
2472     /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2473     /// allocating.
2474     #[stable(feature = "into_boxed_path", since = "1.20.0")]
2475     pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2476         let rw = Box::into_raw(self) as *mut OsStr;
2477         let inner = unsafe { Box::from_raw(rw) };
2478         PathBuf { inner: OsString::from(inner) }
2479     }
2480 }
2481
2482 #[stable(feature = "rust1", since = "1.0.0")]
2483 impl AsRef<OsStr> for Path {
2484     fn as_ref(&self) -> &OsStr {
2485         &self.inner
2486     }
2487 }
2488
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl fmt::Debug for Path {
2491     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2492         fmt::Debug::fmt(&self.inner, formatter)
2493     }
2494 }
2495
2496 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2497 ///
2498 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2499 /// [`Display`] trait in a way that mitigates that. It is created by the
2500 /// [`display`](Path::display) method on [`Path`].
2501 ///
2502 /// # Examples
2503 ///
2504 /// ```
2505 /// use std::path::Path;
2506 ///
2507 /// let path = Path::new("/tmp/foo.rs");
2508 ///
2509 /// println!("{}", path.display());
2510 /// ```
2511 ///
2512 /// [`Display`]: fmt::Display
2513 /// [`format!`]: crate::format
2514 #[stable(feature = "rust1", since = "1.0.0")]
2515 pub struct Display<'a> {
2516     path: &'a Path,
2517 }
2518
2519 #[stable(feature = "rust1", since = "1.0.0")]
2520 impl fmt::Debug for Display<'_> {
2521     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2522         fmt::Debug::fmt(&self.path, f)
2523     }
2524 }
2525
2526 #[stable(feature = "rust1", since = "1.0.0")]
2527 impl fmt::Display for Display<'_> {
2528     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2529         self.path.inner.display(f)
2530     }
2531 }
2532
2533 #[stable(feature = "rust1", since = "1.0.0")]
2534 impl cmp::PartialEq for Path {
2535     fn eq(&self, other: &Path) -> bool {
2536         self.components().eq(other.components())
2537     }
2538 }
2539
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 impl Hash for Path {
2542     fn hash<H: Hasher>(&self, h: &mut H) {
2543         for component in self.components() {
2544             component.hash(h);
2545         }
2546     }
2547 }
2548
2549 #[stable(feature = "rust1", since = "1.0.0")]
2550 impl cmp::Eq for Path {}
2551
2552 #[stable(feature = "rust1", since = "1.0.0")]
2553 impl cmp::PartialOrd for Path {
2554     fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2555         self.components().partial_cmp(other.components())
2556     }
2557 }
2558
2559 #[stable(feature = "rust1", since = "1.0.0")]
2560 impl cmp::Ord for Path {
2561     fn cmp(&self, other: &Path) -> cmp::Ordering {
2562         self.components().cmp(other.components())
2563     }
2564 }
2565
2566 #[stable(feature = "rust1", since = "1.0.0")]
2567 impl AsRef<Path> for Path {
2568     fn as_ref(&self) -> &Path {
2569         self
2570     }
2571 }
2572
2573 #[stable(feature = "rust1", since = "1.0.0")]
2574 impl AsRef<Path> for OsStr {
2575     fn as_ref(&self) -> &Path {
2576         Path::new(self)
2577     }
2578 }
2579
2580 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2581 impl AsRef<Path> for Cow<'_, OsStr> {
2582     fn as_ref(&self) -> &Path {
2583         Path::new(self)
2584     }
2585 }
2586
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 impl AsRef<Path> for OsString {
2589     fn as_ref(&self) -> &Path {
2590         Path::new(self)
2591     }
2592 }
2593
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 impl AsRef<Path> for str {
2596     #[inline]
2597     fn as_ref(&self) -> &Path {
2598         Path::new(self)
2599     }
2600 }
2601
2602 #[stable(feature = "rust1", since = "1.0.0")]
2603 impl AsRef<Path> for String {
2604     fn as_ref(&self) -> &Path {
2605         Path::new(self)
2606     }
2607 }
2608
2609 #[stable(feature = "rust1", since = "1.0.0")]
2610 impl AsRef<Path> for PathBuf {
2611     #[inline]
2612     fn as_ref(&self) -> &Path {
2613         self
2614     }
2615 }
2616
2617 #[stable(feature = "path_into_iter", since = "1.6.0")]
2618 impl<'a> IntoIterator for &'a PathBuf {
2619     type Item = &'a OsStr;
2620     type IntoIter = Iter<'a>;
2621     fn into_iter(self) -> Iter<'a> {
2622         self.iter()
2623     }
2624 }
2625
2626 #[stable(feature = "path_into_iter", since = "1.6.0")]
2627 impl<'a> IntoIterator for &'a Path {
2628     type Item = &'a OsStr;
2629     type IntoIter = Iter<'a>;
2630     fn into_iter(self) -> Iter<'a> {
2631         self.iter()
2632     }
2633 }
2634
2635 macro_rules! impl_cmp {
2636     ($lhs:ty, $rhs: ty) => {
2637         #[stable(feature = "partialeq_path", since = "1.6.0")]
2638         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2639             #[inline]
2640             fn eq(&self, other: &$rhs) -> bool {
2641                 <Path as PartialEq>::eq(self, other)
2642             }
2643         }
2644
2645         #[stable(feature = "partialeq_path", since = "1.6.0")]
2646         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2647             #[inline]
2648             fn eq(&self, other: &$lhs) -> bool {
2649                 <Path as PartialEq>::eq(self, other)
2650             }
2651         }
2652
2653         #[stable(feature = "cmp_path", since = "1.8.0")]
2654         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2655             #[inline]
2656             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2657                 <Path as PartialOrd>::partial_cmp(self, other)
2658             }
2659         }
2660
2661         #[stable(feature = "cmp_path", since = "1.8.0")]
2662         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2663             #[inline]
2664             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2665                 <Path as PartialOrd>::partial_cmp(self, other)
2666             }
2667         }
2668     };
2669 }
2670
2671 impl_cmp!(PathBuf, Path);
2672 impl_cmp!(PathBuf, &'a Path);
2673 impl_cmp!(Cow<'a, Path>, Path);
2674 impl_cmp!(Cow<'a, Path>, &'b Path);
2675 impl_cmp!(Cow<'a, Path>, PathBuf);
2676
2677 macro_rules! impl_cmp_os_str {
2678     ($lhs:ty, $rhs: ty) => {
2679         #[stable(feature = "cmp_path", since = "1.8.0")]
2680         impl<'a, 'b> PartialEq<$rhs> for $lhs {
2681             #[inline]
2682             fn eq(&self, other: &$rhs) -> bool {
2683                 <Path as PartialEq>::eq(self, other.as_ref())
2684             }
2685         }
2686
2687         #[stable(feature = "cmp_path", since = "1.8.0")]
2688         impl<'a, 'b> PartialEq<$lhs> for $rhs {
2689             #[inline]
2690             fn eq(&self, other: &$lhs) -> bool {
2691                 <Path as PartialEq>::eq(self.as_ref(), other)
2692             }
2693         }
2694
2695         #[stable(feature = "cmp_path", since = "1.8.0")]
2696         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2697             #[inline]
2698             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2699                 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2700             }
2701         }
2702
2703         #[stable(feature = "cmp_path", since = "1.8.0")]
2704         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2705             #[inline]
2706             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2707                 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2708             }
2709         }
2710     };
2711 }
2712
2713 impl_cmp_os_str!(PathBuf, OsStr);
2714 impl_cmp_os_str!(PathBuf, &'a OsStr);
2715 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2716 impl_cmp_os_str!(PathBuf, OsString);
2717 impl_cmp_os_str!(Path, OsStr);
2718 impl_cmp_os_str!(Path, &'a OsStr);
2719 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2720 impl_cmp_os_str!(Path, OsString);
2721 impl_cmp_os_str!(&'a Path, OsStr);
2722 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2723 impl_cmp_os_str!(&'a Path, OsString);
2724 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2725 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2726 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2727
2728 #[stable(since = "1.7.0", feature = "strip_prefix")]
2729 impl fmt::Display for StripPrefixError {
2730     #[allow(deprecated, deprecated_in_future)]
2731     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2732         self.description().fmt(f)
2733     }
2734 }
2735
2736 #[stable(since = "1.7.0", feature = "strip_prefix")]
2737 impl Error for StripPrefixError {
2738     #[allow(deprecated)]
2739     fn description(&self) -> &str {
2740         "prefix not found"
2741     }
2742 }