1 //! Cross-platform path manipulation.
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.
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.
15 //! ## Case sensitivity
17 //! Unless otherwise indicated path methods that do not access the filesystem,
18 //! such as [`Path::starts_with`] and [`Path::ends_with`], are case sensitive no
19 //! matter the platform or filesystem. An exception to this is made for Windows
24 //! Path manipulation includes both parsing components from slices and building
27 //! To parse a path, you can create a [`Path`] slice from a [`str`]
28 //! slice and start asking questions:
31 //! use std::path::Path;
32 //! use std::ffi::OsStr;
34 //! let path = Path::new("/tmp/foo/bar.txt");
36 //! let parent = path.parent();
37 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
39 //! let file_stem = path.file_stem();
40 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
42 //! let extension = path.extension();
43 //! assert_eq!(extension, Some(OsStr::new("txt")));
46 //! To build or modify paths, use [`PathBuf`]:
49 //! use std::path::PathBuf;
51 //! // This way works...
52 //! let mut path = PathBuf::from("c:\\");
54 //! path.push("windows");
55 //! path.push("system32");
57 //! path.set_extension("dll");
59 //! // ... but push is best used if you don't know everything up
60 //! // front. If you do, this way is better:
61 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
64 //! [`components`]: Path::components
65 //! [`push`]: PathBuf::push
67 #![stable(feature = "rust1", since = "1.0.0")]
68 #![deny(unsafe_op_in_unsafe_fn)]
73 use crate::borrow::{Borrow, Cow};
75 use crate::collections::TryReserveError;
76 use crate::error::Error;
79 use crate::hash::{Hash, Hasher};
81 use crate::iter::{self, FusedIterator};
82 use crate::ops::{self, Deref};
84 use crate::str::FromStr;
87 use crate::ffi::{OsStr, OsString};
89 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
91 ////////////////////////////////////////////////////////////////////////////////
93 ////////////////////////////////////////////////////////////////////////////////
95 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
96 // taking advantage of the fact that OsStr always encodes ASCII characters
97 // as-is. Eventually, this transmutation should be replaced by direct uses of
98 // OsStr APIs for parsing, but it will take a while for those to become
101 ////////////////////////////////////////////////////////////////////////////////
103 ////////////////////////////////////////////////////////////////////////////////
105 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
107 /// Windows uses a variety of path prefix styles, including references to drive
108 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
109 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
110 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
111 /// no normalization is performed.
116 /// use std::path::{Component, Path, Prefix};
117 /// use std::path::Prefix::*;
118 /// use std::ffi::OsStr;
120 /// fn get_path_prefix(s: &str) -> Prefix {
121 /// let path = Path::new(s);
122 /// match path.components().next().unwrap() {
123 /// Component::Prefix(prefix_component) => prefix_component.kind(),
128 /// # if cfg!(windows) {
129 /// assert_eq!(Verbatim(OsStr::new("pictures")),
130 /// get_path_prefix(r"\\?\pictures\kittens"));
131 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
132 /// get_path_prefix(r"\\?\UNC\server\share"));
133 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
134 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
135 /// get_path_prefix(r"\\.\BrainInterface"));
136 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
137 /// get_path_prefix(r"\\server\share"));
138 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
141 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub enum Prefix<'a> {
144 /// Verbatim prefix, e.g., `\\?\cat_pics`.
146 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
148 #[stable(feature = "rust1", since = "1.0.0")]
149 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
151 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
152 /// e.g., `\\?\UNC\server\share`.
154 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
155 /// server's hostname and a share name.
156 #[stable(feature = "rust1", since = "1.0.0")]
158 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
159 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
162 /// Verbatim disk prefix, e.g., `\\?\C:`.
164 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
165 /// drive letter and `:`.
166 #[stable(feature = "rust1", since = "1.0.0")]
167 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
169 /// Device namespace prefix, e.g., `\\.\COM42`.
171 /// Device namespace prefixes consist of `\\.\` immediately followed by the
173 #[stable(feature = "rust1", since = "1.0.0")]
174 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
176 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
177 /// `\\server\share`.
179 /// UNC prefixes consist of the server's hostname and a share name.
180 #[stable(feature = "rust1", since = "1.0.0")]
182 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
183 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
186 /// Prefix `C:` for the given disk drive.
187 #[stable(feature = "rust1", since = "1.0.0")]
188 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
191 impl<'a> Prefix<'a> {
193 fn len(&self) -> usize {
195 fn os_str_len(s: &OsStr) -> usize {
196 os_str_as_u8_slice(s).len()
199 Verbatim(x) => 4 + os_str_len(x),
200 VerbatimUNC(x, y) => {
201 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
203 VerbatimDisk(_) => 6,
204 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
205 DeviceNS(x) => 4 + os_str_len(x),
210 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
215 /// use std::path::Prefix::*;
216 /// use std::ffi::OsStr;
218 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
219 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
220 /// assert!(VerbatimDisk(b'C').is_verbatim());
221 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
222 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
223 /// assert!(!Disk(b'C').is_verbatim());
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn is_verbatim(&self) -> bool {
230 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
234 fn is_drive(&self) -> bool {
235 matches!(*self, Prefix::Disk(_))
239 fn has_implicit_root(&self) -> bool {
244 ////////////////////////////////////////////////////////////////////////////////
245 // Exposed parsing helpers
246 ////////////////////////////////////////////////////////////////////////////////
248 /// Determines whether the character is one of the permitted path
249 /// separators for the current platform.
256 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
257 /// assert!(!path::is_separator('❤'));
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn is_separator(c: char) -> bool {
262 c.is_ascii() && is_sep_byte(c as u8)
265 /// The primary separator of path components for the current platform.
267 /// For example, `/` on Unix and `\` on Windows.
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
271 ////////////////////////////////////////////////////////////////////////////////
273 ////////////////////////////////////////////////////////////////////////////////
275 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
276 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
277 // `iter` after having exhausted `prefix`.
278 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
280 I: Iterator<Item = Component<'a>> + Clone,
281 J: Iterator<Item = Component<'b>>,
284 let mut iter_next = iter.clone();
285 match (iter_next.next(), prefix.next()) {
286 (Some(ref x), Some(ref y)) if x == y => (),
287 (Some(_), Some(_)) => return None,
288 (Some(_), None) => return Some(iter),
289 (None, None) => return Some(iter),
290 (None, Some(_)) => return None,
296 // See note at the top of this module to understand why these are used:
298 // These casts are safe as OsStr is internally a wrapper around [u8] on all
301 // Note that currently this relies on the special knowledge that libstd has;
302 // these types are single-element structs but are not marked repr(transparent)
303 // or repr(C) which would make these casts allowable outside std.
304 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
305 unsafe { &*(s as *const OsStr as *const [u8]) }
307 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
308 // SAFETY: see the comment of `os_str_as_u8_slice`
309 unsafe { &*(s as *const [u8] as *const OsStr) }
312 // Detect scheme on Redox
313 fn has_redox_scheme(s: &[u8]) -> bool {
314 cfg!(target_os = "redox") && s.contains(&b':')
317 ////////////////////////////////////////////////////////////////////////////////
318 // Cross-platform, iterator-independent parsing
319 ////////////////////////////////////////////////////////////////////////////////
321 /// Says whether the first byte after the prefix is a separator.
322 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
323 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
324 !path.is_empty() && is_sep_byte(path[0])
327 // basic workhorse for splitting stem and extension
328 fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
329 if os_str_as_u8_slice(file) == b".." {
330 return (Some(file), None);
333 // The unsafety here stems from converting between &OsStr and &[u8]
334 // and back. This is safe to do because (1) we only look at ASCII
335 // contents of the encoding and (2) new &OsStr values are produced
336 // only from ASCII-bounded slices of existing &OsStr values.
337 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
338 let after = iter.next();
339 let before = iter.next();
340 if before == Some(b"") {
343 unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
347 fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
348 let slice = os_str_as_u8_slice(file);
353 // The unsafety here stems from converting between &OsStr and &[u8]
354 // and back. This is safe to do because (1) we only look at ASCII
355 // contents of the encoding and (2) new &OsStr values are produced
356 // only from ASCII-bounded slices of existing &OsStr values.
357 let i = match slice[1..].iter().position(|b| *b == b'.') {
359 None => return (file, None),
361 let before = &slice[..i];
362 let after = &slice[i + 1..];
363 unsafe { (u8_slice_as_os_str(before), Some(u8_slice_as_os_str(after))) }
366 ////////////////////////////////////////////////////////////////////////////////
367 // The core iterators
368 ////////////////////////////////////////////////////////////////////////////////
370 /// Component parsing works by a double-ended state machine; the cursors at the
371 /// front and back of the path each keep track of what parts of the path have
372 /// been consumed so far.
374 /// Going front to back, a path is made up of a prefix, a starting
375 /// directory component, and a body (of normal components)
376 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
379 StartDir = 1, // / or . or nothing
380 Body = 2, // foo/bar/baz
384 /// A structure wrapping a Windows path prefix as well as its unparsed string
387 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
388 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
389 /// returned by [`as_os_str`].
391 /// Instances of this `struct` can be obtained by matching against the
392 /// [`Prefix` variant] on [`Component`].
394 /// Does not occur on Unix.
399 /// # if cfg!(windows) {
400 /// use std::path::{Component, Path, Prefix};
401 /// use std::ffi::OsStr;
403 /// let path = Path::new(r"c:\you\later\");
404 /// match path.components().next().unwrap() {
405 /// Component::Prefix(prefix_component) => {
406 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
407 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
409 /// _ => unreachable!(),
414 /// [`as_os_str`]: PrefixComponent::as_os_str
415 /// [`kind`]: PrefixComponent::kind
416 /// [`Prefix` variant]: Component::Prefix
417 #[stable(feature = "rust1", since = "1.0.0")]
418 #[derive(Copy, Clone, Eq, Debug)]
419 pub struct PrefixComponent<'a> {
420 /// The prefix as an unparsed `OsStr` slice.
423 /// The parsed prefix data.
427 impl<'a> PrefixComponent<'a> {
428 /// Returns the parsed prefix data.
430 /// See [`Prefix`]'s documentation for more information on the different
431 /// kinds of prefixes.
432 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn kind(&self) -> Prefix<'a> {
439 /// Returns the raw [`OsStr`] slice for this prefix.
440 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn as_os_str(&self) -> &'a OsStr {
448 #[stable(feature = "rust1", since = "1.0.0")]
449 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
451 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
452 cmp::PartialEq::eq(&self.parsed, &other.parsed)
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
459 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
460 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl cmp::Ord for PrefixComponent<'_> {
467 fn cmp(&self, other: &Self) -> cmp::Ordering {
468 cmp::Ord::cmp(&self.parsed, &other.parsed)
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl Hash for PrefixComponent<'_> {
474 fn hash<H: Hasher>(&self, h: &mut H) {
479 /// A single component of a path.
481 /// A `Component` roughly corresponds to a substring between path separators
484 /// This `enum` is created by iterating over [`Components`], which in turn is
485 /// created by the [`components`](Path::components) method on [`Path`].
490 /// use std::path::{Component, Path};
492 /// let path = Path::new("/tmp/foo/bar.txt");
493 /// let components = path.components().collect::<Vec<_>>();
494 /// assert_eq!(&components, &[
495 /// Component::RootDir,
496 /// Component::Normal("tmp".as_ref()),
497 /// Component::Normal("foo".as_ref()),
498 /// Component::Normal("bar.txt".as_ref()),
501 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub enum Component<'a> {
504 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
506 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
509 /// Does not occur on Unix.
510 #[stable(feature = "rust1", since = "1.0.0")]
511 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
513 /// The root directory component, appears after any prefix and before anything else.
515 /// It represents a separator that designates that a path starts from root.
516 #[stable(feature = "rust1", since = "1.0.0")]
519 /// A reference to the current directory, i.e., `.`.
520 #[stable(feature = "rust1", since = "1.0.0")]
523 /// A reference to the parent directory, i.e., `..`.
524 #[stable(feature = "rust1", since = "1.0.0")]
527 /// A normal component, e.g., `a` and `b` in `a/b`.
529 /// This variant is the most common one, it represents references to files
531 #[stable(feature = "rust1", since = "1.0.0")]
532 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
535 impl<'a> Component<'a> {
536 /// Extracts the underlying [`OsStr`] slice.
541 /// use std::path::Path;
543 /// let path = Path::new("./tmp/foo/bar.txt");
544 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
545 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
547 #[must_use = "`self` will be dropped if the result is not used"]
548 #[stable(feature = "rust1", since = "1.0.0")]
549 pub fn as_os_str(self) -> &'a OsStr {
551 Component::Prefix(p) => p.as_os_str(),
552 Component::RootDir => OsStr::new(MAIN_SEP_STR),
553 Component::CurDir => OsStr::new("."),
554 Component::ParentDir => OsStr::new(".."),
555 Component::Normal(path) => path,
560 #[stable(feature = "rust1", since = "1.0.0")]
561 impl AsRef<OsStr> for Component<'_> {
563 fn as_ref(&self) -> &OsStr {
568 #[stable(feature = "path_component_asref", since = "1.25.0")]
569 impl AsRef<Path> for Component<'_> {
571 fn as_ref(&self) -> &Path {
572 self.as_os_str().as_ref()
576 /// An iterator over the [`Component`]s of a [`Path`].
578 /// This `struct` is created by the [`components`] method on [`Path`].
579 /// See its documentation for more.
584 /// use std::path::Path;
586 /// let path = Path::new("/tmp/foo/bar.txt");
588 /// for component in path.components() {
589 /// println!("{:?}", component);
593 /// [`components`]: Path::components
595 #[must_use = "iterators are lazy and do nothing unless consumed"]
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub struct Components<'a> {
598 // The path left to parse components from
601 // The prefix as it was originally parsed, if any
602 prefix: Option<Prefix<'a>>,
604 // true if path *physically* has a root separator; for most Windows
605 // prefixes, it may have a "logical" root separator for the purposes of
606 // normalization, e.g., \\server\share == \\server\share\.
607 has_physical_root: bool,
609 // The iterator is double-ended, and these two states keep track of what has
610 // been produced from either end
615 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
617 /// This `struct` is created by the [`iter`] method on [`Path`].
618 /// See its documentation for more.
620 /// [`iter`]: Path::iter
622 #[must_use = "iterators are lazy and do nothing unless consumed"]
623 #[stable(feature = "rust1", since = "1.0.0")]
624 pub struct Iter<'a> {
625 inner: Components<'a>,
628 #[stable(feature = "path_components_debug", since = "1.13.0")]
629 impl fmt::Debug for Components<'_> {
630 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631 struct DebugHelper<'a>(&'a Path);
633 impl fmt::Debug for DebugHelper<'_> {
634 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635 f.debug_list().entries(self.0.components()).finish()
639 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
643 impl<'a> Components<'a> {
644 // how long is the prefix, if any?
646 fn prefix_len(&self) -> usize {
647 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
651 fn prefix_verbatim(&self) -> bool {
652 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
655 /// how much of the prefix is left from the point of view of iteration?
657 fn prefix_remaining(&self) -> usize {
658 if self.front == State::Prefix { self.prefix_len() } else { 0 }
661 // Given the iteration so far, how much of the pre-State::Body path is left?
663 fn len_before_body(&self) -> usize {
664 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
665 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
666 self.prefix_remaining() + root + cur_dir
669 // is the iteration complete?
671 fn finished(&self) -> bool {
672 self.front == State::Done || self.back == State::Done || self.front > self.back
676 fn is_sep_byte(&self, b: u8) -> bool {
677 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
680 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
685 /// use std::path::Path;
687 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
688 /// components.next();
689 /// components.next();
691 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn as_path(&self) -> &'a Path {
696 let mut comps = self.clone();
697 if comps.front == State::Body {
700 if comps.back == State::Body {
703 unsafe { Path::from_u8_slice(comps.path) }
706 /// Is the *original* path rooted?
707 fn has_root(&self) -> bool {
708 if self.has_physical_root {
711 if let Some(p) = self.prefix {
712 if p.has_implicit_root() {
719 /// Should the normalized path include a leading . ?
720 fn include_cur_dir(&self) -> bool {
724 let mut iter = self.path[self.prefix_len()..].iter();
725 match (iter.next(), iter.next()) {
726 (Some(&b'.'), None) => true,
727 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
732 // parse a given byte sequence into the corresponding path component
733 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
735 b"." if self.prefix_verbatim() => Some(Component::CurDir),
736 b"." => None, // . components are normalized away, except at
737 // the beginning of a path, which is treated
738 // separately via `include_cur_dir`
739 b".." => Some(Component::ParentDir),
741 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
745 // parse a component from the left, saying how many bytes to consume to
746 // remove the component
747 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
748 debug_assert!(self.front == State::Body);
749 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
750 None => (0, self.path),
751 Some(i) => (1, &self.path[..i]),
753 (comp.len() + extra, self.parse_single_component(comp))
756 // parse a component from the right, saying how many bytes to consume to
757 // remove the component
758 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
759 debug_assert!(self.back == State::Body);
760 let start = self.len_before_body();
761 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
762 None => (0, &self.path[start..]),
763 Some(i) => (1, &self.path[start + i + 1..]),
765 (comp.len() + extra, self.parse_single_component(comp))
768 // trim away repeated separators (i.e., empty components) on the left
769 fn trim_left(&mut self) {
770 while !self.path.is_empty() {
771 let (size, comp) = self.parse_next_component();
775 self.path = &self.path[size..];
780 // trim away repeated separators (i.e., empty components) on the right
781 fn trim_right(&mut self) {
782 while self.path.len() > self.len_before_body() {
783 let (size, comp) = self.parse_next_component_back();
787 self.path = &self.path[..self.path.len() - size];
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl AsRef<Path> for Components<'_> {
796 fn as_ref(&self) -> &Path {
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl AsRef<OsStr> for Components<'_> {
804 fn as_ref(&self) -> &OsStr {
805 self.as_path().as_os_str()
809 #[stable(feature = "path_iter_debug", since = "1.13.0")]
810 impl fmt::Debug for Iter<'_> {
811 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812 struct DebugHelper<'a>(&'a Path);
814 impl fmt::Debug for DebugHelper<'_> {
815 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
816 f.debug_list().entries(self.0.iter()).finish()
820 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
825 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
830 /// use std::path::Path;
832 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
836 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
838 #[stable(feature = "rust1", since = "1.0.0")]
841 pub fn as_path(&self) -> &'a Path {
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl AsRef<Path> for Iter<'_> {
849 fn as_ref(&self) -> &Path {
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl AsRef<OsStr> for Iter<'_> {
857 fn as_ref(&self) -> &OsStr {
858 self.as_path().as_os_str()
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<'a> Iterator for Iter<'a> {
864 type Item = &'a OsStr;
867 fn next(&mut self) -> Option<&'a OsStr> {
868 self.inner.next().map(Component::as_os_str)
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a> DoubleEndedIterator for Iter<'a> {
875 fn next_back(&mut self) -> Option<&'a OsStr> {
876 self.inner.next_back().map(Component::as_os_str)
880 #[stable(feature = "fused", since = "1.26.0")]
881 impl FusedIterator for Iter<'_> {}
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<'a> Iterator for Components<'a> {
885 type Item = Component<'a>;
887 fn next(&mut self) -> Option<Component<'a>> {
888 while !self.finished() {
890 State::Prefix if self.prefix_len() > 0 => {
891 self.front = State::StartDir;
892 debug_assert!(self.prefix_len() <= self.path.len());
893 let raw = &self.path[..self.prefix_len()];
894 self.path = &self.path[self.prefix_len()..];
895 return Some(Component::Prefix(PrefixComponent {
896 raw: unsafe { u8_slice_as_os_str(raw) },
897 parsed: self.prefix.unwrap(),
901 self.front = State::StartDir;
904 self.front = State::Body;
905 if self.has_physical_root {
906 debug_assert!(!self.path.is_empty());
907 self.path = &self.path[1..];
908 return Some(Component::RootDir);
909 } else if let Some(p) = self.prefix {
910 if p.has_implicit_root() && !p.is_verbatim() {
911 return Some(Component::RootDir);
913 } else if self.include_cur_dir() {
914 debug_assert!(!self.path.is_empty());
915 self.path = &self.path[1..];
916 return Some(Component::CurDir);
919 State::Body if !self.path.is_empty() => {
920 let (size, comp) = self.parse_next_component();
921 self.path = &self.path[size..];
927 self.front = State::Done;
929 State::Done => unreachable!(),
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<'a> DoubleEndedIterator for Components<'a> {
938 fn next_back(&mut self) -> Option<Component<'a>> {
939 while !self.finished() {
941 State::Body if self.path.len() > self.len_before_body() => {
942 let (size, comp) = self.parse_next_component_back();
943 self.path = &self.path[..self.path.len() - size];
949 self.back = State::StartDir;
952 self.back = State::Prefix;
953 if self.has_physical_root {
954 self.path = &self.path[..self.path.len() - 1];
955 return Some(Component::RootDir);
956 } else if let Some(p) = self.prefix {
957 if p.has_implicit_root() && !p.is_verbatim() {
958 return Some(Component::RootDir);
960 } else if self.include_cur_dir() {
961 self.path = &self.path[..self.path.len() - 1];
962 return Some(Component::CurDir);
965 State::Prefix if self.prefix_len() > 0 => {
966 self.back = State::Done;
967 return Some(Component::Prefix(PrefixComponent {
968 raw: unsafe { u8_slice_as_os_str(self.path) },
969 parsed: self.prefix.unwrap(),
973 self.back = State::Done;
976 State::Done => unreachable!(),
983 #[stable(feature = "fused", since = "1.26.0")]
984 impl FusedIterator for Components<'_> {}
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<'a> cmp::PartialEq for Components<'a> {
989 fn eq(&self, other: &Components<'a>) -> bool {
990 let Components { path: _, front: _, back: _, has_physical_root: _, prefix: _ } = self;
992 // Fast path for exact matches, e.g. for hashmap lookups.
993 // Don't explicitly compare the prefix or has_physical_root fields since they'll
994 // either be covered by the `path` buffer or are only relevant for `prefix_verbatim()`.
995 if self.path.len() == other.path.len()
996 && self.front == other.front
997 && self.back == State::Body
998 && other.back == State::Body
999 && self.prefix_verbatim() == other.prefix_verbatim()
1001 // possible future improvement: this could bail out earlier if there were a
1002 // reverse memcmp/bcmp comparing back to front
1003 if self.path == other.path {
1008 // compare back to front since absolute paths often share long prefixes
1009 Iterator::eq(self.clone().rev(), other.clone().rev())
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl cmp::Eq for Components<'_> {}
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<'a> cmp::PartialOrd for Components<'a> {
1019 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1020 Some(compare_components(self.clone(), other.clone()))
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl cmp::Ord for Components<'_> {
1027 fn cmp(&self, other: &Self) -> cmp::Ordering {
1028 compare_components(self.clone(), other.clone())
1032 fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cmp::Ordering {
1033 // Fast path for long shared prefixes
1035 // - compare raw bytes to find first mismatch
1036 // - backtrack to find separator before mismatch to avoid ambiguous parsings of '.' or '..' characters
1037 // - if found update state to only do a component-wise comparison on the remainder,
1038 // otherwise do it on the full path
1040 // The fast path isn't taken for paths with a PrefixComponent to avoid backtracking into
1041 // the middle of one
1042 if left.prefix.is_none() && right.prefix.is_none() && left.front == right.front {
1043 // possible future improvement: a [u8]::first_mismatch simd implementation
1044 let first_difference = match left.path.iter().zip(right.path).position(|(&a, &b)| a != b) {
1045 None if left.path.len() == right.path.len() => return cmp::Ordering::Equal,
1046 None => left.path.len().min(right.path.len()),
1050 if let Some(previous_sep) =
1051 left.path[..first_difference].iter().rposition(|&b| left.is_sep_byte(b))
1053 let mismatched_component_start = previous_sep + 1;
1054 left.path = &left.path[mismatched_component_start..];
1055 left.front = State::Body;
1056 right.path = &right.path[mismatched_component_start..];
1057 right.front = State::Body;
1061 Iterator::cmp(left, right)
1064 /// An iterator over [`Path`] and its ancestors.
1066 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1067 /// See its documentation for more.
1072 /// use std::path::Path;
1074 /// let path = Path::new("/foo/bar");
1076 /// for ancestor in path.ancestors() {
1077 /// println!("{}", ancestor.display());
1081 /// [`ancestors`]: Path::ancestors
1082 #[derive(Copy, Clone, Debug)]
1083 #[must_use = "iterators are lazy and do nothing unless consumed"]
1084 #[stable(feature = "path_ancestors", since = "1.28.0")]
1085 pub struct Ancestors<'a> {
1086 next: Option<&'a Path>,
1089 #[stable(feature = "path_ancestors", since = "1.28.0")]
1090 impl<'a> Iterator for Ancestors<'a> {
1091 type Item = &'a Path;
1094 fn next(&mut self) -> Option<Self::Item> {
1095 let next = self.next;
1096 self.next = next.and_then(Path::parent);
1101 #[stable(feature = "path_ancestors", since = "1.28.0")]
1102 impl FusedIterator for Ancestors<'_> {}
1104 ////////////////////////////////////////////////////////////////////////////////
1105 // Basic types and traits
1106 ////////////////////////////////////////////////////////////////////////////////
1108 /// An owned, mutable path (akin to [`String`]).
1110 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1111 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1112 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1114 /// [`push`]: PathBuf::push
1115 /// [`set_extension`]: PathBuf::set_extension
1117 /// More details about the overall approach can be found in
1118 /// the [module documentation](self).
1122 /// You can use [`push`] to build up a `PathBuf` from
1126 /// use std::path::PathBuf;
1128 /// let mut path = PathBuf::new();
1130 /// path.push(r"C:\");
1131 /// path.push("windows");
1132 /// path.push("system32");
1134 /// path.set_extension("dll");
1137 /// However, [`push`] is best used for dynamic situations. This is a better way
1138 /// to do this when you know all of the components ahead of time:
1141 /// use std::path::PathBuf;
1143 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1146 /// We can still do better than this! Since these are all strings, we can use
1150 /// use std::path::PathBuf;
1152 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1155 /// Which method works best depends on what kind of situation you're in.
1156 #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1157 #[stable(feature = "rust1", since = "1.0.0")]
1159 // `PathBuf::as_mut_vec` current implementation relies
1160 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1161 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1162 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1163 // not documented and must not be relied upon.
1164 pub struct PathBuf {
1170 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1171 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1174 /// Allocates an empty `PathBuf`.
1179 /// use std::path::PathBuf;
1181 /// let path = PathBuf::new();
1183 #[stable(feature = "rust1", since = "1.0.0")]
1186 pub fn new() -> PathBuf {
1187 PathBuf { inner: OsString::new() }
1190 /// Creates a new `PathBuf` with a given capacity used to create the
1191 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1196 /// use std::path::PathBuf;
1198 /// let mut path = PathBuf::with_capacity(10);
1199 /// let capacity = path.capacity();
1201 /// // This push is done without reallocating
1202 /// path.push(r"C:\");
1204 /// assert_eq!(capacity, path.capacity());
1207 /// [`with_capacity`]: OsString::with_capacity
1208 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1211 pub fn with_capacity(capacity: usize) -> PathBuf {
1212 PathBuf { inner: OsString::with_capacity(capacity) }
1215 /// Coerces to a [`Path`] slice.
1220 /// use std::path::{Path, PathBuf};
1222 /// let p = PathBuf::from("/test");
1223 /// assert_eq!(Path::new("/test"), p.as_path());
1225 #[stable(feature = "rust1", since = "1.0.0")]
1228 pub fn as_path(&self) -> &Path {
1232 /// Extends `self` with `path`.
1234 /// If `path` is absolute, it replaces the current path.
1238 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1239 /// replaces everything except for the prefix (if any) of `self`.
1240 /// * if `path` has a prefix but no root, it replaces `self`.
1241 /// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
1242 /// and `path` is not empty, the new path is normalized: all references
1243 /// to `.` and `..` are removed.
1247 /// Pushing a relative path extends the existing path:
1250 /// use std::path::PathBuf;
1252 /// let mut path = PathBuf::from("/tmp");
1253 /// path.push("file.bk");
1254 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1257 /// Pushing an absolute path replaces the existing path:
1260 /// use std::path::PathBuf;
1262 /// let mut path = PathBuf::from("/tmp");
1263 /// path.push("/etc");
1264 /// assert_eq!(path, PathBuf::from("/etc"));
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1268 self._push(path.as_ref())
1271 fn _push(&mut self, path: &Path) {
1272 // in general, a separator is needed if the rightmost byte is not a separator
1273 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1275 // in the special case of `C:` on Windows, do *not* add a separator
1276 let comps = self.components();
1278 if comps.prefix_len() > 0
1279 && comps.prefix_len() == comps.path.len()
1280 && comps.prefix.unwrap().is_drive()
1285 // absolute `path` replaces `self`
1286 if path.is_absolute() || path.prefix().is_some() {
1287 self.as_mut_vec().truncate(0);
1289 // verbatim paths need . and .. removed
1290 } else if comps.prefix_verbatim() && !path.inner.is_empty() {
1291 let mut buf: Vec<_> = comps.collect();
1292 for c in path.components() {
1294 Component::RootDir => {
1298 Component::CurDir => (),
1299 Component::ParentDir => {
1300 if let Some(Component::Normal(_)) = buf.last() {
1308 let mut res = OsString::new();
1309 let mut need_sep = false;
1312 if need_sep && c != Component::RootDir {
1313 res.push(MAIN_SEP_STR);
1315 res.push(c.as_os_str());
1317 need_sep = match c {
1318 Component::RootDir => false,
1319 Component::Prefix(prefix) => {
1320 !prefix.parsed.is_drive() && prefix.parsed.len() > 0
1329 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1330 } else if path.has_root() {
1331 let prefix_len = self.components().prefix_remaining();
1332 self.as_mut_vec().truncate(prefix_len);
1334 // `path` is a pure relative path
1335 } else if need_sep {
1336 self.inner.push(MAIN_SEP_STR);
1339 self.inner.push(path);
1342 /// Truncates `self` to [`self.parent`].
1344 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1345 /// Otherwise, returns `true`.
1347 /// [`self.parent`]: Path::parent
1352 /// use std::path::{Path, PathBuf};
1354 /// let mut p = PathBuf::from("/spirited/away.rs");
1357 /// assert_eq!(Path::new("/spirited"), p);
1359 /// assert_eq!(Path::new("/"), p);
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 pub fn pop(&mut self) -> bool {
1363 match self.parent().map(|p| p.as_u8_slice().len()) {
1365 self.as_mut_vec().truncate(len);
1372 /// Updates [`self.file_name`] to `file_name`.
1374 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1377 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1378 /// `file_name`. The new path will be a sibling of the original path.
1379 /// (That is, it will have the same parent.)
1381 /// [`self.file_name`]: Path::file_name
1382 /// [`pop`]: PathBuf::pop
1387 /// use std::path::PathBuf;
1389 /// let mut buf = PathBuf::from("/");
1390 /// assert!(buf.file_name() == None);
1391 /// buf.set_file_name("bar");
1392 /// assert!(buf == PathBuf::from("/bar"));
1393 /// assert!(buf.file_name().is_some());
1394 /// buf.set_file_name("baz.txt");
1395 /// assert!(buf == PathBuf::from("/baz.txt"));
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1399 self._set_file_name(file_name.as_ref())
1402 fn _set_file_name(&mut self, file_name: &OsStr) {
1403 if self.file_name().is_some() {
1404 let popped = self.pop();
1405 debug_assert!(popped);
1407 self.push(file_name);
1410 /// Updates [`self.extension`] to `extension`.
1412 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1413 /// returns `true` and updates the extension otherwise.
1415 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1418 /// [`self.file_name`]: Path::file_name
1419 /// [`self.extension`]: Path::extension
1424 /// use std::path::{Path, PathBuf};
1426 /// let mut p = PathBuf::from("/feel/the");
1428 /// p.set_extension("force");
1429 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1431 /// p.set_extension("dark_side");
1432 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1436 self._set_extension(extension.as_ref())
1439 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1440 let file_stem = match self.file_stem() {
1441 None => return false,
1442 Some(f) => os_str_as_u8_slice(f),
1445 // truncate until right after the file stem
1446 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1447 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1448 let v = self.as_mut_vec();
1449 v.truncate(end_file_stem.wrapping_sub(start));
1451 // add the new extension, if any
1452 let new = os_str_as_u8_slice(extension);
1453 if !new.is_empty() {
1454 v.reserve_exact(new.len() + 1);
1456 v.extend_from_slice(new);
1462 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1467 /// use std::path::PathBuf;
1469 /// let p = PathBuf::from("/the/head");
1470 /// let os_str = p.into_os_string();
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 #[must_use = "`self` will be dropped if the result is not used"]
1475 pub fn into_os_string(self) -> OsString {
1479 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1480 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1481 #[must_use = "`self` will be dropped if the result is not used"]
1483 pub fn into_boxed_path(self) -> Box<Path> {
1484 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1485 unsafe { Box::from_raw(rw) }
1488 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1490 /// [`capacity`]: OsString::capacity
1491 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1494 pub fn capacity(&self) -> usize {
1495 self.inner.capacity()
1498 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1500 /// [`clear`]: OsString::clear
1501 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1503 pub fn clear(&mut self) {
1507 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1509 /// [`reserve`]: OsString::reserve
1510 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1512 pub fn reserve(&mut self, additional: usize) {
1513 self.inner.reserve(additional)
1516 /// Invokes [`try_reserve`] on the underlying instance of [`OsString`].
1518 /// [`try_reserve`]: OsString::try_reserve
1519 #[unstable(feature = "try_reserve_2", issue = "91789")]
1521 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1522 self.inner.try_reserve(additional)
1525 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1527 /// [`reserve_exact`]: OsString::reserve_exact
1528 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1530 pub fn reserve_exact(&mut self, additional: usize) {
1531 self.inner.reserve_exact(additional)
1534 /// Invokes [`try_reserve_exact`] on the underlying instance of [`OsString`].
1536 /// [`try_reserve_exact`]: OsString::try_reserve_exact
1537 #[unstable(feature = "try_reserve_2", issue = "91789")]
1539 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1540 self.inner.try_reserve_exact(additional)
1543 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1545 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1546 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1548 pub fn shrink_to_fit(&mut self) {
1549 self.inner.shrink_to_fit()
1552 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1554 /// [`shrink_to`]: OsString::shrink_to
1555 #[stable(feature = "shrink_to", since = "1.56.0")]
1557 pub fn shrink_to(&mut self, min_capacity: usize) {
1558 self.inner.shrink_to(min_capacity)
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl Clone for PathBuf {
1565 fn clone(&self) -> Self {
1566 PathBuf { inner: self.inner.clone() }
1570 fn clone_from(&mut self, source: &Self) {
1571 self.inner.clone_from(&source.inner)
1575 #[stable(feature = "box_from_path", since = "1.17.0")]
1576 impl From<&Path> for Box<Path> {
1577 /// Creates a boxed [`Path`] from a reference.
1579 /// This will allocate and clone `path` to it.
1580 fn from(path: &Path) -> Box<Path> {
1581 let boxed: Box<OsStr> = path.inner.into();
1582 let rw = Box::into_raw(boxed) as *mut Path;
1583 unsafe { Box::from_raw(rw) }
1587 #[stable(feature = "box_from_cow", since = "1.45.0")]
1588 impl From<Cow<'_, Path>> for Box<Path> {
1589 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1591 /// Converting from a `Cow::Owned` does not clone or allocate.
1593 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1595 Cow::Borrowed(path) => Box::from(path),
1596 Cow::Owned(path) => Box::from(path),
1601 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1602 impl From<Box<Path>> for PathBuf {
1603 /// Converts a `Box<Path>` into a `PathBuf`
1605 /// This conversion does not allocate or copy memory.
1607 fn from(boxed: Box<Path>) -> PathBuf {
1608 boxed.into_path_buf()
1612 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1613 impl From<PathBuf> for Box<Path> {
1614 /// Converts a `PathBuf` into a `Box<Path>`
1616 /// This conversion currently should not allocate memory,
1617 /// but this behavior is not guaranteed on all platforms or in all future versions.
1619 fn from(p: PathBuf) -> Box<Path> {
1624 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1625 impl Clone for Box<Path> {
1627 fn clone(&self) -> Self {
1628 self.to_path_buf().into_boxed_path()
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1634 /// Converts a borrowed `OsStr` to a `PathBuf`.
1636 /// Allocates a [`PathBuf`] and copies the data into it.
1638 fn from(s: &T) -> PathBuf {
1639 PathBuf::from(s.as_ref().to_os_string())
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl From<OsString> for PathBuf {
1645 /// Converts an [`OsString`] into a [`PathBuf`]
1647 /// This conversion does not allocate or copy memory.
1649 fn from(s: OsString) -> PathBuf {
1650 PathBuf { inner: s }
1654 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1655 impl From<PathBuf> for OsString {
1656 /// Converts a [`PathBuf`] into an [`OsString`]
1658 /// This conversion does not allocate or copy memory.
1660 fn from(path_buf: PathBuf) -> OsString {
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl From<String> for PathBuf {
1667 /// Converts a [`String`] into a [`PathBuf`]
1669 /// This conversion does not allocate or copy memory.
1671 fn from(s: String) -> PathBuf {
1672 PathBuf::from(OsString::from(s))
1676 #[stable(feature = "path_from_str", since = "1.32.0")]
1677 impl FromStr for PathBuf {
1678 type Err = core::convert::Infallible;
1681 fn from_str(s: &str) -> Result<Self, Self::Err> {
1682 Ok(PathBuf::from(s))
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1688 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1689 let mut buf = PathBuf::new();
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1697 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1698 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1702 fn extend_one(&mut self, p: P) {
1703 self.push(p.as_ref());
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 impl fmt::Debug for PathBuf {
1709 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1710 fmt::Debug::fmt(&**self, formatter)
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl ops::Deref for PathBuf {
1718 fn deref(&self) -> &Path {
1719 Path::new(&self.inner)
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 impl Borrow<Path> for PathBuf {
1726 fn borrow(&self) -> &Path {
1731 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1732 impl Default for PathBuf {
1734 fn default() -> Self {
1739 #[stable(feature = "cow_from_path", since = "1.6.0")]
1740 impl<'a> From<&'a Path> for Cow<'a, Path> {
1741 /// Creates a clone-on-write pointer from a reference to
1744 /// This conversion does not clone or allocate.
1746 fn from(s: &'a Path) -> Cow<'a, Path> {
1751 #[stable(feature = "cow_from_path", since = "1.6.0")]
1752 impl<'a> From<PathBuf> for Cow<'a, Path> {
1753 /// Creates a clone-on-write pointer from an owned
1754 /// instance of [`PathBuf`].
1756 /// This conversion does not clone or allocate.
1758 fn from(s: PathBuf) -> Cow<'a, Path> {
1763 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1764 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1765 /// Creates a clone-on-write pointer from a reference to
1768 /// This conversion does not clone or allocate.
1770 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1771 Cow::Borrowed(p.as_path())
1775 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1776 impl<'a> From<Cow<'a, Path>> for PathBuf {
1777 /// Converts a clone-on-write pointer to an owned path.
1779 /// Converting from a `Cow::Owned` does not clone or allocate.
1781 fn from(p: Cow<'a, Path>) -> Self {
1786 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1787 impl From<PathBuf> for Arc<Path> {
1788 /// Converts a [`PathBuf`] into an <code>[Arc]<[Path]></code> by moving the [`PathBuf`] data
1789 /// into a new [`Arc`] buffer.
1791 fn from(s: PathBuf) -> Arc<Path> {
1792 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1793 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1797 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1798 impl From<&Path> for Arc<Path> {
1799 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
1801 fn from(s: &Path) -> Arc<Path> {
1802 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1803 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1807 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1808 impl From<PathBuf> for Rc<Path> {
1809 /// Converts a [`PathBuf`] into an <code>[Rc]<[Path]></code> by moving the [`PathBuf`] data into
1810 /// a new [`Rc`] buffer.
1812 fn from(s: PathBuf) -> Rc<Path> {
1813 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1814 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1818 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1819 impl From<&Path> for Rc<Path> {
1820 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new [`Rc`] buffer.
1822 fn from(s: &Path) -> Rc<Path> {
1823 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1824 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 impl ToOwned for Path {
1830 type Owned = PathBuf;
1832 fn to_owned(&self) -> PathBuf {
1836 fn clone_into(&self, target: &mut PathBuf) {
1837 self.inner.clone_into(&mut target.inner);
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 impl cmp::PartialEq for PathBuf {
1844 fn eq(&self, other: &PathBuf) -> bool {
1845 self.components() == other.components()
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 impl Hash for PathBuf {
1851 fn hash<H: Hasher>(&self, h: &mut H) {
1852 self.as_path().hash(h)
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl cmp::Eq for PathBuf {}
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 impl cmp::PartialOrd for PathBuf {
1862 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1863 Some(compare_components(self.components(), other.components()))
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 impl cmp::Ord for PathBuf {
1870 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1871 compare_components(self.components(), other.components())
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 impl AsRef<OsStr> for PathBuf {
1878 fn as_ref(&self) -> &OsStr {
1883 /// A slice of a path (akin to [`str`]).
1885 /// This type supports a number of operations for inspecting a path, including
1886 /// breaking the path into its components (separated by `/` on Unix and by either
1887 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1888 /// is absolute, and so on.
1890 /// This is an *unsized* type, meaning that it must always be used behind a
1891 /// pointer like `&` or [`Box`]. For an owned version of this type,
1892 /// see [`PathBuf`].
1894 /// More details about the overall approach can be found in
1895 /// the [module documentation](self).
1900 /// use std::path::Path;
1901 /// use std::ffi::OsStr;
1903 /// // Note: this example does work on Windows
1904 /// let path = Path::new("./foo/bar.txt");
1906 /// let parent = path.parent();
1907 /// assert_eq!(parent, Some(Path::new("./foo")));
1909 /// let file_stem = path.file_stem();
1910 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1912 /// let extension = path.extension();
1913 /// assert_eq!(extension, Some(OsStr::new("txt")));
1915 #[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
1916 #[stable(feature = "rust1", since = "1.0.0")]
1918 // `Path::new` current implementation relies
1919 // on `Path` being layout-compatible with `OsStr`.
1920 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1921 // Anyway, `Path` representation and layout are considered implementation detail, are
1922 // not documented and must not be relied upon.
1927 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1929 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1930 /// See its documentation for more.
1932 /// [`strip_prefix`]: Path::strip_prefix
1933 #[derive(Debug, Clone, PartialEq, Eq)]
1934 #[stable(since = "1.7.0", feature = "strip_prefix")]
1935 pub struct StripPrefixError(());
1938 // The following (private!) function allows construction of a path from a u8
1939 // slice, which is only safe when it is known to follow the OsStr encoding.
1940 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1941 unsafe { Path::new(u8_slice_as_os_str(s)) }
1943 // The following (private!) function reveals the byte encoding used for OsStr.
1944 fn as_u8_slice(&self) -> &[u8] {
1945 os_str_as_u8_slice(&self.inner)
1948 /// Directly wraps a string slice as a `Path` slice.
1950 /// This is a cost-free conversion.
1955 /// use std::path::Path;
1957 /// Path::new("foo.txt");
1960 /// You can create `Path`s from `String`s, or even other `Path`s:
1963 /// use std::path::Path;
1965 /// let string = String::from("foo.txt");
1966 /// let from_string = Path::new(&string);
1967 /// let from_path = Path::new(&from_string);
1968 /// assert_eq!(from_string, from_path);
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1972 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1975 /// Yields the underlying [`OsStr`] slice.
1980 /// use std::path::Path;
1982 /// let os_str = Path::new("foo.txt").as_os_str();
1983 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1985 #[stable(feature = "rust1", since = "1.0.0")]
1988 pub fn as_os_str(&self) -> &OsStr {
1992 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1994 /// This conversion may entail doing a check for UTF-8 validity.
1995 /// Note that validation is performed because non-UTF-8 strings are
1996 /// perfectly valid for some OS.
2003 /// use std::path::Path;
2005 /// let path = Path::new("foo.txt");
2006 /// assert_eq!(path.to_str(), Some("foo.txt"));
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 #[must_use = "this returns the result of the operation, \
2010 without modifying the original"]
2012 pub fn to_str(&self) -> Option<&str> {
2016 /// Converts a `Path` to a [`Cow<str>`].
2018 /// Any non-Unicode sequences are replaced with
2019 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
2021 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
2025 /// Calling `to_string_lossy` on a `Path` with valid unicode:
2028 /// use std::path::Path;
2030 /// let path = Path::new("foo.txt");
2031 /// assert_eq!(path.to_string_lossy(), "foo.txt");
2034 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
2035 /// have returned `"fo�.txt"`.
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 #[must_use = "this returns the result of the operation, \
2038 without modifying the original"]
2040 pub fn to_string_lossy(&self) -> Cow<'_, str> {
2041 self.inner.to_string_lossy()
2044 /// Converts a `Path` to an owned [`PathBuf`].
2049 /// use std::path::Path;
2051 /// let path_buf = Path::new("foo.txt").to_path_buf();
2052 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
2054 #[rustc_conversion_suggestion]
2055 #[must_use = "this returns the result of the operation, \
2056 without modifying the original"]
2057 #[stable(feature = "rust1", since = "1.0.0")]
2058 pub fn to_path_buf(&self) -> PathBuf {
2059 PathBuf::from(self.inner.to_os_string())
2062 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
2063 /// the current directory.
2065 /// * On Unix, a path is absolute if it starts with the root, so
2066 /// `is_absolute` and [`has_root`] are equivalent.
2068 /// * On Windows, a path is absolute if it has a prefix and starts with the
2069 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
2074 /// use std::path::Path;
2076 /// assert!(!Path::new("foo.txt").is_absolute());
2079 /// [`has_root`]: Path::has_root
2080 #[stable(feature = "rust1", since = "1.0.0")]
2082 #[allow(deprecated)]
2083 pub fn is_absolute(&self) -> bool {
2084 if cfg!(target_os = "redox") {
2085 // FIXME: Allow Redox prefixes
2086 self.has_root() || has_redox_scheme(self.as_u8_slice())
2088 self.has_root() && (cfg!(any(unix, target_os = "wasi")) || self.prefix().is_some())
2092 /// Returns `true` if the `Path` is relative, i.e., not absolute.
2094 /// See [`is_absolute`]'s documentation for more details.
2099 /// use std::path::Path;
2101 /// assert!(Path::new("foo.txt").is_relative());
2104 /// [`is_absolute`]: Path::is_absolute
2105 #[stable(feature = "rust1", since = "1.0.0")]
2108 pub fn is_relative(&self) -> bool {
2112 fn prefix(&self) -> Option<Prefix<'_>> {
2113 self.components().prefix
2116 /// Returns `true` if the `Path` has a root.
2118 /// * On Unix, a path has a root if it begins with `/`.
2120 /// * On Windows, a path has a root if it:
2121 /// * has no prefix and begins with a separator, e.g., `\windows`
2122 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
2123 /// * has any non-disk prefix, e.g., `\\server\share`
2128 /// use std::path::Path;
2130 /// assert!(Path::new("/etc/passwd").has_root());
2132 #[stable(feature = "rust1", since = "1.0.0")]
2135 pub fn has_root(&self) -> bool {
2136 self.components().has_root()
2139 /// Returns the `Path` without its final component, if there is one.
2141 /// Returns [`None`] if the path terminates in a root or prefix.
2146 /// use std::path::Path;
2148 /// let path = Path::new("/foo/bar");
2149 /// let parent = path.parent().unwrap();
2150 /// assert_eq!(parent, Path::new("/foo"));
2152 /// let grand_parent = parent.parent().unwrap();
2153 /// assert_eq!(grand_parent, Path::new("/"));
2154 /// assert_eq!(grand_parent.parent(), None);
2156 #[stable(feature = "rust1", since = "1.0.0")]
2158 pub fn parent(&self) -> Option<&Path> {
2159 let mut comps = self.components();
2160 let comp = comps.next_back();
2161 comp.and_then(|p| match p {
2162 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
2163 Some(comps.as_path())
2169 /// Produces an iterator over `Path` and its ancestors.
2171 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2172 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2173 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2174 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2180 /// use std::path::Path;
2182 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2183 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2184 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2185 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2186 /// assert_eq!(ancestors.next(), None);
2188 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2189 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2190 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2191 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2192 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2193 /// assert_eq!(ancestors.next(), None);
2196 /// [`parent`]: Path::parent
2197 #[stable(feature = "path_ancestors", since = "1.28.0")]
2199 pub fn ancestors(&self) -> Ancestors<'_> {
2200 Ancestors { next: Some(&self) }
2203 /// Returns the final component of the `Path`, if there is one.
2205 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2206 /// is the directory name.
2208 /// Returns [`None`] if the path terminates in `..`.
2213 /// use std::path::Path;
2214 /// use std::ffi::OsStr;
2216 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2217 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2218 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2219 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2220 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2221 /// assert_eq!(None, Path::new("/").file_name());
2223 #[stable(feature = "rust1", since = "1.0.0")]
2225 pub fn file_name(&self) -> Option<&OsStr> {
2226 self.components().next_back().and_then(|p| match p {
2227 Component::Normal(p) => Some(p),
2232 /// Returns a path that, when joined onto `base`, yields `self`.
2236 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2237 /// returns `false`), returns [`Err`].
2239 /// [`starts_with`]: Path::starts_with
2244 /// use std::path::{Path, PathBuf};
2246 /// let path = Path::new("/test/haha/foo.txt");
2248 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2249 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2250 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2251 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2252 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2254 /// assert!(path.strip_prefix("test").is_err());
2255 /// assert!(path.strip_prefix("/haha").is_err());
2257 /// let prefix = PathBuf::from("/test/");
2258 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2260 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2261 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2265 self._strip_prefix(base.as_ref())
2268 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2269 iter_after(self.components(), base.components())
2270 .map(|c| c.as_path())
2271 .ok_or(StripPrefixError(()))
2274 /// Determines whether `base` is a prefix of `self`.
2276 /// Only considers whole path components to match.
2281 /// use std::path::Path;
2283 /// let path = Path::new("/etc/passwd");
2285 /// assert!(path.starts_with("/etc"));
2286 /// assert!(path.starts_with("/etc/"));
2287 /// assert!(path.starts_with("/etc/passwd"));
2288 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2289 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2291 /// assert!(!path.starts_with("/e"));
2292 /// assert!(!path.starts_with("/etc/passwd.txt"));
2294 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2296 #[stable(feature = "rust1", since = "1.0.0")]
2298 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2299 self._starts_with(base.as_ref())
2302 fn _starts_with(&self, base: &Path) -> bool {
2303 iter_after(self.components(), base.components()).is_some()
2306 /// Determines whether `child` is a suffix of `self`.
2308 /// Only considers whole path components to match.
2313 /// use std::path::Path;
2315 /// let path = Path::new("/etc/resolv.conf");
2317 /// assert!(path.ends_with("resolv.conf"));
2318 /// assert!(path.ends_with("etc/resolv.conf"));
2319 /// assert!(path.ends_with("/etc/resolv.conf"));
2321 /// assert!(!path.ends_with("/resolv.conf"));
2322 /// assert!(!path.ends_with("conf")); // use .extension() instead
2324 #[stable(feature = "rust1", since = "1.0.0")]
2326 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2327 self._ends_with(child.as_ref())
2330 fn _ends_with(&self, child: &Path) -> bool {
2331 iter_after(self.components().rev(), child.components().rev()).is_some()
2334 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2336 /// [`self.file_name`]: Path::file_name
2340 /// * [`None`], if there is no file name;
2341 /// * The entire file name if there is no embedded `.`;
2342 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2343 /// * Otherwise, the portion of the file name before the final `.`
2348 /// use std::path::Path;
2350 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2351 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2355 /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
2356 /// before the *first* `.`
2358 /// [`Path::file_prefix`]: Path::file_prefix
2360 #[stable(feature = "rust1", since = "1.0.0")]
2362 pub fn file_stem(&self) -> Option<&OsStr> {
2363 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2366 /// Extracts the prefix of [`self.file_name`].
2370 /// * [`None`], if there is no file name;
2371 /// * The entire file name if there is no embedded `.`;
2372 /// * The portion of the file name before the first non-beginning `.`;
2373 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2374 /// * The portion of the file name before the second `.` if the file name begins with `.`
2376 /// [`self.file_name`]: Path::file_name
2381 /// # #![feature(path_file_prefix)]
2382 /// use std::path::Path;
2384 /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
2385 /// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
2389 /// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
2390 /// before the *last* `.`
2392 /// [`Path::file_stem`]: Path::file_stem
2394 #[unstable(feature = "path_file_prefix", issue = "86319")]
2396 pub fn file_prefix(&self) -> Option<&OsStr> {
2397 self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before))
2400 /// Extracts the extension of [`self.file_name`], if possible.
2402 /// The extension is:
2404 /// * [`None`], if there is no file name;
2405 /// * [`None`], if there is no embedded `.`;
2406 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2407 /// * Otherwise, the portion of the file name after the final `.`
2409 /// [`self.file_name`]: Path::file_name
2414 /// use std::path::Path;
2416 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2417 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2419 #[stable(feature = "rust1", since = "1.0.0")]
2421 pub fn extension(&self) -> Option<&OsStr> {
2422 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
2425 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2427 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2432 /// use std::path::{Path, PathBuf};
2434 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2436 #[stable(feature = "rust1", since = "1.0.0")]
2438 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2439 self._join(path.as_ref())
2442 fn _join(&self, path: &Path) -> PathBuf {
2443 let mut buf = self.to_path_buf();
2448 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2450 /// See [`PathBuf::set_file_name`] for more details.
2455 /// use std::path::{Path, PathBuf};
2457 /// let path = Path::new("/tmp/foo.txt");
2458 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2460 /// let path = Path::new("/tmp");
2461 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2463 #[stable(feature = "rust1", since = "1.0.0")]
2465 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2466 self._with_file_name(file_name.as_ref())
2469 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2470 let mut buf = self.to_path_buf();
2471 buf.set_file_name(file_name);
2475 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2477 /// See [`PathBuf::set_extension`] for more details.
2482 /// use std::path::{Path, PathBuf};
2484 /// let path = Path::new("foo.rs");
2485 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2487 /// let path = Path::new("foo.tar.gz");
2488 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2489 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2490 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2494 self._with_extension(extension.as_ref())
2497 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2498 let mut buf = self.to_path_buf();
2499 buf.set_extension(extension);
2503 /// Produces an iterator over the [`Component`]s of the path.
2505 /// When parsing the path, there is a small amount of normalization:
2507 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2508 /// `a` and `b` as components.
2510 /// * Occurrences of `.` are normalized away, except if they are at the
2511 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2512 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2513 /// an additional [`CurDir`] component.
2515 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2517 /// Note that no other normalization takes place; in particular, `a/c`
2518 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2519 /// is a symbolic link (so its parent isn't `a`).
2524 /// use std::path::{Path, Component};
2525 /// use std::ffi::OsStr;
2527 /// let mut components = Path::new("/tmp/foo.txt").components();
2529 /// assert_eq!(components.next(), Some(Component::RootDir));
2530 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2531 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2532 /// assert_eq!(components.next(), None)
2535 /// [`CurDir`]: Component::CurDir
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 pub fn components(&self) -> Components<'_> {
2538 let prefix = parse_prefix(self.as_os_str());
2540 path: self.as_u8_slice(),
2542 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2543 || has_redox_scheme(self.as_u8_slice()),
2544 front: State::Prefix,
2549 /// Produces an iterator over the path's components viewed as [`OsStr`]
2552 /// For more information about the particulars of how the path is separated
2553 /// into components, see [`components`].
2555 /// [`components`]: Path::components
2560 /// use std::path::{self, Path};
2561 /// use std::ffi::OsStr;
2563 /// let mut it = Path::new("/tmp/foo.txt").iter();
2564 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2565 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2566 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2567 /// assert_eq!(it.next(), None)
2569 #[stable(feature = "rust1", since = "1.0.0")]
2571 pub fn iter(&self) -> Iter<'_> {
2572 Iter { inner: self.components() }
2575 /// Returns an object that implements [`Display`] for safely printing paths
2576 /// that may contain non-Unicode data. This may perform lossy conversion,
2577 /// depending on the platform. If you would like an implementation which
2578 /// escapes the path please use [`Debug`] instead.
2580 /// [`Display`]: fmt::Display
2585 /// use std::path::Path;
2587 /// let path = Path::new("/tmp/foo.rs");
2589 /// println!("{}", path.display());
2591 #[stable(feature = "rust1", since = "1.0.0")]
2592 #[must_use = "this does not display the path, \
2593 it returns an object that can be displayed"]
2595 pub fn display(&self) -> Display<'_> {
2596 Display { path: self }
2599 /// Queries the file system to get information about a file, directory, etc.
2601 /// This function will traverse symbolic links to query information about the
2602 /// destination file.
2604 /// This is an alias to [`fs::metadata`].
2609 /// use std::path::Path;
2611 /// let path = Path::new("/Minas/tirith");
2612 /// let metadata = path.metadata().expect("metadata call failed");
2613 /// println!("{:?}", metadata.file_type());
2615 #[stable(feature = "path_ext", since = "1.5.0")]
2617 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2621 /// Queries the metadata about a file without following symlinks.
2623 /// This is an alias to [`fs::symlink_metadata`].
2628 /// use std::path::Path;
2630 /// let path = Path::new("/Minas/tirith");
2631 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2632 /// println!("{:?}", metadata.file_type());
2634 #[stable(feature = "path_ext", since = "1.5.0")]
2636 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2637 fs::symlink_metadata(self)
2640 /// Returns the canonical, absolute form of the path with all intermediate
2641 /// components normalized and symbolic links resolved.
2643 /// This is an alias to [`fs::canonicalize`].
2648 /// use std::path::{Path, PathBuf};
2650 /// let path = Path::new("/foo/test/../test/bar.rs");
2651 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2653 #[stable(feature = "path_ext", since = "1.5.0")]
2655 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2656 fs::canonicalize(self)
2659 /// Reads a symbolic link, returning the file that the link points to.
2661 /// This is an alias to [`fs::read_link`].
2666 /// use std::path::Path;
2668 /// let path = Path::new("/laputa/sky_castle.rs");
2669 /// let path_link = path.read_link().expect("read_link call failed");
2671 #[stable(feature = "path_ext", since = "1.5.0")]
2673 pub fn read_link(&self) -> io::Result<PathBuf> {
2677 /// Returns an iterator over the entries within a directory.
2679 /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. New
2680 /// errors may be encountered after an iterator is initially constructed.
2682 /// This is an alias to [`fs::read_dir`].
2687 /// use std::path::Path;
2689 /// let path = Path::new("/laputa");
2690 /// for entry in path.read_dir().expect("read_dir call failed") {
2691 /// if let Ok(entry) = entry {
2692 /// println!("{:?}", entry.path());
2696 #[stable(feature = "path_ext", since = "1.5.0")]
2698 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2702 /// Returns `true` if the path points at an existing entity.
2704 /// This function will traverse symbolic links to query information about the
2705 /// destination file.
2707 /// If you cannot access the metadata of the file, e.g. because of a
2708 /// permission error or broken symbolic links, this will return `false`.
2713 /// use std::path::Path;
2714 /// assert!(!Path::new("does_not_exist.txt").exists());
2719 /// This is a convenience function that coerces errors to false. If you want to
2720 /// check errors, call [`fs::metadata`].
2721 #[stable(feature = "path_ext", since = "1.5.0")]
2724 pub fn exists(&self) -> bool {
2725 fs::metadata(self).is_ok()
2728 /// Returns `Ok(true)` if the path points at an existing entity.
2730 /// This function will traverse symbolic links to query information about the
2731 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2733 /// As opposed to the [`exists()`] method, this one doesn't silently ignore errors
2734 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2735 /// denied on some of the parent directories.)
2740 /// #![feature(path_try_exists)]
2742 /// use std::path::Path;
2743 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2744 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2747 /// [`exists()`]: Self::exists
2748 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2750 #[unstable(feature = "path_try_exists", issue = "83186")]
2752 pub fn try_exists(&self) -> io::Result<bool> {
2753 fs::try_exists(self)
2756 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2758 /// This function will traverse symbolic links to query information about the
2759 /// destination file.
2761 /// If you cannot access the metadata of the file, e.g. because of a
2762 /// permission error or broken symbolic links, this will return `false`.
2767 /// use std::path::Path;
2768 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2769 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2774 /// This is a convenience function that coerces errors to false. If you want to
2775 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2776 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2778 /// When the goal is simply to read from (or write to) the source, the most
2779 /// reliable way to test the source can be read (or written to) is to open
2780 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2781 /// a Unix-like system for example. See [`fs::File::open`] or
2782 /// [`fs::OpenOptions::open`] for more information.
2783 #[stable(feature = "path_ext", since = "1.5.0")]
2785 pub fn is_file(&self) -> bool {
2786 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2789 /// Returns `true` if the path exists on disk and is pointing at a directory.
2791 /// This function will traverse symbolic links to query information about the
2792 /// destination file.
2794 /// If you cannot access the metadata of the file, e.g. because of a
2795 /// permission error or broken symbolic links, this will return `false`.
2800 /// use std::path::Path;
2801 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2802 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2807 /// This is a convenience function that coerces errors to false. If you want to
2808 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2809 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2810 #[stable(feature = "path_ext", since = "1.5.0")]
2812 pub fn is_dir(&self) -> bool {
2813 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2816 /// Returns `true` if the path exists on disk and is pointing at a symbolic link.
2818 /// This function will not traverse symbolic links.
2819 /// In case of a broken symbolic link this will also return true.
2821 /// If you cannot access the directory containing the file, e.g., because of a
2822 /// permission error, this will return false.
2826 #[cfg_attr(unix, doc = "```no_run")]
2827 #[cfg_attr(not(unix), doc = "```ignore")]
2828 /// use std::path::Path;
2829 /// use std::os::unix::fs::symlink;
2831 /// let link_path = Path::new("link");
2832 /// symlink("/origin_does_not_exist/", link_path).unwrap();
2833 /// assert_eq!(link_path.is_symlink(), true);
2834 /// assert_eq!(link_path.exists(), false);
2839 /// This is a convenience function that coerces errors to false. If you want to
2840 /// check errors, call [`fs::symlink_metadata`] and handle its [`Result`]. Then call
2841 /// [`fs::Metadata::is_symlink`] if it was [`Ok`].
2843 #[stable(feature = "is_symlink", since = "1.58.0")]
2844 pub fn is_symlink(&self) -> bool {
2845 fs::symlink_metadata(self).map(|m| m.is_symlink()).unwrap_or(false)
2848 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2850 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2851 #[must_use = "`self` will be dropped if the result is not used"]
2852 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2853 let rw = Box::into_raw(self) as *mut OsStr;
2854 let inner = unsafe { Box::from_raw(rw) };
2855 PathBuf { inner: OsString::from(inner) }
2859 #[stable(feature = "rust1", since = "1.0.0")]
2860 impl AsRef<OsStr> for Path {
2862 fn as_ref(&self) -> &OsStr {
2867 #[stable(feature = "rust1", since = "1.0.0")]
2868 impl fmt::Debug for Path {
2869 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2870 fmt::Debug::fmt(&self.inner, formatter)
2874 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2876 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2877 /// [`Display`] trait in a way that mitigates that. It is created by the
2878 /// [`display`](Path::display) method on [`Path`]. This may perform lossy
2879 /// conversion, depending on the platform. If you would like an implementation
2880 /// which escapes the path please use [`Debug`] instead.
2885 /// use std::path::Path;
2887 /// let path = Path::new("/tmp/foo.rs");
2889 /// println!("{}", path.display());
2892 /// [`Display`]: fmt::Display
2893 /// [`format!`]: crate::format
2894 #[stable(feature = "rust1", since = "1.0.0")]
2895 pub struct Display<'a> {
2899 #[stable(feature = "rust1", since = "1.0.0")]
2900 impl fmt::Debug for Display<'_> {
2901 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2902 fmt::Debug::fmt(&self.path, f)
2906 #[stable(feature = "rust1", since = "1.0.0")]
2907 impl fmt::Display for Display<'_> {
2908 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2909 self.path.inner.display(f)
2913 #[stable(feature = "rust1", since = "1.0.0")]
2914 impl cmp::PartialEq for Path {
2916 fn eq(&self, other: &Path) -> bool {
2917 self.components() == other.components()
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 impl Hash for Path {
2923 fn hash<H: Hasher>(&self, h: &mut H) {
2924 let bytes = self.as_u8_slice();
2925 let prefix_len = match parse_prefix(&self.inner) {
2932 let bytes = &bytes[prefix_len..];
2934 let mut component_start = 0;
2935 let mut bytes_hashed = 0;
2937 for i in 0..bytes.len() {
2938 if is_sep_byte(bytes[i]) {
2939 if i > component_start {
2940 let to_hash = &bytes[component_start..i];
2942 bytes_hashed += to_hash.len();
2945 // skip over separator and optionally a following CurDir item
2946 // since components() would normalize these away
2947 component_start = i + match bytes[i..] {
2948 [_, b'.', b'/', ..] | [_, b'.'] => 2,
2954 if component_start < bytes.len() {
2955 let to_hash = &bytes[component_start..];
2957 bytes_hashed += to_hash.len();
2960 h.write_usize(bytes_hashed);
2964 #[stable(feature = "rust1", since = "1.0.0")]
2965 impl cmp::Eq for Path {}
2967 #[stable(feature = "rust1", since = "1.0.0")]
2968 impl cmp::PartialOrd for Path {
2970 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2971 Some(compare_components(self.components(), other.components()))
2975 #[stable(feature = "rust1", since = "1.0.0")]
2976 impl cmp::Ord for Path {
2978 fn cmp(&self, other: &Path) -> cmp::Ordering {
2979 compare_components(self.components(), other.components())
2983 #[stable(feature = "rust1", since = "1.0.0")]
2984 impl AsRef<Path> for Path {
2986 fn as_ref(&self) -> &Path {
2991 #[stable(feature = "rust1", since = "1.0.0")]
2992 impl AsRef<Path> for OsStr {
2994 fn as_ref(&self) -> &Path {
2999 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
3000 impl AsRef<Path> for Cow<'_, OsStr> {
3002 fn as_ref(&self) -> &Path {
3007 #[stable(feature = "rust1", since = "1.0.0")]
3008 impl AsRef<Path> for OsString {
3010 fn as_ref(&self) -> &Path {
3015 #[stable(feature = "rust1", since = "1.0.0")]
3016 impl AsRef<Path> for str {
3018 fn as_ref(&self) -> &Path {
3023 #[stable(feature = "rust1", since = "1.0.0")]
3024 impl AsRef<Path> for String {
3026 fn as_ref(&self) -> &Path {
3031 #[stable(feature = "rust1", since = "1.0.0")]
3032 impl AsRef<Path> for PathBuf {
3034 fn as_ref(&self) -> &Path {
3039 #[stable(feature = "path_into_iter", since = "1.6.0")]
3040 impl<'a> IntoIterator for &'a PathBuf {
3041 type Item = &'a OsStr;
3042 type IntoIter = Iter<'a>;
3044 fn into_iter(self) -> Iter<'a> {
3049 #[stable(feature = "path_into_iter", since = "1.6.0")]
3050 impl<'a> IntoIterator for &'a Path {
3051 type Item = &'a OsStr;
3052 type IntoIter = Iter<'a>;
3054 fn into_iter(self) -> Iter<'a> {
3059 macro_rules! impl_cmp {
3060 ($lhs:ty, $rhs: ty) => {
3061 #[stable(feature = "partialeq_path", since = "1.6.0")]
3062 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3064 fn eq(&self, other: &$rhs) -> bool {
3065 <Path as PartialEq>::eq(self, other)
3069 #[stable(feature = "partialeq_path", since = "1.6.0")]
3070 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3072 fn eq(&self, other: &$lhs) -> bool {
3073 <Path as PartialEq>::eq(self, other)
3077 #[stable(feature = "cmp_path", since = "1.8.0")]
3078 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3080 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3081 <Path as PartialOrd>::partial_cmp(self, other)
3085 #[stable(feature = "cmp_path", since = "1.8.0")]
3086 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3088 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3089 <Path as PartialOrd>::partial_cmp(self, other)
3095 impl_cmp!(PathBuf, Path);
3096 impl_cmp!(PathBuf, &'a Path);
3097 impl_cmp!(Cow<'a, Path>, Path);
3098 impl_cmp!(Cow<'a, Path>, &'b Path);
3099 impl_cmp!(Cow<'a, Path>, PathBuf);
3101 macro_rules! impl_cmp_os_str {
3102 ($lhs:ty, $rhs: ty) => {
3103 #[stable(feature = "cmp_path", since = "1.8.0")]
3104 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3106 fn eq(&self, other: &$rhs) -> bool {
3107 <Path as PartialEq>::eq(self, other.as_ref())
3111 #[stable(feature = "cmp_path", since = "1.8.0")]
3112 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3114 fn eq(&self, other: &$lhs) -> bool {
3115 <Path as PartialEq>::eq(self.as_ref(), other)
3119 #[stable(feature = "cmp_path", since = "1.8.0")]
3120 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3122 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3123 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
3127 #[stable(feature = "cmp_path", since = "1.8.0")]
3128 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3130 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3131 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
3137 impl_cmp_os_str!(PathBuf, OsStr);
3138 impl_cmp_os_str!(PathBuf, &'a OsStr);
3139 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
3140 impl_cmp_os_str!(PathBuf, OsString);
3141 impl_cmp_os_str!(Path, OsStr);
3142 impl_cmp_os_str!(Path, &'a OsStr);
3143 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
3144 impl_cmp_os_str!(Path, OsString);
3145 impl_cmp_os_str!(&'a Path, OsStr);
3146 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
3147 impl_cmp_os_str!(&'a Path, OsString);
3148 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
3149 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
3150 impl_cmp_os_str!(Cow<'a, Path>, OsString);
3152 #[stable(since = "1.7.0", feature = "strip_prefix")]
3153 impl fmt::Display for StripPrefixError {
3154 #[allow(deprecated, deprecated_in_future)]
3155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3156 self.description().fmt(f)
3160 #[stable(since = "1.7.0", feature = "strip_prefix")]
3161 impl Error for StripPrefixError {
3162 #[allow(deprecated)]
3163 fn description(&self) -> &str {