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