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