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