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.
17 //! Path manipulation includes both parsing components from slices and building
20 //! To parse a path, you can create a [`Path`] slice from a [`str`]
21 //! slice and start asking questions:
24 //! use std::path::Path;
25 //! use std::ffi::OsStr;
27 //! let path = Path::new("/tmp/foo/bar.txt");
29 //! let parent = path.parent();
30 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
32 //! let file_stem = path.file_stem();
33 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
35 //! let extension = path.extension();
36 //! assert_eq!(extension, Some(OsStr::new("txt")));
39 //! To build or modify paths, use [`PathBuf`]:
42 //! use std::path::PathBuf;
44 //! // This way works...
45 //! let mut path = PathBuf::from("c:\\");
47 //! path.push("windows");
48 //! path.push("system32");
50 //! path.set_extension("dll");
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();
57 //! [`components`]: Path::components
58 //! [`push`]: PathBuf::push
60 #![stable(feature = "rust1", since = "1.0.0")]
65 use crate::borrow::{Borrow, Cow};
67 use crate::error::Error;
70 use crate::hash::{Hash, Hasher};
72 use crate::iter::{self, FusedIterator};
73 use crate::ops::{self, Deref};
75 use crate::str::FromStr;
78 use crate::ffi::{OsStr, OsString};
80 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
82 ////////////////////////////////////////////////////////////////////////////////
84 ////////////////////////////////////////////////////////////////////////////////
86 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
87 // taking advantage of the fact that OsStr always encodes ASCII characters
88 // as-is. Eventually, this transmutation should be replaced by direct uses of
89 // OsStr APIs for parsing, but it will take a while for those to become
92 ////////////////////////////////////////////////////////////////////////////////
94 ////////////////////////////////////////////////////////////////////////////////
96 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
98 /// Windows uses a variety of path prefix styles, including references to drive
99 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
100 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
101 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
102 /// no normalization is performed.
107 /// use std::path::{Component, Path, Prefix};
108 /// use std::path::Prefix::*;
109 /// use std::ffi::OsStr;
111 /// fn get_path_prefix(s: &str) -> Prefix {
112 /// let path = Path::new(s);
113 /// match path.components().next().unwrap() {
114 /// Component::Prefix(prefix_component) => prefix_component.kind(),
119 /// # if cfg!(windows) {
120 /// assert_eq!(Verbatim(OsStr::new("pictures")),
121 /// get_path_prefix(r"\\?\pictures\kittens"));
122 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
123 /// get_path_prefix(r"\\?\UNC\server\share"));
124 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
125 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
126 /// get_path_prefix(r"\\.\BrainInterface"));
127 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
128 /// get_path_prefix(r"\\server\share"));
129 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
132 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub enum Prefix<'a> {
135 /// Verbatim prefix, e.g., `\\?\cat_pics`.
137 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
139 #[stable(feature = "rust1", since = "1.0.0")]
140 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
142 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
143 /// e.g., `\\?\UNC\server\share`.
145 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
146 /// server's hostname and a share name.
147 #[stable(feature = "rust1", since = "1.0.0")]
149 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
150 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
153 /// Verbatim disk prefix, e.g., `\\?\C:`.
155 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
156 /// drive letter and `:`.
157 #[stable(feature = "rust1", since = "1.0.0")]
158 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
160 /// Device namespace prefix, e.g., `\\.\COM42`.
162 /// Device namespace prefixes consist of `\\.\` immediately followed by the
164 #[stable(feature = "rust1", since = "1.0.0")]
165 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
167 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
168 /// `\\server\share`.
170 /// UNC prefixes consist of the server's hostname and a share name.
171 #[stable(feature = "rust1", since = "1.0.0")]
173 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
174 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
177 /// Prefix `C:` for the given disk drive.
178 #[stable(feature = "rust1", since = "1.0.0")]
179 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
182 impl<'a> Prefix<'a> {
184 fn len(&self) -> usize {
186 fn os_str_len(s: &OsStr) -> usize {
187 os_str_as_u8_slice(s).len()
190 Verbatim(x) => 4 + os_str_len(x),
191 VerbatimUNC(x, y) => {
192 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
194 VerbatimDisk(_) => 6,
195 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
196 DeviceNS(x) => 4 + os_str_len(x),
201 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
206 /// use std::path::Prefix::*;
207 /// use std::ffi::OsStr;
209 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
210 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
211 /// assert!(VerbatimDisk(b'C').is_verbatim());
212 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
213 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
214 /// assert!(!Disk(b'C').is_verbatim());
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn is_verbatim(&self) -> bool {
220 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
224 fn is_drive(&self) -> bool {
225 matches!(*self, Prefix::Disk(_))
229 fn has_implicit_root(&self) -> bool {
234 ////////////////////////////////////////////////////////////////////////////////
235 // Exposed parsing helpers
236 ////////////////////////////////////////////////////////////////////////////////
238 /// Determines whether the character is one of the permitted path
239 /// separators for the current platform.
246 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
247 /// assert!(!path::is_separator('❤'));
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub fn is_separator(c: char) -> bool {
251 c.is_ascii() && is_sep_byte(c as u8)
254 /// The primary separator of path components for the current platform.
256 /// For example, `/` on Unix and `\` on Windows.
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
260 ////////////////////////////////////////////////////////////////////////////////
262 ////////////////////////////////////////////////////////////////////////////////
264 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
265 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
266 // `iter` after having exhausted `prefix`.
267 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
269 I: Iterator<Item = Component<'a>> + Clone,
270 J: Iterator<Item = Component<'b>>,
273 let mut iter_next = iter.clone();
274 match (iter_next.next(), prefix.next()) {
275 (Some(ref x), Some(ref y)) if x == y => (),
276 (Some(_), Some(_)) => return None,
277 (Some(_), None) => return Some(iter),
278 (None, None) => return Some(iter),
279 (None, Some(_)) => return None,
285 // See note at the top of this module to understand why these are used:
287 // These casts are safe as OsStr is internally a wrapper around [u8] on all
290 // Note that currently this relies on the special knowledge that libstd has;
291 // these types are single-element structs but are not marked repr(transparent)
292 // or repr(C) which would make these casts allowable outside std.
293 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
294 unsafe { &*(s as *const OsStr as *const [u8]) }
296 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
297 &*(s as *const [u8] as *const OsStr)
300 // Detect scheme on Redox
301 fn has_redox_scheme(s: &[u8]) -> bool {
302 cfg!(target_os = "redox") && s.contains(&b':')
305 ////////////////////////////////////////////////////////////////////////////////
306 // Cross-platform, iterator-independent parsing
307 ////////////////////////////////////////////////////////////////////////////////
309 /// Says whether the first byte after the prefix is a separator.
310 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
311 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
312 !path.is_empty() && is_sep_byte(path[0])
315 // basic workhorse for splitting stem and extension
316 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
318 if os_str_as_u8_slice(file) == b".." {
319 return (Some(file), None);
322 // The unsafety here stems from converting between &OsStr and &[u8]
323 // and back. This is safe to do because (1) we only look at ASCII
324 // contents of the encoding and (2) new &OsStr values are produced
325 // 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"") {
333 (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s)))
338 ////////////////////////////////////////////////////////////////////////////////
339 // The core iterators
340 ////////////////////////////////////////////////////////////////////////////////
342 /// Component parsing works by a double-ended state machine; the cursors at the
343 /// front and back of the path each keep track of what parts of the path have
344 /// been consumed so far.
346 /// Going front to back, a path is made up of a prefix, a starting
347 /// directory component, and a body (of normal components)
348 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
351 StartDir = 1, // / or . or nothing
352 Body = 2, // foo/bar/baz
356 /// A structure wrapping a Windows path prefix as well as its unparsed string
359 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
360 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
361 /// returned by [`as_os_str`].
363 /// Instances of this `struct` can be obtained by matching against the
364 /// [`Prefix` variant] on [`Component`].
366 /// Does not occur on Unix.
371 /// # if cfg!(windows) {
372 /// use std::path::{Component, Path, Prefix};
373 /// use std::ffi::OsStr;
375 /// let path = Path::new(r"c:\you\later\");
376 /// match path.components().next().unwrap() {
377 /// Component::Prefix(prefix_component) => {
378 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
379 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
381 /// _ => unreachable!(),
386 /// [`as_os_str`]: PrefixComponent::as_os_str
387 /// [`kind`]: PrefixComponent::kind
388 /// [`Prefix` variant]: Component::Prefix
389 #[stable(feature = "rust1", since = "1.0.0")]
390 #[derive(Copy, Clone, Eq, Debug)]
391 pub struct PrefixComponent<'a> {
392 /// The prefix as an unparsed `OsStr` slice.
395 /// The parsed prefix data.
399 impl<'a> PrefixComponent<'a> {
400 /// Returns the parsed prefix data.
402 /// See [`Prefix`]'s documentation for more information on the different
403 /// kinds of prefixes.
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn kind(&self) -> Prefix<'a> {
409 /// Returns the raw [`OsStr`] slice for this prefix.
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn as_os_str(&self) -> &'a OsStr {
416 #[stable(feature = "rust1", since = "1.0.0")]
417 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
418 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
419 cmp::PartialEq::eq(&self.parsed, &other.parsed)
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
425 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
426 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl cmp::Ord for PrefixComponent<'_> {
432 fn cmp(&self, other: &Self) -> cmp::Ordering {
433 cmp::Ord::cmp(&self.parsed, &other.parsed)
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl Hash for PrefixComponent<'_> {
439 fn hash<H: Hasher>(&self, h: &mut H) {
444 /// A single component of a path.
446 /// A `Component` roughly corresponds to a substring between path separators
449 /// This `enum` is created by iterating over [`Components`], which in turn is
450 /// created by the [`components`][`Path::components`] method on [`Path`].
455 /// use std::path::{Component, Path};
457 /// let path = Path::new("/tmp/foo/bar.txt");
458 /// let components = path.components().collect::<Vec<_>>();
459 /// assert_eq!(&components, &[
460 /// Component::RootDir,
461 /// Component::Normal("tmp".as_ref()),
462 /// Component::Normal("foo".as_ref()),
463 /// Component::Normal("bar.txt".as_ref()),
466 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub enum Component<'a> {
469 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
471 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
474 /// Does not occur on Unix.
475 #[stable(feature = "rust1", since = "1.0.0")]
476 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
478 /// The root directory component, appears after any prefix and before anything else.
480 /// It represents a separator that designates that a path starts from root.
481 #[stable(feature = "rust1", since = "1.0.0")]
484 /// A reference to the current directory, i.e., `.`.
485 #[stable(feature = "rust1", since = "1.0.0")]
488 /// A reference to the parent directory, i.e., `..`.
489 #[stable(feature = "rust1", since = "1.0.0")]
492 /// A normal component, e.g., `a` and `b` in `a/b`.
494 /// This variant is the most common one, it represents references to files
496 #[stable(feature = "rust1", since = "1.0.0")]
497 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
500 impl<'a> Component<'a> {
501 /// Extracts the underlying [`OsStr`] slice.
506 /// use std::path::Path;
508 /// let path = Path::new("./tmp/foo/bar.txt");
509 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
510 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn as_os_str(self) -> &'a OsStr {
515 Component::Prefix(p) => p.as_os_str(),
516 Component::RootDir => OsStr::new(MAIN_SEP_STR),
517 Component::CurDir => OsStr::new("."),
518 Component::ParentDir => OsStr::new(".."),
519 Component::Normal(path) => path,
524 #[stable(feature = "rust1", since = "1.0.0")]
525 impl AsRef<OsStr> for Component<'_> {
526 fn as_ref(&self) -> &OsStr {
531 #[stable(feature = "path_component_asref", since = "1.25.0")]
532 impl AsRef<Path> for Component<'_> {
533 fn as_ref(&self) -> &Path {
534 self.as_os_str().as_ref()
538 /// An iterator over the [`Component`]s of a [`Path`].
540 /// This `struct` is created by the [`components`] method on [`Path`].
541 /// See its documentation for more.
546 /// use std::path::Path;
548 /// let path = Path::new("/tmp/foo/bar.txt");
550 /// for component in path.components() {
551 /// println!("{:?}", component);
555 /// [`components`]: Path::components
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub struct Components<'a> {
559 // The path left to parse components from
562 // The prefix as it was originally parsed, if any
563 prefix: Option<Prefix<'a>>,
565 // true if path *physically* has a root separator; for most Windows
566 // prefixes, it may have a "logical" rootseparator for the purposes of
567 // normalization, e.g., \\server\share == \\server\share\.
568 has_physical_root: bool,
570 // The iterator is double-ended, and these two states keep track of what has
571 // been produced from either end
576 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
578 /// This `struct` is created by the [`iter`] method on [`Path`].
579 /// See its documentation for more.
581 /// [`iter`]: Path::iter
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub struct Iter<'a> {
585 inner: Components<'a>,
588 #[stable(feature = "path_components_debug", since = "1.13.0")]
589 impl fmt::Debug for Components<'_> {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 struct DebugHelper<'a>(&'a Path);
593 impl fmt::Debug for DebugHelper<'_> {
594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595 f.debug_list().entries(self.0.components()).finish()
599 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
603 impl<'a> Components<'a> {
604 // how long is the prefix, if any?
606 fn prefix_len(&self) -> usize {
607 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
611 fn prefix_verbatim(&self) -> bool {
612 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
615 /// how much of the prefix is left from the point of view of iteration?
617 fn prefix_remaining(&self) -> usize {
618 if self.front == State::Prefix { self.prefix_len() } else { 0 }
621 // Given the iteration so far, how much of the pre-State::Body path is left?
623 fn len_before_body(&self) -> usize {
624 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
625 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
626 self.prefix_remaining() + root + cur_dir
629 // is the iteration complete?
631 fn finished(&self) -> bool {
632 self.front == State::Done || self.back == State::Done || self.front > self.back
636 fn is_sep_byte(&self, b: u8) -> bool {
637 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
640 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
645 /// use std::path::Path;
647 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
648 /// components.next();
649 /// components.next();
651 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn as_path(&self) -> &'a Path {
655 let mut comps = self.clone();
656 if comps.front == State::Body {
659 if comps.back == State::Body {
662 unsafe { Path::from_u8_slice(comps.path) }
665 /// Is the *original* path rooted?
666 fn has_root(&self) -> bool {
667 if self.has_physical_root {
670 if let Some(p) = self.prefix {
671 if p.has_implicit_root() {
678 /// Should the normalized path include a leading . ?
679 fn include_cur_dir(&self) -> bool {
683 let mut iter = self.path[self.prefix_len()..].iter();
684 match (iter.next(), iter.next()) {
685 (Some(&b'.'), None) => true,
686 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
691 // parse a given byte sequence into the corresponding path component
692 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
694 b"." if self.prefix_verbatim() => Some(Component::CurDir),
695 b"." => None, // . components are normalized away, except at
696 // the beginning of a path, which is treated
697 // separately via `include_cur_dir`
698 b".." => Some(Component::ParentDir),
700 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
704 // parse a component from the left, saying how many bytes to consume to
705 // remove the component
706 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
707 debug_assert!(self.front == State::Body);
708 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
709 None => (0, self.path),
710 Some(i) => (1, &self.path[..i]),
712 (comp.len() + extra, self.parse_single_component(comp))
715 // parse a component from the right, saying how many bytes to consume to
716 // remove the component
717 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
718 debug_assert!(self.back == State::Body);
719 let start = self.len_before_body();
720 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
721 None => (0, &self.path[start..]),
722 Some(i) => (1, &self.path[start + i + 1..]),
724 (comp.len() + extra, self.parse_single_component(comp))
727 // trim away repeated separators (i.e., empty components) on the left
728 fn trim_left(&mut self) {
729 while !self.path.is_empty() {
730 let (size, comp) = self.parse_next_component();
734 self.path = &self.path[size..];
739 // trim away repeated separators (i.e., empty components) on the right
740 fn trim_right(&mut self) {
741 while self.path.len() > self.len_before_body() {
742 let (size, comp) = self.parse_next_component_back();
746 self.path = &self.path[..self.path.len() - size];
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl AsRef<Path> for Components<'_> {
754 fn as_ref(&self) -> &Path {
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl AsRef<OsStr> for Components<'_> {
761 fn as_ref(&self) -> &OsStr {
762 self.as_path().as_os_str()
766 #[stable(feature = "path_iter_debug", since = "1.13.0")]
767 impl fmt::Debug for Iter<'_> {
768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 struct DebugHelper<'a>(&'a Path);
771 impl fmt::Debug for DebugHelper<'_> {
772 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
773 f.debug_list().entries(self.0.iter()).finish()
777 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
782 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
787 /// use std::path::Path;
789 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
793 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn as_path(&self) -> &'a Path {
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl AsRef<Path> for Iter<'_> {
803 fn as_ref(&self) -> &Path {
808 #[stable(feature = "rust1", since = "1.0.0")]
809 impl AsRef<OsStr> for Iter<'_> {
810 fn as_ref(&self) -> &OsStr {
811 self.as_path().as_os_str()
815 #[stable(feature = "rust1", since = "1.0.0")]
816 impl<'a> Iterator for Iter<'a> {
817 type Item = &'a OsStr;
819 fn next(&mut self) -> Option<&'a OsStr> {
820 self.inner.next().map(Component::as_os_str)
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl<'a> DoubleEndedIterator for Iter<'a> {
826 fn next_back(&mut self) -> Option<&'a OsStr> {
827 self.inner.next_back().map(Component::as_os_str)
831 #[stable(feature = "fused", since = "1.26.0")]
832 impl FusedIterator for Iter<'_> {}
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl<'a> Iterator for Components<'a> {
836 type Item = Component<'a>;
838 fn next(&mut self) -> Option<Component<'a>> {
839 while !self.finished() {
841 State::Prefix if self.prefix_len() > 0 => {
842 self.front = State::StartDir;
843 debug_assert!(self.prefix_len() <= self.path.len());
844 let raw = &self.path[..self.prefix_len()];
845 self.path = &self.path[self.prefix_len()..];
846 return Some(Component::Prefix(PrefixComponent {
847 raw: unsafe { u8_slice_as_os_str(raw) },
848 parsed: self.prefix.unwrap(),
852 self.front = State::StartDir;
855 self.front = State::Body;
856 if self.has_physical_root {
857 debug_assert!(!self.path.is_empty());
858 self.path = &self.path[1..];
859 return Some(Component::RootDir);
860 } else if let Some(p) = self.prefix {
861 if p.has_implicit_root() && !p.is_verbatim() {
862 return Some(Component::RootDir);
864 } else if self.include_cur_dir() {
865 debug_assert!(!self.path.is_empty());
866 self.path = &self.path[1..];
867 return Some(Component::CurDir);
870 State::Body if !self.path.is_empty() => {
871 let (size, comp) = self.parse_next_component();
872 self.path = &self.path[size..];
878 self.front = State::Done;
880 State::Done => unreachable!(),
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl<'a> DoubleEndedIterator for Components<'a> {
889 fn next_back(&mut self) -> Option<Component<'a>> {
890 while !self.finished() {
892 State::Body if self.path.len() > self.len_before_body() => {
893 let (size, comp) = self.parse_next_component_back();
894 self.path = &self.path[..self.path.len() - size];
900 self.back = State::StartDir;
903 self.back = State::Prefix;
904 if self.has_physical_root {
905 self.path = &self.path[..self.path.len() - 1];
906 return Some(Component::RootDir);
907 } else if let Some(p) = self.prefix {
908 if p.has_implicit_root() && !p.is_verbatim() {
909 return Some(Component::RootDir);
911 } else if self.include_cur_dir() {
912 self.path = &self.path[..self.path.len() - 1];
913 return Some(Component::CurDir);
916 State::Prefix if self.prefix_len() > 0 => {
917 self.back = State::Done;
918 return Some(Component::Prefix(PrefixComponent {
919 raw: unsafe { u8_slice_as_os_str(self.path) },
920 parsed: self.prefix.unwrap(),
924 self.back = State::Done;
927 State::Done => unreachable!(),
934 #[stable(feature = "fused", since = "1.26.0")]
935 impl FusedIterator for Components<'_> {}
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a> cmp::PartialEq for Components<'a> {
939 fn eq(&self, other: &Components<'a>) -> bool {
940 Iterator::eq(self.clone(), other.clone())
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl cmp::Eq for Components<'_> {}
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<'a> cmp::PartialOrd for Components<'a> {
949 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
950 Iterator::partial_cmp(self.clone(), other.clone())
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl cmp::Ord for Components<'_> {
956 fn cmp(&self, other: &Self) -> cmp::Ordering {
957 Iterator::cmp(self.clone(), other.clone())
961 /// An iterator over [`Path`] and its ancestors.
963 /// This `struct` is created by the [`ancestors`] method on [`Path`].
964 /// See its documentation for more.
969 /// use std::path::Path;
971 /// let path = Path::new("/foo/bar");
973 /// for ancestor in path.ancestors() {
974 /// println!("{}", ancestor.display());
978 /// [`ancestors`]: Path::ancestors
979 #[derive(Copy, Clone, Debug)]
980 #[stable(feature = "path_ancestors", since = "1.28.0")]
981 pub struct Ancestors<'a> {
982 next: Option<&'a Path>,
985 #[stable(feature = "path_ancestors", since = "1.28.0")]
986 impl<'a> Iterator for Ancestors<'a> {
987 type Item = &'a Path;
989 fn next(&mut self) -> Option<Self::Item> {
990 let next = self.next;
991 self.next = next.and_then(Path::parent);
996 #[stable(feature = "path_ancestors", since = "1.28.0")]
997 impl FusedIterator for Ancestors<'_> {}
999 ////////////////////////////////////////////////////////////////////////////////
1000 // Basic types and traits
1001 ////////////////////////////////////////////////////////////////////////////////
1003 /// An owned, mutable path (akin to [`String`]).
1005 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1006 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1007 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1009 /// [`push`]: PathBuf::push
1010 /// [`set_extension`]: PathBuf::set_extension
1012 /// More details about the overall approach can be found in
1013 /// the [module documentation](index.html).
1017 /// You can use [`push`] to build up a `PathBuf` from
1021 /// use std::path::PathBuf;
1023 /// let mut path = PathBuf::new();
1025 /// path.push(r"C:\");
1026 /// path.push("windows");
1027 /// path.push("system32");
1029 /// path.set_extension("dll");
1032 /// However, [`push`] is best used for dynamic situations. This is a better way
1033 /// to do this when you know all of the components ahead of time:
1036 /// use std::path::PathBuf;
1038 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1041 /// We can still do better than this! Since these are all strings, we can use
1045 /// use std::path::PathBuf;
1047 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1050 /// Which method works best depends on what kind of situation you're in.
1052 #[stable(feature = "rust1", since = "1.0.0")]
1054 // `PathBuf::as_mut_vec` current implementation relies
1055 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1056 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1057 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1058 // not documented and must not be relied upon.
1059 pub struct PathBuf {
1064 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1065 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1068 /// Allocates an empty `PathBuf`.
1073 /// use std::path::PathBuf;
1075 /// let path = PathBuf::new();
1077 #[stable(feature = "rust1", since = "1.0.0")]
1078 pub fn new() -> PathBuf {
1079 PathBuf { inner: OsString::new() }
1082 /// Creates a new `PathBuf` with a given capacity used to create the
1083 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1088 /// use std::path::PathBuf;
1090 /// let mut path = PathBuf::with_capacity(10);
1091 /// let capacity = path.capacity();
1093 /// // This push is done without reallocating
1094 /// path.push(r"C:\");
1096 /// assert_eq!(capacity, path.capacity());
1099 /// [`with_capacity`]: OsString::with_capacity
1100 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1101 pub fn with_capacity(capacity: usize) -> PathBuf {
1102 PathBuf { inner: OsString::with_capacity(capacity) }
1105 /// Coerces to a [`Path`] slice.
1110 /// use std::path::{Path, PathBuf};
1112 /// let p = PathBuf::from("/test");
1113 /// assert_eq!(Path::new("/test"), p.as_path());
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 pub fn as_path(&self) -> &Path {
1120 /// Extends `self` with `path`.
1122 /// If `path` is absolute, it replaces the current path.
1126 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1127 /// replaces everything except for the prefix (if any) of `self`.
1128 /// * if `path` has a prefix but no root, it replaces `self`.
1132 /// Pushing a relative path extends the existing path:
1135 /// use std::path::PathBuf;
1137 /// let mut path = PathBuf::from("/tmp");
1138 /// path.push("file.bk");
1139 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1142 /// Pushing an absolute path replaces the existing path:
1145 /// use std::path::PathBuf;
1147 /// let mut path = PathBuf::from("/tmp");
1148 /// path.push("/etc");
1149 /// assert_eq!(path, PathBuf::from("/etc"));
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1153 self._push(path.as_ref())
1156 fn _push(&mut self, path: &Path) {
1157 // in general, a separator is needed if the rightmost byte is not a separator
1158 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1160 // in the special case of `C:` on Windows, do *not* add a separator
1162 let comps = self.components();
1163 if comps.prefix_len() > 0
1164 && comps.prefix_len() == comps.path.len()
1165 && comps.prefix.unwrap().is_drive()
1171 // absolute `path` replaces `self`
1172 if path.is_absolute() || path.prefix().is_some() {
1173 self.as_mut_vec().truncate(0);
1175 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1176 } else if path.has_root() {
1177 let prefix_len = self.components().prefix_remaining();
1178 self.as_mut_vec().truncate(prefix_len);
1180 // `path` is a pure relative path
1181 } else if need_sep {
1182 self.inner.push(MAIN_SEP_STR);
1185 self.inner.push(path);
1188 /// Truncates `self` to [`self.parent`].
1190 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1191 /// Otherwise, returns `true`.
1193 /// [`self.parent`]: Path::parent
1198 /// use std::path::{Path, PathBuf};
1200 /// let mut p = PathBuf::from("/spirited/away.rs");
1203 /// assert_eq!(Path::new("/spirited"), p);
1205 /// assert_eq!(Path::new("/"), p);
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 pub fn pop(&mut self) -> bool {
1209 match self.parent().map(|p| p.as_u8_slice().len()) {
1211 self.as_mut_vec().truncate(len);
1218 /// Updates [`self.file_name`] to `file_name`.
1220 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1223 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1224 /// `file_name`. The new path will be a sibling of the original path.
1225 /// (That is, it will have the same parent.)
1227 /// [`self.file_name`]: Path::file_name
1228 /// [`pop`]: PathBuf::pop
1233 /// use std::path::PathBuf;
1235 /// let mut buf = PathBuf::from("/");
1236 /// assert!(buf.file_name() == None);
1237 /// buf.set_file_name("bar");
1238 /// assert!(buf == PathBuf::from("/bar"));
1239 /// assert!(buf.file_name().is_some());
1240 /// buf.set_file_name("baz.txt");
1241 /// assert!(buf == PathBuf::from("/baz.txt"));
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1245 self._set_file_name(file_name.as_ref())
1248 fn _set_file_name(&mut self, file_name: &OsStr) {
1249 if self.file_name().is_some() {
1250 let popped = self.pop();
1251 debug_assert!(popped);
1253 self.push(file_name);
1256 /// Updates [`self.extension`] to `extension`.
1258 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1259 /// returns `true` and updates the extension otherwise.
1261 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1264 /// [`self.file_name`]: Path::file_name
1265 /// [`self.extension`]: Path::extension
1270 /// use std::path::{Path, PathBuf};
1272 /// let mut p = PathBuf::from("/feel/the");
1274 /// p.set_extension("force");
1275 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1277 /// p.set_extension("dark_side");
1278 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1282 self._set_extension(extension.as_ref())
1285 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1286 let file_stem = match self.file_stem() {
1287 None => return false,
1288 Some(f) => os_str_as_u8_slice(f),
1291 // truncate until right after the file stem
1292 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1293 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1294 let v = self.as_mut_vec();
1295 v.truncate(end_file_stem.wrapping_sub(start));
1297 // add the new extension, if any
1298 let new = os_str_as_u8_slice(extension);
1299 if !new.is_empty() {
1300 v.reserve_exact(new.len() + 1);
1302 v.extend_from_slice(new);
1308 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1313 /// use std::path::PathBuf;
1315 /// let p = PathBuf::from("/the/head");
1316 /// let os_str = p.into_os_string();
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 pub fn into_os_string(self) -> OsString {
1323 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1324 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1325 pub fn into_boxed_path(self) -> Box<Path> {
1326 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1327 unsafe { Box::from_raw(rw) }
1330 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1332 /// [`capacity`]: OsString::capacity
1333 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1334 pub fn capacity(&self) -> usize {
1335 self.inner.capacity()
1338 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1340 /// [`clear`]: OsString::clear
1341 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1342 pub fn clear(&mut self) {
1346 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1348 /// [`reserve`]: OsString::reserve
1349 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1350 pub fn reserve(&mut self, additional: usize) {
1351 self.inner.reserve(additional)
1354 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1356 /// [`reserve_exact`]: OsString::reserve_exact
1357 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1358 pub fn reserve_exact(&mut self, additional: usize) {
1359 self.inner.reserve_exact(additional)
1362 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1364 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1365 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1366 pub fn shrink_to_fit(&mut self) {
1367 self.inner.shrink_to_fit()
1370 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1372 /// [`shrink_to`]: OsString::shrink_to
1373 #[unstable(feature = "shrink_to", issue = "56431")]
1374 pub fn shrink_to(&mut self, min_capacity: usize) {
1375 self.inner.shrink_to(min_capacity)
1379 #[stable(feature = "box_from_path", since = "1.17.0")]
1380 impl From<&Path> for Box<Path> {
1381 fn from(path: &Path) -> Box<Path> {
1382 let boxed: Box<OsStr> = path.inner.into();
1383 let rw = Box::into_raw(boxed) as *mut Path;
1384 unsafe { Box::from_raw(rw) }
1388 #[stable(feature = "box_from_cow", since = "1.45.0")]
1389 impl From<Cow<'_, Path>> for Box<Path> {
1391 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1393 Cow::Borrowed(path) => Box::from(path),
1394 Cow::Owned(path) => Box::from(path),
1399 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1400 impl From<Box<Path>> for PathBuf {
1401 /// Converts a `Box<Path>` into a `PathBuf`
1403 /// This conversion does not allocate or copy memory.
1404 fn from(boxed: Box<Path>) -> PathBuf {
1405 boxed.into_path_buf()
1409 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1410 impl From<PathBuf> for Box<Path> {
1411 /// Converts a `PathBuf` into a `Box<Path>`
1413 /// This conversion currently should not allocate memory,
1414 /// but this behavior is not guaranteed on all platforms or in all future versions.
1415 fn from(p: PathBuf) -> Box<Path> {
1420 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1421 impl Clone for Box<Path> {
1423 fn clone(&self) -> Self {
1424 self.to_path_buf().into_boxed_path()
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1430 fn from(s: &T) -> PathBuf {
1431 PathBuf::from(s.as_ref().to_os_string())
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 impl From<OsString> for PathBuf {
1437 /// Converts a `OsString` into a `PathBuf`
1439 /// This conversion does not allocate or copy memory.
1441 fn from(s: OsString) -> PathBuf {
1442 PathBuf { inner: s }
1446 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1447 impl From<PathBuf> for OsString {
1448 /// Converts a `PathBuf` into a `OsString`
1450 /// This conversion does not allocate or copy memory.
1451 fn from(path_buf: PathBuf) -> OsString {
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl From<String> for PathBuf {
1458 /// Converts a `String` into a `PathBuf`
1460 /// This conversion does not allocate or copy memory.
1461 fn from(s: String) -> PathBuf {
1462 PathBuf::from(OsString::from(s))
1466 #[stable(feature = "path_from_str", since = "1.32.0")]
1467 impl FromStr for PathBuf {
1468 type Err = core::convert::Infallible;
1470 fn from_str(s: &str) -> Result<Self, Self::Err> {
1471 Ok(PathBuf::from(s))
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1477 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1478 let mut buf = PathBuf::new();
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1486 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1487 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1491 fn extend_one(&mut self, p: P) {
1492 self.push(p.as_ref());
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 impl fmt::Debug for PathBuf {
1498 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1499 fmt::Debug::fmt(&**self, formatter)
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl ops::Deref for PathBuf {
1507 fn deref(&self) -> &Path {
1508 Path::new(&self.inner)
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 impl Borrow<Path> for PathBuf {
1514 fn borrow(&self) -> &Path {
1519 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1520 impl Default for PathBuf {
1521 fn default() -> Self {
1526 #[stable(feature = "cow_from_path", since = "1.6.0")]
1527 impl<'a> From<&'a Path> for Cow<'a, Path> {
1529 fn from(s: &'a Path) -> Cow<'a, Path> {
1534 #[stable(feature = "cow_from_path", since = "1.6.0")]
1535 impl<'a> From<PathBuf> for Cow<'a, Path> {
1537 fn from(s: PathBuf) -> Cow<'a, Path> {
1542 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1543 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1545 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1546 Cow::Borrowed(p.as_path())
1550 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1551 impl<'a> From<Cow<'a, Path>> for PathBuf {
1553 fn from(p: Cow<'a, Path>) -> Self {
1558 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1559 impl From<PathBuf> for Arc<Path> {
1560 /// Converts a `PathBuf` into an `Arc` by moving the `PathBuf` data into a new `Arc` buffer.
1562 fn from(s: PathBuf) -> Arc<Path> {
1563 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1564 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1568 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1569 impl From<&Path> for Arc<Path> {
1570 /// Converts a `Path` into an `Arc` by copying the `Path` data into a new `Arc` buffer.
1572 fn from(s: &Path) -> Arc<Path> {
1573 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1574 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1578 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1579 impl From<PathBuf> for Rc<Path> {
1580 /// Converts a `PathBuf` into an `Rc` by moving the `PathBuf` data into a new `Rc` buffer.
1582 fn from(s: PathBuf) -> Rc<Path> {
1583 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1584 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1588 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1589 impl From<&Path> for Rc<Path> {
1590 /// Converts a `Path` into an `Rc` by copying the `Path` data into a new `Rc` buffer.
1592 fn from(s: &Path) -> Rc<Path> {
1593 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1594 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl ToOwned for Path {
1600 type Owned = PathBuf;
1601 fn to_owned(&self) -> PathBuf {
1604 fn clone_into(&self, target: &mut PathBuf) {
1605 self.inner.clone_into(&mut target.inner);
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 impl cmp::PartialEq for PathBuf {
1611 fn eq(&self, other: &PathBuf) -> bool {
1612 self.components() == other.components()
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl Hash for PathBuf {
1618 fn hash<H: Hasher>(&self, h: &mut H) {
1619 self.as_path().hash(h)
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl cmp::Eq for PathBuf {}
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 impl cmp::PartialOrd for PathBuf {
1628 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1629 self.components().partial_cmp(other.components())
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl cmp::Ord for PathBuf {
1635 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1636 self.components().cmp(other.components())
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 impl AsRef<OsStr> for PathBuf {
1642 fn as_ref(&self) -> &OsStr {
1647 /// A slice of a path (akin to [`str`]).
1649 /// This type supports a number of operations for inspecting a path, including
1650 /// breaking the path into its components (separated by `/` on Unix and by either
1651 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1652 /// is absolute, and so on.
1654 /// This is an *unsized* type, meaning that it must always be used behind a
1655 /// pointer like `&` or [`Box`]. For an owned version of this type,
1656 /// see [`PathBuf`].
1658 /// More details about the overall approach can be found in
1659 /// the [module documentation](index.html).
1664 /// use std::path::Path;
1665 /// use std::ffi::OsStr;
1667 /// // Note: this example does work on Windows
1668 /// let path = Path::new("./foo/bar.txt");
1670 /// let parent = path.parent();
1671 /// assert_eq!(parent, Some(Path::new("./foo")));
1673 /// let file_stem = path.file_stem();
1674 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1676 /// let extension = path.extension();
1677 /// assert_eq!(extension, Some(OsStr::new("txt")));
1679 #[stable(feature = "rust1", since = "1.0.0")]
1681 // `Path::new` current implementation relies
1682 // on `Path` being layout-compatible with `OsStr`.
1683 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1684 // Anyway, `Path` representation and layout are considered implementation detail, are
1685 // not documented and must not be relied upon.
1690 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1693 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1694 /// See its documentation for more.
1696 /// [`strip_prefix`]: Path::strip_prefix
1697 #[derive(Debug, Clone, PartialEq, Eq)]
1698 #[stable(since = "1.7.0", feature = "strip_prefix")]
1699 pub struct StripPrefixError(());
1702 // The following (private!) function allows construction of a path from a u8
1703 // slice, which is only safe when it is known to follow the OsStr encoding.
1704 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1705 Path::new(u8_slice_as_os_str(s))
1707 // The following (private!) function reveals the byte encoding used for OsStr.
1708 fn as_u8_slice(&self) -> &[u8] {
1709 os_str_as_u8_slice(&self.inner)
1712 /// Directly wraps a string slice as a `Path` slice.
1714 /// This is a cost-free conversion.
1719 /// use std::path::Path;
1721 /// Path::new("foo.txt");
1724 /// You can create `Path`s from `String`s, or even other `Path`s:
1727 /// use std::path::Path;
1729 /// let string = String::from("foo.txt");
1730 /// let from_string = Path::new(&string);
1731 /// let from_path = Path::new(&from_string);
1732 /// assert_eq!(from_string, from_path);
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1736 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1739 /// Yields the underlying [`OsStr`] slice.
1744 /// use std::path::Path;
1746 /// let os_str = Path::new("foo.txt").as_os_str();
1747 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 pub fn as_os_str(&self) -> &OsStr {
1754 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1756 /// This conversion may entail doing a check for UTF-8 validity.
1757 /// Note that validation is performed because non-UTF-8 strings are
1758 /// perfectly valid for some OS.
1765 /// use std::path::Path;
1767 /// let path = Path::new("foo.txt");
1768 /// assert_eq!(path.to_str(), Some("foo.txt"));
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 pub fn to_str(&self) -> Option<&str> {
1775 /// Converts a `Path` to a [`Cow<str>`].
1777 /// Any non-Unicode sequences are replaced with
1778 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1780 /// [`Cow<str>`]: Cow
1781 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1785 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1788 /// use std::path::Path;
1790 /// let path = Path::new("foo.txt");
1791 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1794 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1795 /// have returned `"fo�.txt"`.
1796 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1798 self.inner.to_string_lossy()
1801 /// Converts a `Path` to an owned [`PathBuf`].
1806 /// use std::path::Path;
1808 /// let path_buf = Path::new("foo.txt").to_path_buf();
1809 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1811 #[rustc_conversion_suggestion]
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 pub fn to_path_buf(&self) -> PathBuf {
1814 PathBuf::from(self.inner.to_os_string())
1817 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1818 /// the current directory.
1820 /// * On Unix, a path is absolute if it starts with the root, so
1821 /// `is_absolute` and [`has_root`] are equivalent.
1823 /// * On Windows, a path is absolute if it has a prefix and starts with the
1824 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1829 /// use std::path::Path;
1831 /// assert!(!Path::new("foo.txt").is_absolute());
1834 /// [`has_root`]: Path::has_root
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 #[allow(deprecated)]
1837 pub fn is_absolute(&self) -> bool {
1838 if cfg!(target_os = "redox") {
1839 // FIXME: Allow Redox prefixes
1840 self.has_root() || has_redox_scheme(self.as_u8_slice())
1842 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1846 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1848 /// See [`is_absolute`]'s documentation for more details.
1853 /// use std::path::Path;
1855 /// assert!(Path::new("foo.txt").is_relative());
1858 /// [`is_absolute`]: Path::is_absolute
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 pub fn is_relative(&self) -> bool {
1864 fn prefix(&self) -> Option<Prefix<'_>> {
1865 self.components().prefix
1868 /// Returns `true` if the `Path` has a root.
1870 /// * On Unix, a path has a root if it begins with `/`.
1872 /// * On Windows, a path has a root if it:
1873 /// * has no prefix and begins with a separator, e.g., `\windows`
1874 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1875 /// * has any non-disk prefix, e.g., `\\server\share`
1880 /// use std::path::Path;
1882 /// assert!(Path::new("/etc/passwd").has_root());
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 pub fn has_root(&self) -> bool {
1886 self.components().has_root()
1889 /// Returns the `Path` without its final component, if there is one.
1891 /// Returns [`None`] if the path terminates in a root or prefix.
1896 /// use std::path::Path;
1898 /// let path = Path::new("/foo/bar");
1899 /// let parent = path.parent().unwrap();
1900 /// assert_eq!(parent, Path::new("/foo"));
1902 /// let grand_parent = parent.parent().unwrap();
1903 /// assert_eq!(grand_parent, Path::new("/"));
1904 /// assert_eq!(grand_parent.parent(), None);
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 pub fn parent(&self) -> Option<&Path> {
1908 let mut comps = self.components();
1909 let comp = comps.next_back();
1910 comp.and_then(|p| match p {
1911 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
1912 Some(comps.as_path())
1918 /// Produces an iterator over `Path` and its ancestors.
1920 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1921 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1922 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1923 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1929 /// use std::path::Path;
1931 /// let mut ancestors = Path::new("/foo/bar").ancestors();
1932 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1933 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1934 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1935 /// assert_eq!(ancestors.next(), None);
1937 /// let mut ancestors = Path::new("../foo/bar").ancestors();
1938 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
1939 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
1940 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
1941 /// assert_eq!(ancestors.next(), Some(Path::new("")));
1942 /// assert_eq!(ancestors.next(), None);
1945 /// [`parent`]: Path::parent
1946 #[stable(feature = "path_ancestors", since = "1.28.0")]
1947 pub fn ancestors(&self) -> Ancestors<'_> {
1948 Ancestors { next: Some(&self) }
1951 /// Returns the final component of the `Path`, if there is one.
1953 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1954 /// is the directory name.
1956 /// Returns [`None`] if the path terminates in `..`.
1961 /// use std::path::Path;
1962 /// use std::ffi::OsStr;
1964 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1965 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1966 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1967 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1968 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1969 /// assert_eq!(None, Path::new("/").file_name());
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 pub fn file_name(&self) -> Option<&OsStr> {
1973 self.components().next_back().and_then(|p| match p {
1974 Component::Normal(p) => Some(p),
1979 /// Returns a path that, when joined onto `base`, yields `self`.
1983 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
1984 /// returns `false`), returns [`Err`].
1986 /// [`starts_with`]: Path::starts_with
1991 /// use std::path::{Path, PathBuf};
1993 /// let path = Path::new("/test/haha/foo.txt");
1995 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
1996 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1997 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
1998 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
1999 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2001 /// assert!(path.strip_prefix("test").is_err());
2002 /// assert!(path.strip_prefix("/haha").is_err());
2004 /// let prefix = PathBuf::from("/test/");
2005 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2007 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2008 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2012 self._strip_prefix(base.as_ref())
2015 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2016 iter_after(self.components(), base.components())
2017 .map(|c| c.as_path())
2018 .ok_or(StripPrefixError(()))
2021 /// Determines whether `base` is a prefix of `self`.
2023 /// Only considers whole path components to match.
2028 /// use std::path::Path;
2030 /// let path = Path::new("/etc/passwd");
2032 /// assert!(path.starts_with("/etc"));
2033 /// assert!(path.starts_with("/etc/"));
2034 /// assert!(path.starts_with("/etc/passwd"));
2035 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2036 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2038 /// assert!(!path.starts_with("/e"));
2039 /// assert!(!path.starts_with("/etc/passwd.txt"));
2041 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2045 self._starts_with(base.as_ref())
2048 fn _starts_with(&self, base: &Path) -> bool {
2049 iter_after(self.components(), base.components()).is_some()
2052 /// Determines whether `child` is a suffix of `self`.
2054 /// Only considers whole path components to match.
2059 /// use std::path::Path;
2061 /// let path = Path::new("/etc/resolv.conf");
2063 /// assert!(path.ends_with("resolv.conf"));
2064 /// assert!(path.ends_with("etc/resolv.conf"));
2065 /// assert!(path.ends_with("/etc/resolv.conf"));
2067 /// assert!(!path.ends_with("/resolv.conf"));
2068 /// assert!(!path.ends_with("conf")); // use .extension() instead
2070 #[stable(feature = "rust1", since = "1.0.0")]
2071 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2072 self._ends_with(child.as_ref())
2075 fn _ends_with(&self, child: &Path) -> bool {
2076 iter_after(self.components().rev(), child.components().rev()).is_some()
2079 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2081 /// [`self.file_name`]: Path::file_name
2085 /// * [`None`], if there is no file name;
2086 /// * The entire file name if there is no embedded `.`;
2087 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2088 /// * Otherwise, the portion of the file name before the final `.`
2093 /// use std::path::Path;
2095 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2096 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 pub fn file_stem(&self) -> Option<&OsStr> {
2100 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2103 /// Extracts the extension of [`self.file_name`], if possible.
2105 /// The extension is:
2107 /// * [`None`], if there is no file name;
2108 /// * [`None`], if there is no embedded `.`;
2109 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2110 /// * Otherwise, the portion of the file name after the final `.`
2112 /// [`self.file_name`]: Path::file_name
2117 /// use std::path::Path;
2119 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2120 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2122 #[stable(feature = "rust1", since = "1.0.0")]
2123 pub fn extension(&self) -> Option<&OsStr> {
2124 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2127 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2129 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2134 /// use std::path::{Path, PathBuf};
2136 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2138 #[stable(feature = "rust1", since = "1.0.0")]
2140 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2141 self._join(path.as_ref())
2144 fn _join(&self, path: &Path) -> PathBuf {
2145 let mut buf = self.to_path_buf();
2150 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2152 /// See [`PathBuf::set_file_name`] for more details.
2157 /// use std::path::{Path, PathBuf};
2159 /// let path = Path::new("/tmp/foo.txt");
2160 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2162 /// let path = Path::new("/tmp");
2163 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2167 self._with_file_name(file_name.as_ref())
2170 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2171 let mut buf = self.to_path_buf();
2172 buf.set_file_name(file_name);
2176 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2178 /// See [`PathBuf::set_extension`] for more details.
2183 /// use std::path::{Path, PathBuf};
2185 /// let path = Path::new("foo.rs");
2186 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2188 /// let path = Path::new("foo.tar.gz");
2189 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2190 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2191 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2193 #[stable(feature = "rust1", since = "1.0.0")]
2194 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2195 self._with_extension(extension.as_ref())
2198 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2199 let mut buf = self.to_path_buf();
2200 buf.set_extension(extension);
2204 /// Produces an iterator over the [`Component`]s of the path.
2206 /// When parsing the path, there is a small amount of normalization:
2208 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2209 /// `a` and `b` as components.
2211 /// * Occurrences of `.` are normalized away, except if they are at the
2212 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2213 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2214 /// an additional [`CurDir`] component.
2216 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2218 /// Note that no other normalization takes place; in particular, `a/c`
2219 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2220 /// is a symbolic link (so its parent isn't `a`).
2225 /// use std::path::{Path, Component};
2226 /// use std::ffi::OsStr;
2228 /// let mut components = Path::new("/tmp/foo.txt").components();
2230 /// assert_eq!(components.next(), Some(Component::RootDir));
2231 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2232 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2233 /// assert_eq!(components.next(), None)
2236 /// [`CurDir`]: Component::CurDir
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 pub fn components(&self) -> Components<'_> {
2239 let prefix = parse_prefix(self.as_os_str());
2241 path: self.as_u8_slice(),
2243 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2244 || has_redox_scheme(self.as_u8_slice()),
2245 front: State::Prefix,
2250 /// Produces an iterator over the path's components viewed as [`OsStr`]
2253 /// For more information about the particulars of how the path is separated
2254 /// into components, see [`components`].
2256 /// [`components`]: Path::components
2261 /// use std::path::{self, Path};
2262 /// use std::ffi::OsStr;
2264 /// let mut it = Path::new("/tmp/foo.txt").iter();
2265 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2266 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2267 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2268 /// assert_eq!(it.next(), None)
2270 #[stable(feature = "rust1", since = "1.0.0")]
2271 pub fn iter(&self) -> Iter<'_> {
2272 Iter { inner: self.components() }
2275 /// Returns an object that implements [`Display`] for safely printing paths
2276 /// that may contain non-Unicode data.
2278 /// [`Display`]: fmt::Display
2283 /// use std::path::Path;
2285 /// let path = Path::new("/tmp/foo.rs");
2287 /// println!("{}", path.display());
2289 #[stable(feature = "rust1", since = "1.0.0")]
2290 pub fn display(&self) -> Display<'_> {
2291 Display { path: self }
2294 /// Queries the file system to get information about a file, directory, etc.
2296 /// This function will traverse symbolic links to query information about the
2297 /// destination file.
2299 /// This is an alias to [`fs::metadata`].
2304 /// use std::path::Path;
2306 /// let path = Path::new("/Minas/tirith");
2307 /// let metadata = path.metadata().expect("metadata call failed");
2308 /// println!("{:?}", metadata.file_type());
2310 #[stable(feature = "path_ext", since = "1.5.0")]
2311 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2315 /// Queries the metadata about a file without following symlinks.
2317 /// This is an alias to [`fs::symlink_metadata`].
2322 /// use std::path::Path;
2324 /// let path = Path::new("/Minas/tirith");
2325 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2326 /// println!("{:?}", metadata.file_type());
2328 #[stable(feature = "path_ext", since = "1.5.0")]
2329 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2330 fs::symlink_metadata(self)
2333 /// Returns the canonical, absolute form of the path with all intermediate
2334 /// components normalized and symbolic links resolved.
2336 /// This is an alias to [`fs::canonicalize`].
2341 /// use std::path::{Path, PathBuf};
2343 /// let path = Path::new("/foo/test/../test/bar.rs");
2344 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2346 #[stable(feature = "path_ext", since = "1.5.0")]
2347 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2348 fs::canonicalize(self)
2351 /// Reads a symbolic link, returning the file that the link points to.
2353 /// This is an alias to [`fs::read_link`].
2358 /// use std::path::Path;
2360 /// let path = Path::new("/laputa/sky_castle.rs");
2361 /// let path_link = path.read_link().expect("read_link call failed");
2363 #[stable(feature = "path_ext", since = "1.5.0")]
2364 pub fn read_link(&self) -> io::Result<PathBuf> {
2368 /// Returns an iterator over the entries within a directory.
2370 /// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New
2371 /// errors may be encountered after an iterator is initially constructed.
2373 /// This is an alias to [`fs::read_dir`].
2378 /// use std::path::Path;
2380 /// let path = Path::new("/laputa");
2381 /// for entry in path.read_dir().expect("read_dir call failed") {
2382 /// if let Ok(entry) = entry {
2383 /// println!("{:?}", entry.path());
2387 #[stable(feature = "path_ext", since = "1.5.0")]
2388 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2392 /// Returns `true` if the path points at an existing entity.
2394 /// This function will traverse symbolic links to query information about the
2395 /// destination file. In case of broken symbolic links this will return `false`.
2397 /// If you cannot access the directory containing the file, e.g., because of a
2398 /// permission error, this will return `false`.
2403 /// use std::path::Path;
2404 /// assert!(!Path::new("does_not_exist.txt").exists());
2409 /// This is a convenience function that coerces errors to false. If you want to
2410 /// check errors, call [`fs::metadata`].
2411 #[stable(feature = "path_ext", since = "1.5.0")]
2412 pub fn exists(&self) -> bool {
2413 fs::metadata(self).is_ok()
2416 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2418 /// This function will traverse symbolic links to query information about the
2419 /// destination file. In case of broken symbolic links this will return `false`.
2421 /// If you cannot access the directory containing the file, e.g., because of a
2422 /// permission error, this will return `false`.
2427 /// use std::path::Path;
2428 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2429 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2434 /// This is a convenience function that coerces errors to false. If you want to
2435 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2436 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2438 /// When the goal is simply to read from (or write to) the source, the most
2439 /// reliable way to test the source can be read (or written to) is to open
2440 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2441 /// a Unix-like system for example. See [`fs::File::open`] or
2442 /// [`fs::OpenOptions::open`] for more information.
2443 #[stable(feature = "path_ext", since = "1.5.0")]
2444 pub fn is_file(&self) -> bool {
2445 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2448 /// Returns `true` if the path exists on disk and is pointing at a directory.
2450 /// This function will traverse symbolic links to query information about the
2451 /// destination file. In case of broken symbolic links this will return `false`.
2453 /// If you cannot access the directory containing the file, e.g., because of a
2454 /// permission error, this will return `false`.
2459 /// use std::path::Path;
2460 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2461 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2466 /// This is a convenience function that coerces errors to false. If you want to
2467 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2468 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2469 #[stable(feature = "path_ext", since = "1.5.0")]
2470 pub fn is_dir(&self) -> bool {
2471 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2474 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2476 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2477 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2478 let rw = Box::into_raw(self) as *mut OsStr;
2479 let inner = unsafe { Box::from_raw(rw) };
2480 PathBuf { inner: OsString::from(inner) }
2484 #[stable(feature = "rust1", since = "1.0.0")]
2485 impl AsRef<OsStr> for Path {
2486 fn as_ref(&self) -> &OsStr {
2491 #[stable(feature = "rust1", since = "1.0.0")]
2492 impl fmt::Debug for Path {
2493 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2494 fmt::Debug::fmt(&self.inner, formatter)
2498 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2500 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2501 /// [`Display`] trait in a way that mitigates that. It is created by the
2502 /// [`display`][`Path::display`] method on [`Path`].
2507 /// use std::path::Path;
2509 /// let path = Path::new("/tmp/foo.rs");
2511 /// println!("{}", path.display());
2514 /// [`Display`]: fmt::Display
2515 /// [`format!`]: crate::format
2516 #[stable(feature = "rust1", since = "1.0.0")]
2517 pub struct Display<'a> {
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl fmt::Debug for Display<'_> {
2523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2524 fmt::Debug::fmt(&self.path, f)
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 impl fmt::Display for Display<'_> {
2530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2531 self.path.inner.display(f)
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 impl cmp::PartialEq for Path {
2537 fn eq(&self, other: &Path) -> bool {
2538 self.components().eq(other.components())
2542 #[stable(feature = "rust1", since = "1.0.0")]
2543 impl Hash for Path {
2544 fn hash<H: Hasher>(&self, h: &mut H) {
2545 for component in self.components() {
2551 #[stable(feature = "rust1", since = "1.0.0")]
2552 impl cmp::Eq for Path {}
2554 #[stable(feature = "rust1", since = "1.0.0")]
2555 impl cmp::PartialOrd for Path {
2556 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2557 self.components().partial_cmp(other.components())
2561 #[stable(feature = "rust1", since = "1.0.0")]
2562 impl cmp::Ord for Path {
2563 fn cmp(&self, other: &Path) -> cmp::Ordering {
2564 self.components().cmp(other.components())
2568 #[stable(feature = "rust1", since = "1.0.0")]
2569 impl AsRef<Path> for Path {
2570 fn as_ref(&self) -> &Path {
2575 #[stable(feature = "rust1", since = "1.0.0")]
2576 impl AsRef<Path> for OsStr {
2577 fn as_ref(&self) -> &Path {
2582 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2583 impl AsRef<Path> for Cow<'_, OsStr> {
2584 fn as_ref(&self) -> &Path {
2589 #[stable(feature = "rust1", since = "1.0.0")]
2590 impl AsRef<Path> for OsString {
2591 fn as_ref(&self) -> &Path {
2596 #[stable(feature = "rust1", since = "1.0.0")]
2597 impl AsRef<Path> for str {
2599 fn as_ref(&self) -> &Path {
2604 #[stable(feature = "rust1", since = "1.0.0")]
2605 impl AsRef<Path> for String {
2606 fn as_ref(&self) -> &Path {
2611 #[stable(feature = "rust1", since = "1.0.0")]
2612 impl AsRef<Path> for PathBuf {
2614 fn as_ref(&self) -> &Path {
2619 #[stable(feature = "path_into_iter", since = "1.6.0")]
2620 impl<'a> IntoIterator for &'a PathBuf {
2621 type Item = &'a OsStr;
2622 type IntoIter = Iter<'a>;
2623 fn into_iter(self) -> Iter<'a> {
2628 #[stable(feature = "path_into_iter", since = "1.6.0")]
2629 impl<'a> IntoIterator for &'a Path {
2630 type Item = &'a OsStr;
2631 type IntoIter = Iter<'a>;
2632 fn into_iter(self) -> Iter<'a> {
2637 macro_rules! impl_cmp {
2638 ($lhs:ty, $rhs: ty) => {
2639 #[stable(feature = "partialeq_path", since = "1.6.0")]
2640 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2642 fn eq(&self, other: &$rhs) -> bool {
2643 <Path as PartialEq>::eq(self, other)
2647 #[stable(feature = "partialeq_path", since = "1.6.0")]
2648 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2650 fn eq(&self, other: &$lhs) -> bool {
2651 <Path as PartialEq>::eq(self, other)
2655 #[stable(feature = "cmp_path", since = "1.8.0")]
2656 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2658 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2659 <Path as PartialOrd>::partial_cmp(self, other)
2663 #[stable(feature = "cmp_path", since = "1.8.0")]
2664 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2666 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2667 <Path as PartialOrd>::partial_cmp(self, other)
2673 impl_cmp!(PathBuf, Path);
2674 impl_cmp!(PathBuf, &'a Path);
2675 impl_cmp!(Cow<'a, Path>, Path);
2676 impl_cmp!(Cow<'a, Path>, &'b Path);
2677 impl_cmp!(Cow<'a, Path>, PathBuf);
2679 macro_rules! impl_cmp_os_str {
2680 ($lhs:ty, $rhs: ty) => {
2681 #[stable(feature = "cmp_path", since = "1.8.0")]
2682 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2684 fn eq(&self, other: &$rhs) -> bool {
2685 <Path as PartialEq>::eq(self, other.as_ref())
2689 #[stable(feature = "cmp_path", since = "1.8.0")]
2690 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2692 fn eq(&self, other: &$lhs) -> bool {
2693 <Path as PartialEq>::eq(self.as_ref(), other)
2697 #[stable(feature = "cmp_path", since = "1.8.0")]
2698 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2700 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2701 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2705 #[stable(feature = "cmp_path", since = "1.8.0")]
2706 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2708 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2709 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2715 impl_cmp_os_str!(PathBuf, OsStr);
2716 impl_cmp_os_str!(PathBuf, &'a OsStr);
2717 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2718 impl_cmp_os_str!(PathBuf, OsString);
2719 impl_cmp_os_str!(Path, OsStr);
2720 impl_cmp_os_str!(Path, &'a OsStr);
2721 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2722 impl_cmp_os_str!(Path, OsString);
2723 impl_cmp_os_str!(&'a Path, OsStr);
2724 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2725 impl_cmp_os_str!(&'a Path, OsString);
2726 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2727 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2728 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2730 #[stable(since = "1.7.0", feature = "strip_prefix")]
2731 impl fmt::Display for StripPrefixError {
2732 #[allow(deprecated, deprecated_in_future)]
2733 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2734 self.description().fmt(f)
2738 #[stable(since = "1.7.0", feature = "strip_prefix")]
2739 impl Error for StripPrefixError {
2740 #[allow(deprecated)]
2741 fn description(&self) -> &str {