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