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