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