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")]
61 #![deny(unsafe_op_in_unsafe_fn)]
66 use crate::borrow::{Borrow, Cow};
68 use crate::error::Error;
71 use crate::hash::{Hash, Hasher};
73 use crate::iter::{self, FusedIterator};
74 use crate::ops::{self, Deref};
76 use crate::str::FromStr;
79 use crate::ffi::{OsStr, OsString};
81 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
83 ////////////////////////////////////////////////////////////////////////////////
85 ////////////////////////////////////////////////////////////////////////////////
87 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
88 // taking advantage of the fact that OsStr always encodes ASCII characters
89 // as-is. Eventually, this transmutation should be replaced by direct uses of
90 // OsStr APIs for parsing, but it will take a while for those to become
93 ////////////////////////////////////////////////////////////////////////////////
95 ////////////////////////////////////////////////////////////////////////////////
97 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
99 /// Windows uses a variety of path prefix styles, including references to drive
100 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
101 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
102 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
103 /// no normalization is performed.
108 /// use std::path::{Component, Path, Prefix};
109 /// use std::path::Prefix::*;
110 /// use std::ffi::OsStr;
112 /// fn get_path_prefix(s: &str) -> Prefix {
113 /// let path = Path::new(s);
114 /// match path.components().next().unwrap() {
115 /// Component::Prefix(prefix_component) => prefix_component.kind(),
120 /// # if cfg!(windows) {
121 /// assert_eq!(Verbatim(OsStr::new("pictures")),
122 /// get_path_prefix(r"\\?\pictures\kittens"));
123 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
124 /// get_path_prefix(r"\\?\UNC\server\share"));
125 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
126 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
127 /// get_path_prefix(r"\\.\BrainInterface"));
128 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
129 /// get_path_prefix(r"\\server\share"));
130 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
133 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub enum Prefix<'a> {
136 /// Verbatim prefix, e.g., `\\?\cat_pics`.
138 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
140 #[stable(feature = "rust1", since = "1.0.0")]
141 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
143 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
144 /// e.g., `\\?\UNC\server\share`.
146 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
147 /// server's hostname and a share name.
148 #[stable(feature = "rust1", since = "1.0.0")]
150 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
151 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
154 /// Verbatim disk prefix, e.g., `\\?\C:`.
156 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
157 /// drive letter and `:`.
158 #[stable(feature = "rust1", since = "1.0.0")]
159 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
161 /// Device namespace prefix, e.g., `\\.\COM42`.
163 /// Device namespace prefixes consist of `\\.\` immediately followed by the
165 #[stable(feature = "rust1", since = "1.0.0")]
166 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
168 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
169 /// `\\server\share`.
171 /// UNC prefixes consist of the server's hostname and a share name.
172 #[stable(feature = "rust1", since = "1.0.0")]
174 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
175 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
178 /// Prefix `C:` for the given disk drive.
179 #[stable(feature = "rust1", since = "1.0.0")]
180 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
183 impl<'a> Prefix<'a> {
185 fn len(&self) -> usize {
187 fn os_str_len(s: &OsStr) -> usize {
188 os_str_as_u8_slice(s).len()
191 Verbatim(x) => 4 + os_str_len(x),
192 VerbatimUNC(x, y) => {
193 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
195 VerbatimDisk(_) => 6,
196 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
197 DeviceNS(x) => 4 + os_str_len(x),
202 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
207 /// use std::path::Prefix::*;
208 /// use std::ffi::OsStr;
210 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
211 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
212 /// assert!(VerbatimDisk(b'C').is_verbatim());
213 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
214 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
215 /// assert!(!Disk(b'C').is_verbatim());
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn is_verbatim(&self) -> bool {
221 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
225 fn is_drive(&self) -> bool {
226 matches!(*self, Prefix::Disk(_))
230 fn has_implicit_root(&self) -> bool {
235 ////////////////////////////////////////////////////////////////////////////////
236 // Exposed parsing helpers
237 ////////////////////////////////////////////////////////////////////////////////
239 /// Determines whether the character is one of the permitted path
240 /// separators for the current platform.
247 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
248 /// assert!(!path::is_separator('❤'));
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn is_separator(c: char) -> bool {
252 c.is_ascii() && is_sep_byte(c as u8)
255 /// The primary separator of path components for the current platform.
257 /// For example, `/` on Unix and `\` on Windows.
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
261 ////////////////////////////////////////////////////////////////////////////////
263 ////////////////////////////////////////////////////////////////////////////////
265 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
266 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
267 // `iter` after having exhausted `prefix`.
268 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
270 I: Iterator<Item = Component<'a>> + Clone,
271 J: Iterator<Item = Component<'b>>,
274 let mut iter_next = iter.clone();
275 match (iter_next.next(), prefix.next()) {
276 (Some(ref x), Some(ref y)) if x == y => (),
277 (Some(_), Some(_)) => return None,
278 (Some(_), None) => return Some(iter),
279 (None, None) => return Some(iter),
280 (None, Some(_)) => return None,
286 // See note at the top of this module to understand why these are used:
288 // These casts are safe as OsStr is internally a wrapper around [u8] on all
291 // Note that currently this relies on the special knowledge that libstd has;
292 // these types are single-element structs but are not marked repr(transparent)
293 // or repr(C) which would make these casts allowable outside std.
294 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
295 unsafe { &*(s as *const OsStr as *const [u8]) }
297 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
298 // SAFETY: see the comment of `os_str_as_u8_slice`
299 unsafe { &*(s as *const [u8] as *const OsStr) }
302 // Detect scheme on Redox
303 fn has_redox_scheme(s: &[u8]) -> bool {
304 cfg!(target_os = "redox") && s.contains(&b':')
307 ////////////////////////////////////////////////////////////////////////////////
308 // Cross-platform, iterator-independent parsing
309 ////////////////////////////////////////////////////////////////////////////////
311 /// Says whether the first byte after the prefix is a separator.
312 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
313 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
314 !path.is_empty() && is_sep_byte(path[0])
317 // basic workhorse for splitting stem and extension
318 fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
319 if os_str_as_u8_slice(file) == b".." {
320 return (Some(file), None);
323 // The unsafety here stems from converting between &OsStr and &[u8]
324 // and back. This is safe to do because (1) we only look at ASCII
325 // contents of the encoding and (2) new &OsStr values are produced
326 // only from ASCII-bounded slices of existing &OsStr values.
327 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
328 let after = iter.next();
329 let before = iter.next();
330 if before == Some(b"") {
333 unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
337 fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
338 let slice = os_str_as_u8_slice(file);
343 // The unsafety here stems from converting between &OsStr and &[u8]
344 // and back. This is safe to do because (1) we only look at ASCII
345 // contents of the encoding and (2) new &OsStr values are produced
346 // only from ASCII-bounded slices of existing &OsStr values.
347 let i = match slice[1..].iter().position(|b| *b == b'.') {
349 None => return (file, None),
351 let before = &slice[..i];
352 let after = &slice[i + 1..];
353 unsafe { (u8_slice_as_os_str(before), Some(u8_slice_as_os_str(after))) }
356 ////////////////////////////////////////////////////////////////////////////////
357 // The core iterators
358 ////////////////////////////////////////////////////////////////////////////////
360 /// Component parsing works by a double-ended state machine; the cursors at the
361 /// front and back of the path each keep track of what parts of the path have
362 /// been consumed so far.
364 /// Going front to back, a path is made up of a prefix, a starting
365 /// directory component, and a body (of normal components)
366 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
369 StartDir = 1, // / or . or nothing
370 Body = 2, // foo/bar/baz
374 /// A structure wrapping a Windows path prefix as well as its unparsed string
377 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
378 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
379 /// returned by [`as_os_str`].
381 /// Instances of this `struct` can be obtained by matching against the
382 /// [`Prefix` variant] on [`Component`].
384 /// Does not occur on Unix.
389 /// # if cfg!(windows) {
390 /// use std::path::{Component, Path, Prefix};
391 /// use std::ffi::OsStr;
393 /// let path = Path::new(r"c:\you\later\");
394 /// match path.components().next().unwrap() {
395 /// Component::Prefix(prefix_component) => {
396 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
397 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
399 /// _ => unreachable!(),
404 /// [`as_os_str`]: PrefixComponent::as_os_str
405 /// [`kind`]: PrefixComponent::kind
406 /// [`Prefix` variant]: Component::Prefix
407 #[stable(feature = "rust1", since = "1.0.0")]
408 #[derive(Copy, Clone, Eq, Debug)]
409 pub struct PrefixComponent<'a> {
410 /// The prefix as an unparsed `OsStr` slice.
413 /// The parsed prefix data.
417 impl<'a> PrefixComponent<'a> {
418 /// Returns the parsed prefix data.
420 /// See [`Prefix`]'s documentation for more information on the different
421 /// kinds of prefixes.
422 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn kind(&self) -> Prefix<'a> {
428 /// Returns the raw [`OsStr`] slice for this prefix.
429 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn as_os_str(&self) -> &'a OsStr {
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
439 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
440 cmp::PartialEq::eq(&self.parsed, &other.parsed)
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
447 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
448 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl cmp::Ord for PrefixComponent<'_> {
455 fn cmp(&self, other: &Self) -> cmp::Ordering {
456 cmp::Ord::cmp(&self.parsed, &other.parsed)
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl Hash for PrefixComponent<'_> {
462 fn hash<H: Hasher>(&self, h: &mut H) {
467 /// A single component of a path.
469 /// A `Component` roughly corresponds to a substring between path separators
472 /// This `enum` is created by iterating over [`Components`], which in turn is
473 /// created by the [`components`](Path::components) method on [`Path`].
478 /// use std::path::{Component, Path};
480 /// let path = Path::new("/tmp/foo/bar.txt");
481 /// let components = path.components().collect::<Vec<_>>();
482 /// assert_eq!(&components, &[
483 /// Component::RootDir,
484 /// Component::Normal("tmp".as_ref()),
485 /// Component::Normal("foo".as_ref()),
486 /// Component::Normal("bar.txt".as_ref()),
489 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub enum Component<'a> {
492 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
494 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
497 /// Does not occur on Unix.
498 #[stable(feature = "rust1", since = "1.0.0")]
499 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
501 /// The root directory component, appears after any prefix and before anything else.
503 /// It represents a separator that designates that a path starts from root.
504 #[stable(feature = "rust1", since = "1.0.0")]
507 /// A reference to the current directory, i.e., `.`.
508 #[stable(feature = "rust1", since = "1.0.0")]
511 /// A reference to the parent directory, i.e., `..`.
512 #[stable(feature = "rust1", since = "1.0.0")]
515 /// A normal component, e.g., `a` and `b` in `a/b`.
517 /// This variant is the most common one, it represents references to files
519 #[stable(feature = "rust1", since = "1.0.0")]
520 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
523 impl<'a> Component<'a> {
524 /// Extracts the underlying [`OsStr`] slice.
529 /// use std::path::Path;
531 /// let path = Path::new("./tmp/foo/bar.txt");
532 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
533 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn as_os_str(self) -> &'a OsStr {
538 Component::Prefix(p) => p.as_os_str(),
539 Component::RootDir => OsStr::new(MAIN_SEP_STR),
540 Component::CurDir => OsStr::new("."),
541 Component::ParentDir => OsStr::new(".."),
542 Component::Normal(path) => path,
547 #[stable(feature = "rust1", since = "1.0.0")]
548 impl AsRef<OsStr> for Component<'_> {
550 fn as_ref(&self) -> &OsStr {
555 #[stable(feature = "path_component_asref", since = "1.25.0")]
556 impl AsRef<Path> for Component<'_> {
558 fn as_ref(&self) -> &Path {
559 self.as_os_str().as_ref()
563 /// An iterator over the [`Component`]s of a [`Path`].
565 /// This `struct` is created by the [`components`] method on [`Path`].
566 /// See its documentation for more.
571 /// use std::path::Path;
573 /// let path = Path::new("/tmp/foo/bar.txt");
575 /// for component in path.components() {
576 /// println!("{:?}", component);
580 /// [`components`]: Path::components
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub struct Components<'a> {
584 // The path left to parse components from
587 // The prefix as it was originally parsed, if any
588 prefix: Option<Prefix<'a>>,
590 // true if path *physically* has a root separator; for most Windows
591 // prefixes, it may have a "logical" root separator for the purposes of
592 // normalization, e.g., \\server\share == \\server\share\.
593 has_physical_root: bool,
595 // The iterator is double-ended, and these two states keep track of what has
596 // been produced from either end
601 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
603 /// This `struct` is created by the [`iter`] method on [`Path`].
604 /// See its documentation for more.
606 /// [`iter`]: Path::iter
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub struct Iter<'a> {
610 inner: Components<'a>,
613 #[stable(feature = "path_components_debug", since = "1.13.0")]
614 impl fmt::Debug for Components<'_> {
615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 struct DebugHelper<'a>(&'a Path);
618 impl fmt::Debug for DebugHelper<'_> {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 f.debug_list().entries(self.0.components()).finish()
624 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
628 impl<'a> Components<'a> {
629 // how long is the prefix, if any?
631 fn prefix_len(&self) -> usize {
632 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
636 fn prefix_verbatim(&self) -> bool {
637 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
640 /// how much of the prefix is left from the point of view of iteration?
642 fn prefix_remaining(&self) -> usize {
643 if self.front == State::Prefix { self.prefix_len() } else { 0 }
646 // Given the iteration so far, how much of the pre-State::Body path is left?
648 fn len_before_body(&self) -> usize {
649 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
650 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
651 self.prefix_remaining() + root + cur_dir
654 // is the iteration complete?
656 fn finished(&self) -> bool {
657 self.front == State::Done || self.back == State::Done || self.front > self.back
661 fn is_sep_byte(&self, b: u8) -> bool {
662 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
665 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
670 /// use std::path::Path;
672 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
673 /// components.next();
674 /// components.next();
676 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn as_path(&self) -> &'a Path {
680 let mut comps = self.clone();
681 if comps.front == State::Body {
684 if comps.back == State::Body {
687 unsafe { Path::from_u8_slice(comps.path) }
690 /// Is the *original* path rooted?
691 fn has_root(&self) -> bool {
692 if self.has_physical_root {
695 if let Some(p) = self.prefix {
696 if p.has_implicit_root() {
703 /// Should the normalized path include a leading . ?
704 fn include_cur_dir(&self) -> bool {
708 let mut iter = self.path[self.prefix_len()..].iter();
709 match (iter.next(), iter.next()) {
710 (Some(&b'.'), None) => true,
711 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
716 // parse a given byte sequence into the corresponding path component
717 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
719 b"." if self.prefix_verbatim() => Some(Component::CurDir),
720 b"." => None, // . components are normalized away, except at
721 // the beginning of a path, which is treated
722 // separately via `include_cur_dir`
723 b".." => Some(Component::ParentDir),
725 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
729 // parse a component from the left, saying how many bytes to consume to
730 // remove the component
731 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
732 debug_assert!(self.front == State::Body);
733 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
734 None => (0, self.path),
735 Some(i) => (1, &self.path[..i]),
737 (comp.len() + extra, self.parse_single_component(comp))
740 // parse a component from the right, saying how many bytes to consume to
741 // remove the component
742 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
743 debug_assert!(self.back == State::Body);
744 let start = self.len_before_body();
745 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
746 None => (0, &self.path[start..]),
747 Some(i) => (1, &self.path[start + i + 1..]),
749 (comp.len() + extra, self.parse_single_component(comp))
752 // trim away repeated separators (i.e., empty components) on the left
753 fn trim_left(&mut self) {
754 while !self.path.is_empty() {
755 let (size, comp) = self.parse_next_component();
759 self.path = &self.path[size..];
764 // trim away repeated separators (i.e., empty components) on the right
765 fn trim_right(&mut self) {
766 while self.path.len() > self.len_before_body() {
767 let (size, comp) = self.parse_next_component_back();
771 self.path = &self.path[..self.path.len() - size];
777 #[stable(feature = "rust1", since = "1.0.0")]
778 impl AsRef<Path> for Components<'_> {
780 fn as_ref(&self) -> &Path {
785 #[stable(feature = "rust1", since = "1.0.0")]
786 impl AsRef<OsStr> for Components<'_> {
788 fn as_ref(&self) -> &OsStr {
789 self.as_path().as_os_str()
793 #[stable(feature = "path_iter_debug", since = "1.13.0")]
794 impl fmt::Debug for Iter<'_> {
795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796 struct DebugHelper<'a>(&'a Path);
798 impl fmt::Debug for DebugHelper<'_> {
799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800 f.debug_list().entries(self.0.iter()).finish()
804 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
809 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
814 /// use std::path::Path;
816 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
820 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
822 #[stable(feature = "rust1", since = "1.0.0")]
824 pub fn as_path(&self) -> &'a Path {
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl AsRef<Path> for Iter<'_> {
832 fn as_ref(&self) -> &Path {
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl AsRef<OsStr> for Iter<'_> {
840 fn as_ref(&self) -> &OsStr {
841 self.as_path().as_os_str()
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<'a> Iterator for Iter<'a> {
847 type Item = &'a OsStr;
850 fn next(&mut self) -> Option<&'a OsStr> {
851 self.inner.next().map(Component::as_os_str)
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl<'a> DoubleEndedIterator for Iter<'a> {
858 fn next_back(&mut self) -> Option<&'a OsStr> {
859 self.inner.next_back().map(Component::as_os_str)
863 #[stable(feature = "fused", since = "1.26.0")]
864 impl FusedIterator for Iter<'_> {}
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a> Iterator for Components<'a> {
868 type Item = Component<'a>;
870 fn next(&mut self) -> Option<Component<'a>> {
871 while !self.finished() {
873 State::Prefix if self.prefix_len() > 0 => {
874 self.front = State::StartDir;
875 debug_assert!(self.prefix_len() <= self.path.len());
876 let raw = &self.path[..self.prefix_len()];
877 self.path = &self.path[self.prefix_len()..];
878 return Some(Component::Prefix(PrefixComponent {
879 raw: unsafe { u8_slice_as_os_str(raw) },
880 parsed: self.prefix.unwrap(),
884 self.front = State::StartDir;
887 self.front = State::Body;
888 if self.has_physical_root {
889 debug_assert!(!self.path.is_empty());
890 self.path = &self.path[1..];
891 return Some(Component::RootDir);
892 } else if let Some(p) = self.prefix {
893 if p.has_implicit_root() && !p.is_verbatim() {
894 return Some(Component::RootDir);
896 } else if self.include_cur_dir() {
897 debug_assert!(!self.path.is_empty());
898 self.path = &self.path[1..];
899 return Some(Component::CurDir);
902 State::Body if !self.path.is_empty() => {
903 let (size, comp) = self.parse_next_component();
904 self.path = &self.path[size..];
910 self.front = State::Done;
912 State::Done => unreachable!(),
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl<'a> DoubleEndedIterator for Components<'a> {
921 fn next_back(&mut self) -> Option<Component<'a>> {
922 while !self.finished() {
924 State::Body if self.path.len() > self.len_before_body() => {
925 let (size, comp) = self.parse_next_component_back();
926 self.path = &self.path[..self.path.len() - size];
932 self.back = State::StartDir;
935 self.back = State::Prefix;
936 if self.has_physical_root {
937 self.path = &self.path[..self.path.len() - 1];
938 return Some(Component::RootDir);
939 } else if let Some(p) = self.prefix {
940 if p.has_implicit_root() && !p.is_verbatim() {
941 return Some(Component::RootDir);
943 } else if self.include_cur_dir() {
944 self.path = &self.path[..self.path.len() - 1];
945 return Some(Component::CurDir);
948 State::Prefix if self.prefix_len() > 0 => {
949 self.back = State::Done;
950 return Some(Component::Prefix(PrefixComponent {
951 raw: unsafe { u8_slice_as_os_str(self.path) },
952 parsed: self.prefix.unwrap(),
956 self.back = State::Done;
959 State::Done => unreachable!(),
966 #[stable(feature = "fused", since = "1.26.0")]
967 impl FusedIterator for Components<'_> {}
969 #[stable(feature = "rust1", since = "1.0.0")]
970 impl<'a> cmp::PartialEq for Components<'a> {
972 fn eq(&self, other: &Components<'a>) -> bool {
973 Iterator::eq(self.clone().rev(), other.clone().rev())
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl cmp::Eq for Components<'_> {}
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<'a> cmp::PartialOrd for Components<'a> {
983 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
984 Some(compare_components(self.clone(), other.clone()))
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl cmp::Ord for Components<'_> {
991 fn cmp(&self, other: &Self) -> cmp::Ordering {
992 compare_components(self.clone(), other.clone())
996 fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cmp::Ordering {
997 // Fast path for long shared prefixes
999 // - compare raw bytes to find first mismatch
1000 // - backtrack to find separator before mismatch to avoid ambiguous parsings of '.' or '..' characters
1001 // - if found update state to only do a component-wise comparison on the remainder,
1002 // otherwise do it on the full path
1004 // The fast path isn't taken for paths with a PrefixComponent to avoid backtracking into
1005 // the middle of one
1006 if left.prefix.is_none() && right.prefix.is_none() && left.front == right.front {
1007 // this might benefit from a [u8]::first_mismatch simd implementation, if it existed
1008 let first_difference =
1009 match left.path.iter().zip(right.path.iter()).position(|(&a, &b)| a != b) {
1010 None if left.path.len() == right.path.len() => return cmp::Ordering::Equal,
1011 None => left.path.len().min(right.path.len()),
1015 if let Some(previous_sep) =
1016 left.path[..first_difference].iter().rposition(|&b| left.is_sep_byte(b))
1018 let mismatched_component_start = previous_sep + 1;
1019 left.path = &left.path[mismatched_component_start..];
1020 left.front = State::Body;
1021 right.path = &right.path[mismatched_component_start..];
1022 right.front = State::Body;
1026 Iterator::cmp(left, right)
1029 /// An iterator over [`Path`] and its ancestors.
1031 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1032 /// See its documentation for more.
1037 /// use std::path::Path;
1039 /// let path = Path::new("/foo/bar");
1041 /// for ancestor in path.ancestors() {
1042 /// println!("{}", ancestor.display());
1046 /// [`ancestors`]: Path::ancestors
1047 #[derive(Copy, Clone, Debug)]
1048 #[stable(feature = "path_ancestors", since = "1.28.0")]
1049 pub struct Ancestors<'a> {
1050 next: Option<&'a Path>,
1053 #[stable(feature = "path_ancestors", since = "1.28.0")]
1054 impl<'a> Iterator for Ancestors<'a> {
1055 type Item = &'a Path;
1058 fn next(&mut self) -> Option<Self::Item> {
1059 let next = self.next;
1060 self.next = next.and_then(Path::parent);
1065 #[stable(feature = "path_ancestors", since = "1.28.0")]
1066 impl FusedIterator for Ancestors<'_> {}
1068 ////////////////////////////////////////////////////////////////////////////////
1069 // Basic types and traits
1070 ////////////////////////////////////////////////////////////////////////////////
1072 /// An owned, mutable path (akin to [`String`]).
1074 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1075 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1076 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1078 /// [`push`]: PathBuf::push
1079 /// [`set_extension`]: PathBuf::set_extension
1081 /// More details about the overall approach can be found in
1082 /// the [module documentation](self).
1086 /// You can use [`push`] to build up a `PathBuf` from
1090 /// use std::path::PathBuf;
1092 /// let mut path = PathBuf::new();
1094 /// path.push(r"C:\");
1095 /// path.push("windows");
1096 /// path.push("system32");
1098 /// path.set_extension("dll");
1101 /// However, [`push`] is best used for dynamic situations. This is a better way
1102 /// to do this when you know all of the components ahead of time:
1105 /// use std::path::PathBuf;
1107 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1110 /// We can still do better than this! Since these are all strings, we can use
1114 /// use std::path::PathBuf;
1116 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1119 /// Which method works best depends on what kind of situation you're in.
1120 #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1121 #[stable(feature = "rust1", since = "1.0.0")]
1123 // `PathBuf::as_mut_vec` current implementation relies
1124 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1125 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1126 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1127 // not documented and must not be relied upon.
1128 pub struct PathBuf {
1134 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1135 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1138 /// Allocates an empty `PathBuf`.
1143 /// use std::path::PathBuf;
1145 /// let path = PathBuf::new();
1147 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub fn new() -> PathBuf {
1151 PathBuf { inner: OsString::new() }
1154 /// Creates a new `PathBuf` with a given capacity used to create the
1155 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1160 /// use std::path::PathBuf;
1162 /// let mut path = PathBuf::with_capacity(10);
1163 /// let capacity = path.capacity();
1165 /// // This push is done without reallocating
1166 /// path.push(r"C:\");
1168 /// assert_eq!(capacity, path.capacity());
1171 /// [`with_capacity`]: OsString::with_capacity
1172 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1175 pub fn with_capacity(capacity: usize) -> PathBuf {
1176 PathBuf { inner: OsString::with_capacity(capacity) }
1179 /// Coerces to a [`Path`] slice.
1184 /// use std::path::{Path, PathBuf};
1186 /// let p = PathBuf::from("/test");
1187 /// assert_eq!(Path::new("/test"), p.as_path());
1189 #[stable(feature = "rust1", since = "1.0.0")]
1191 pub fn as_path(&self) -> &Path {
1195 /// Extends `self` with `path`.
1197 /// If `path` is absolute, it replaces the current path.
1201 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1202 /// replaces everything except for the prefix (if any) of `self`.
1203 /// * if `path` has a prefix but no root, it replaces `self`.
1207 /// Pushing a relative path extends the existing path:
1210 /// use std::path::PathBuf;
1212 /// let mut path = PathBuf::from("/tmp");
1213 /// path.push("file.bk");
1214 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1217 /// Pushing an absolute path replaces the existing path:
1220 /// use std::path::PathBuf;
1222 /// let mut path = PathBuf::from("/tmp");
1223 /// path.push("/etc");
1224 /// assert_eq!(path, PathBuf::from("/etc"));
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1228 self._push(path.as_ref())
1231 fn _push(&mut self, path: &Path) {
1232 // in general, a separator is needed if the rightmost byte is not a separator
1233 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1235 // in the special case of `C:` on Windows, do *not* add a separator
1236 let comps = self.components();
1238 if comps.prefix_len() > 0
1239 && comps.prefix_len() == comps.path.len()
1240 && comps.prefix.unwrap().is_drive()
1245 // absolute `path` replaces `self`
1246 if path.is_absolute() || path.prefix().is_some() {
1247 self.as_mut_vec().truncate(0);
1249 // verbatim paths need . and .. removed
1250 } else if comps.prefix_verbatim() {
1251 let mut buf: Vec<_> = comps.collect();
1252 for c in path.components() {
1254 Component::RootDir => {
1258 Component::CurDir => (),
1259 Component::ParentDir => {
1260 if let Some(Component::Normal(_)) = buf.last() {
1268 let mut res = OsString::new();
1269 let mut need_sep = false;
1272 if need_sep && c != Component::RootDir {
1273 res.push(MAIN_SEP_STR);
1275 res.push(c.as_os_str());
1277 need_sep = match c {
1278 Component::RootDir => false,
1279 Component::Prefix(prefix) => {
1280 !prefix.parsed.is_drive() && prefix.parsed.len() > 0
1289 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1290 } else if path.has_root() {
1291 let prefix_len = self.components().prefix_remaining();
1292 self.as_mut_vec().truncate(prefix_len);
1294 // `path` is a pure relative path
1295 } else if need_sep {
1296 self.inner.push(MAIN_SEP_STR);
1299 self.inner.push(path);
1302 /// Truncates `self` to [`self.parent`].
1304 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1305 /// Otherwise, returns `true`.
1307 /// [`self.parent`]: Path::parent
1312 /// use std::path::{Path, PathBuf};
1314 /// let mut p = PathBuf::from("/spirited/away.rs");
1317 /// assert_eq!(Path::new("/spirited"), p);
1319 /// assert_eq!(Path::new("/"), p);
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 pub fn pop(&mut self) -> bool {
1323 match self.parent().map(|p| p.as_u8_slice().len()) {
1325 self.as_mut_vec().truncate(len);
1332 /// Updates [`self.file_name`] to `file_name`.
1334 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1337 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1338 /// `file_name`. The new path will be a sibling of the original path.
1339 /// (That is, it will have the same parent.)
1341 /// [`self.file_name`]: Path::file_name
1342 /// [`pop`]: PathBuf::pop
1347 /// use std::path::PathBuf;
1349 /// let mut buf = PathBuf::from("/");
1350 /// assert!(buf.file_name() == None);
1351 /// buf.set_file_name("bar");
1352 /// assert!(buf == PathBuf::from("/bar"));
1353 /// assert!(buf.file_name().is_some());
1354 /// buf.set_file_name("baz.txt");
1355 /// assert!(buf == PathBuf::from("/baz.txt"));
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1359 self._set_file_name(file_name.as_ref())
1362 fn _set_file_name(&mut self, file_name: &OsStr) {
1363 if self.file_name().is_some() {
1364 let popped = self.pop();
1365 debug_assert!(popped);
1367 self.push(file_name);
1370 /// Updates [`self.extension`] to `extension`.
1372 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1373 /// returns `true` and updates the extension otherwise.
1375 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1378 /// [`self.file_name`]: Path::file_name
1379 /// [`self.extension`]: Path::extension
1384 /// use std::path::{Path, PathBuf};
1386 /// let mut p = PathBuf::from("/feel/the");
1388 /// p.set_extension("force");
1389 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1391 /// p.set_extension("dark_side");
1392 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1396 self._set_extension(extension.as_ref())
1399 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1400 let file_stem = match self.file_stem() {
1401 None => return false,
1402 Some(f) => os_str_as_u8_slice(f),
1405 // truncate until right after the file stem
1406 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1407 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1408 let v = self.as_mut_vec();
1409 v.truncate(end_file_stem.wrapping_sub(start));
1411 // add the new extension, if any
1412 let new = os_str_as_u8_slice(extension);
1413 if !new.is_empty() {
1414 v.reserve_exact(new.len() + 1);
1416 v.extend_from_slice(new);
1422 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1427 /// use std::path::PathBuf;
1429 /// let p = PathBuf::from("/the/head");
1430 /// let os_str = p.into_os_string();
1432 #[stable(feature = "rust1", since = "1.0.0")]
1434 pub fn into_os_string(self) -> OsString {
1438 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1439 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1441 pub fn into_boxed_path(self) -> Box<Path> {
1442 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1443 unsafe { Box::from_raw(rw) }
1446 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1448 /// [`capacity`]: OsString::capacity
1449 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1451 pub fn capacity(&self) -> usize {
1452 self.inner.capacity()
1455 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1457 /// [`clear`]: OsString::clear
1458 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1460 pub fn clear(&mut self) {
1464 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1466 /// [`reserve`]: OsString::reserve
1467 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1469 pub fn reserve(&mut self, additional: usize) {
1470 self.inner.reserve(additional)
1473 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1475 /// [`reserve_exact`]: OsString::reserve_exact
1476 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1478 pub fn reserve_exact(&mut self, additional: usize) {
1479 self.inner.reserve_exact(additional)
1482 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1484 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1485 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1487 pub fn shrink_to_fit(&mut self) {
1488 self.inner.shrink_to_fit()
1491 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1493 /// [`shrink_to`]: OsString::shrink_to
1494 #[stable(feature = "shrink_to", since = "1.56.0")]
1496 pub fn shrink_to(&mut self, min_capacity: usize) {
1497 self.inner.shrink_to(min_capacity)
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl Clone for PathBuf {
1504 fn clone(&self) -> Self {
1505 PathBuf { inner: self.inner.clone() }
1509 fn clone_from(&mut self, source: &Self) {
1510 self.inner.clone_from(&source.inner)
1514 #[stable(feature = "box_from_path", since = "1.17.0")]
1515 impl From<&Path> for Box<Path> {
1516 /// Creates a boxed [`Path`] from a reference.
1518 /// This will allocate and clone `path` to it.
1519 fn from(path: &Path) -> Box<Path> {
1520 let boxed: Box<OsStr> = path.inner.into();
1521 let rw = Box::into_raw(boxed) as *mut Path;
1522 unsafe { Box::from_raw(rw) }
1526 #[stable(feature = "box_from_cow", since = "1.45.0")]
1527 impl From<Cow<'_, Path>> for Box<Path> {
1528 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1530 /// Converting from a `Cow::Owned` does not clone or allocate.
1532 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1534 Cow::Borrowed(path) => Box::from(path),
1535 Cow::Owned(path) => Box::from(path),
1540 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1541 impl From<Box<Path>> for PathBuf {
1542 /// Converts a `Box<Path>` into a `PathBuf`
1544 /// This conversion does not allocate or copy memory.
1546 fn from(boxed: Box<Path>) -> PathBuf {
1547 boxed.into_path_buf()
1551 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1552 impl From<PathBuf> for Box<Path> {
1553 /// Converts a `PathBuf` into a `Box<Path>`
1555 /// This conversion currently should not allocate memory,
1556 /// but this behavior is not guaranteed on all platforms or in all future versions.
1558 fn from(p: PathBuf) -> Box<Path> {
1563 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1564 impl Clone for Box<Path> {
1566 fn clone(&self) -> Self {
1567 self.to_path_buf().into_boxed_path()
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1573 /// Converts a borrowed `OsStr` to a `PathBuf`.
1575 /// Allocates a [`PathBuf`] and copies the data into it.
1577 fn from(s: &T) -> PathBuf {
1578 PathBuf::from(s.as_ref().to_os_string())
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl From<OsString> for PathBuf {
1584 /// Converts an [`OsString`] into a [`PathBuf`]
1586 /// This conversion does not allocate or copy memory.
1588 fn from(s: OsString) -> PathBuf {
1589 PathBuf { inner: s }
1593 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1594 impl From<PathBuf> for OsString {
1595 /// Converts a [`PathBuf`] into an [`OsString`]
1597 /// This conversion does not allocate or copy memory.
1599 fn from(path_buf: PathBuf) -> OsString {
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl From<String> for PathBuf {
1606 /// Converts a [`String`] into a [`PathBuf`]
1608 /// This conversion does not allocate or copy memory.
1610 fn from(s: String) -> PathBuf {
1611 PathBuf::from(OsString::from(s))
1615 #[stable(feature = "path_from_str", since = "1.32.0")]
1616 impl FromStr for PathBuf {
1617 type Err = core::convert::Infallible;
1620 fn from_str(s: &str) -> Result<Self, Self::Err> {
1621 Ok(PathBuf::from(s))
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1627 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1628 let mut buf = PathBuf::new();
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1636 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1637 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1641 fn extend_one(&mut self, p: P) {
1642 self.push(p.as_ref());
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl fmt::Debug for PathBuf {
1648 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1649 fmt::Debug::fmt(&**self, formatter)
1653 #[stable(feature = "rust1", since = "1.0.0")]
1654 impl ops::Deref for PathBuf {
1657 fn deref(&self) -> &Path {
1658 Path::new(&self.inner)
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl Borrow<Path> for PathBuf {
1665 fn borrow(&self) -> &Path {
1670 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1671 impl Default for PathBuf {
1673 fn default() -> Self {
1678 #[stable(feature = "cow_from_path", since = "1.6.0")]
1679 impl<'a> From<&'a Path> for Cow<'a, Path> {
1680 /// Creates a clone-on-write pointer from a reference to
1683 /// This conversion does not clone or allocate.
1685 fn from(s: &'a Path) -> Cow<'a, Path> {
1690 #[stable(feature = "cow_from_path", since = "1.6.0")]
1691 impl<'a> From<PathBuf> for Cow<'a, Path> {
1692 /// Creates a clone-on-write pointer from an owned
1693 /// instance of [`PathBuf`].
1695 /// This conversion does not clone or allocate.
1697 fn from(s: PathBuf) -> Cow<'a, Path> {
1702 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1703 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1704 /// Creates a clone-on-write pointer from a reference to
1707 /// This conversion does not clone or allocate.
1709 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1710 Cow::Borrowed(p.as_path())
1714 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1715 impl<'a> From<Cow<'a, Path>> for PathBuf {
1716 /// Converts a clone-on-write pointer to an owned path.
1718 /// Converting from a `Cow::Owned` does not clone or allocate.
1720 fn from(p: Cow<'a, Path>) -> Self {
1725 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1726 impl From<PathBuf> for Arc<Path> {
1727 /// Converts a [`PathBuf`] into an [`Arc`] by moving the [`PathBuf`] data into a new [`Arc`] buffer.
1729 fn from(s: PathBuf) -> Arc<Path> {
1730 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1731 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1735 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1736 impl From<&Path> for Arc<Path> {
1737 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
1739 fn from(s: &Path) -> Arc<Path> {
1740 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1741 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1745 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1746 impl From<PathBuf> for Rc<Path> {
1747 /// Converts a [`PathBuf`] into an [`Rc`] by moving the [`PathBuf`] data into a new `Rc` buffer.
1749 fn from(s: PathBuf) -> Rc<Path> {
1750 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1751 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1755 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1756 impl From<&Path> for Rc<Path> {
1757 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new `Rc` buffer.
1759 fn from(s: &Path) -> Rc<Path> {
1760 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1761 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1765 #[stable(feature = "rust1", since = "1.0.0")]
1766 impl ToOwned for Path {
1767 type Owned = PathBuf;
1769 fn to_owned(&self) -> PathBuf {
1773 fn clone_into(&self, target: &mut PathBuf) {
1774 self.inner.clone_into(&mut target.inner);
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 impl cmp::PartialEq for PathBuf {
1781 fn eq(&self, other: &PathBuf) -> bool {
1782 self.components() == other.components()
1786 #[stable(feature = "rust1", since = "1.0.0")]
1787 impl Hash for PathBuf {
1788 fn hash<H: Hasher>(&self, h: &mut H) {
1789 self.as_path().hash(h)
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl cmp::Eq for PathBuf {}
1796 #[stable(feature = "rust1", since = "1.0.0")]
1797 impl cmp::PartialOrd for PathBuf {
1799 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1800 Some(compare_components(self.components(), other.components()))
1804 #[stable(feature = "rust1", since = "1.0.0")]
1805 impl cmp::Ord for PathBuf {
1807 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1808 compare_components(self.components(), other.components())
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 impl AsRef<OsStr> for PathBuf {
1815 fn as_ref(&self) -> &OsStr {
1820 /// A slice of a path (akin to [`str`]).
1822 /// This type supports a number of operations for inspecting a path, including
1823 /// breaking the path into its components (separated by `/` on Unix and by either
1824 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1825 /// is absolute, and so on.
1827 /// This is an *unsized* type, meaning that it must always be used behind a
1828 /// pointer like `&` or [`Box`]. For an owned version of this type,
1829 /// see [`PathBuf`].
1831 /// More details about the overall approach can be found in
1832 /// the [module documentation](self).
1837 /// use std::path::Path;
1838 /// use std::ffi::OsStr;
1840 /// // Note: this example does work on Windows
1841 /// let path = Path::new("./foo/bar.txt");
1843 /// let parent = path.parent();
1844 /// assert_eq!(parent, Some(Path::new("./foo")));
1846 /// let file_stem = path.file_stem();
1847 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1849 /// let extension = path.extension();
1850 /// assert_eq!(extension, Some(OsStr::new("txt")));
1852 #[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
1853 #[stable(feature = "rust1", since = "1.0.0")]
1855 // `Path::new` current implementation relies
1856 // on `Path` being layout-compatible with `OsStr`.
1857 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1858 // Anyway, `Path` representation and layout are considered implementation detail, are
1859 // not documented and must not be relied upon.
1864 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1866 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1867 /// See its documentation for more.
1869 /// [`strip_prefix`]: Path::strip_prefix
1870 #[derive(Debug, Clone, PartialEq, Eq)]
1871 #[stable(since = "1.7.0", feature = "strip_prefix")]
1872 pub struct StripPrefixError(());
1875 // The following (private!) function allows construction of a path from a u8
1876 // slice, which is only safe when it is known to follow the OsStr encoding.
1877 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1878 unsafe { Path::new(u8_slice_as_os_str(s)) }
1880 // The following (private!) function reveals the byte encoding used for OsStr.
1881 fn as_u8_slice(&self) -> &[u8] {
1882 os_str_as_u8_slice(&self.inner)
1885 /// Directly wraps a string slice as a `Path` slice.
1887 /// This is a cost-free conversion.
1892 /// use std::path::Path;
1894 /// Path::new("foo.txt");
1897 /// You can create `Path`s from `String`s, or even other `Path`s:
1900 /// use std::path::Path;
1902 /// let string = String::from("foo.txt");
1903 /// let from_string = Path::new(&string);
1904 /// let from_path = Path::new(&from_string);
1905 /// assert_eq!(from_string, from_path);
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1909 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1912 /// Yields the underlying [`OsStr`] slice.
1917 /// use std::path::Path;
1919 /// let os_str = Path::new("foo.txt").as_os_str();
1920 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1922 #[stable(feature = "rust1", since = "1.0.0")]
1924 pub fn as_os_str(&self) -> &OsStr {
1928 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1930 /// This conversion may entail doing a check for UTF-8 validity.
1931 /// Note that validation is performed because non-UTF-8 strings are
1932 /// perfectly valid for some OS.
1939 /// use std::path::Path;
1941 /// let path = Path::new("foo.txt");
1942 /// assert_eq!(path.to_str(), Some("foo.txt"));
1944 #[stable(feature = "rust1", since = "1.0.0")]
1946 pub fn to_str(&self) -> Option<&str> {
1950 /// Converts a `Path` to a [`Cow<str>`].
1952 /// Any non-Unicode sequences are replaced with
1953 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1955 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1959 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1962 /// use std::path::Path;
1964 /// let path = Path::new("foo.txt");
1965 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1968 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1969 /// have returned `"fo�.txt"`.
1970 #[stable(feature = "rust1", since = "1.0.0")]
1972 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1973 self.inner.to_string_lossy()
1976 /// Converts a `Path` to an owned [`PathBuf`].
1981 /// use std::path::Path;
1983 /// let path_buf = Path::new("foo.txt").to_path_buf();
1984 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1986 #[rustc_conversion_suggestion]
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 pub fn to_path_buf(&self) -> PathBuf {
1989 PathBuf::from(self.inner.to_os_string())
1992 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1993 /// the current directory.
1995 /// * On Unix, a path is absolute if it starts with the root, so
1996 /// `is_absolute` and [`has_root`] are equivalent.
1998 /// * On Windows, a path is absolute if it has a prefix and starts with the
1999 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
2004 /// use std::path::Path;
2006 /// assert!(!Path::new("foo.txt").is_absolute());
2009 /// [`has_root`]: Path::has_root
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 #[allow(deprecated)]
2012 pub fn is_absolute(&self) -> bool {
2013 if cfg!(target_os = "redox") {
2014 // FIXME: Allow Redox prefixes
2015 self.has_root() || has_redox_scheme(self.as_u8_slice())
2017 self.has_root() && (cfg!(any(unix, target_os = "wasi")) || self.prefix().is_some())
2021 /// Returns `true` if the `Path` is relative, i.e., not absolute.
2023 /// See [`is_absolute`]'s documentation for more details.
2028 /// use std::path::Path;
2030 /// assert!(Path::new("foo.txt").is_relative());
2033 /// [`is_absolute`]: Path::is_absolute
2034 #[stable(feature = "rust1", since = "1.0.0")]
2036 pub fn is_relative(&self) -> bool {
2040 fn prefix(&self) -> Option<Prefix<'_>> {
2041 self.components().prefix
2044 /// Returns `true` if the `Path` has a root.
2046 /// * On Unix, a path has a root if it begins with `/`.
2048 /// * On Windows, a path has a root if it:
2049 /// * has no prefix and begins with a separator, e.g., `\windows`
2050 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
2051 /// * has any non-disk prefix, e.g., `\\server\share`
2056 /// use std::path::Path;
2058 /// assert!(Path::new("/etc/passwd").has_root());
2060 #[stable(feature = "rust1", since = "1.0.0")]
2062 pub fn has_root(&self) -> bool {
2063 self.components().has_root()
2066 /// Returns the `Path` without its final component, if there is one.
2068 /// Returns [`None`] if the path terminates in a root or prefix.
2073 /// use std::path::Path;
2075 /// let path = Path::new("/foo/bar");
2076 /// let parent = path.parent().unwrap();
2077 /// assert_eq!(parent, Path::new("/foo"));
2079 /// let grand_parent = parent.parent().unwrap();
2080 /// assert_eq!(grand_parent, Path::new("/"));
2081 /// assert_eq!(grand_parent.parent(), None);
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 pub fn parent(&self) -> Option<&Path> {
2085 let mut comps = self.components();
2086 let comp = comps.next_back();
2087 comp.and_then(|p| match p {
2088 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
2089 Some(comps.as_path())
2095 /// Produces an iterator over `Path` and its ancestors.
2097 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2098 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2099 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2100 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2106 /// use std::path::Path;
2108 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2109 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2110 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2111 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2112 /// assert_eq!(ancestors.next(), None);
2114 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2115 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2116 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2117 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2118 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2119 /// assert_eq!(ancestors.next(), None);
2122 /// [`parent`]: Path::parent
2123 #[stable(feature = "path_ancestors", since = "1.28.0")]
2125 pub fn ancestors(&self) -> Ancestors<'_> {
2126 Ancestors { next: Some(&self) }
2129 /// Returns the final component of the `Path`, if there is one.
2131 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2132 /// is the directory name.
2134 /// Returns [`None`] if the path terminates in `..`.
2139 /// use std::path::Path;
2140 /// use std::ffi::OsStr;
2142 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2143 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2144 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2145 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2146 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2147 /// assert_eq!(None, Path::new("/").file_name());
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 pub fn file_name(&self) -> Option<&OsStr> {
2151 self.components().next_back().and_then(|p| match p {
2152 Component::Normal(p) => Some(p),
2157 /// Returns a path that, when joined onto `base`, yields `self`.
2161 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2162 /// returns `false`), returns [`Err`].
2164 /// [`starts_with`]: Path::starts_with
2169 /// use std::path::{Path, PathBuf};
2171 /// let path = Path::new("/test/haha/foo.txt");
2173 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2174 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2175 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2176 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2177 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2179 /// assert!(path.strip_prefix("test").is_err());
2180 /// assert!(path.strip_prefix("/haha").is_err());
2182 /// let prefix = PathBuf::from("/test/");
2183 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2185 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2186 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2190 self._strip_prefix(base.as_ref())
2193 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2194 iter_after(self.components(), base.components())
2195 .map(|c| c.as_path())
2196 .ok_or(StripPrefixError(()))
2199 /// Determines whether `base` is a prefix of `self`.
2201 /// Only considers whole path components to match.
2206 /// use std::path::Path;
2208 /// let path = Path::new("/etc/passwd");
2210 /// assert!(path.starts_with("/etc"));
2211 /// assert!(path.starts_with("/etc/"));
2212 /// assert!(path.starts_with("/etc/passwd"));
2213 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2214 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2216 /// assert!(!path.starts_with("/e"));
2217 /// assert!(!path.starts_with("/etc/passwd.txt"));
2219 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2221 #[stable(feature = "rust1", since = "1.0.0")]
2222 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2223 self._starts_with(base.as_ref())
2226 fn _starts_with(&self, base: &Path) -> bool {
2227 iter_after(self.components(), base.components()).is_some()
2230 /// Determines whether `child` is a suffix of `self`.
2232 /// Only considers whole path components to match.
2237 /// use std::path::Path;
2239 /// let path = Path::new("/etc/resolv.conf");
2241 /// assert!(path.ends_with("resolv.conf"));
2242 /// assert!(path.ends_with("etc/resolv.conf"));
2243 /// assert!(path.ends_with("/etc/resolv.conf"));
2245 /// assert!(!path.ends_with("/resolv.conf"));
2246 /// assert!(!path.ends_with("conf")); // use .extension() instead
2248 #[stable(feature = "rust1", since = "1.0.0")]
2249 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2250 self._ends_with(child.as_ref())
2253 fn _ends_with(&self, child: &Path) -> bool {
2254 iter_after(self.components().rev(), child.components().rev()).is_some()
2257 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2259 /// [`self.file_name`]: Path::file_name
2263 /// * [`None`], if there is no file name;
2264 /// * The entire file name if there is no embedded `.`;
2265 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2266 /// * Otherwise, the portion of the file name before the final `.`
2271 /// use std::path::Path;
2273 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2274 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2278 /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
2279 /// before the *first* `.`
2281 /// [`Path::file_prefix`]: Path::file_prefix
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 pub fn file_stem(&self) -> Option<&OsStr> {
2285 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2288 /// Extracts the prefix of [`self.file_name`].
2292 /// * [`None`], if there is no file name;
2293 /// * The entire file name if there is no embedded `.`;
2294 /// * The portion of the file name before the first non-beginning `.`;
2295 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2296 /// * The portion of the file name before the second `.` if the file name begins with `.`
2298 /// [`self.file_name`]: Path::file_name
2303 /// # #![feature(path_file_prefix)]
2304 /// use std::path::Path;
2306 /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
2307 /// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
2311 /// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
2312 /// before the *last* `.`
2314 /// [`Path::file_stem`]: Path::file_stem
2316 #[unstable(feature = "path_file_prefix", issue = "86319")]
2317 pub fn file_prefix(&self) -> Option<&OsStr> {
2318 self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before))
2321 /// Extracts the extension of [`self.file_name`], if possible.
2323 /// The extension is:
2325 /// * [`None`], if there is no file name;
2326 /// * [`None`], if there is no embedded `.`;
2327 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2328 /// * Otherwise, the portion of the file name after the final `.`
2330 /// [`self.file_name`]: Path::file_name
2335 /// use std::path::Path;
2337 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2338 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2340 #[stable(feature = "rust1", since = "1.0.0")]
2341 pub fn extension(&self) -> Option<&OsStr> {
2342 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
2345 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2347 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2352 /// use std::path::{Path, PathBuf};
2354 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2356 #[stable(feature = "rust1", since = "1.0.0")]
2358 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2359 self._join(path.as_ref())
2362 fn _join(&self, path: &Path) -> PathBuf {
2363 let mut buf = self.to_path_buf();
2368 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2370 /// See [`PathBuf::set_file_name`] for more details.
2375 /// use std::path::{Path, PathBuf};
2377 /// let path = Path::new("/tmp/foo.txt");
2378 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2380 /// let path = Path::new("/tmp");
2381 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2383 #[stable(feature = "rust1", since = "1.0.0")]
2384 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2385 self._with_file_name(file_name.as_ref())
2388 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2389 let mut buf = self.to_path_buf();
2390 buf.set_file_name(file_name);
2394 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2396 /// See [`PathBuf::set_extension`] for more details.
2401 /// use std::path::{Path, PathBuf};
2403 /// let path = Path::new("foo.rs");
2404 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2406 /// let path = Path::new("foo.tar.gz");
2407 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2408 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2409 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2411 #[stable(feature = "rust1", since = "1.0.0")]
2412 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2413 self._with_extension(extension.as_ref())
2416 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2417 let mut buf = self.to_path_buf();
2418 buf.set_extension(extension);
2422 /// Produces an iterator over the [`Component`]s of the path.
2424 /// When parsing the path, there is a small amount of normalization:
2426 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2427 /// `a` and `b` as components.
2429 /// * Occurrences of `.` are normalized away, except if they are at the
2430 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2431 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2432 /// an additional [`CurDir`] component.
2434 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2436 /// Note that no other normalization takes place; in particular, `a/c`
2437 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2438 /// is a symbolic link (so its parent isn't `a`).
2443 /// use std::path::{Path, Component};
2444 /// use std::ffi::OsStr;
2446 /// let mut components = Path::new("/tmp/foo.txt").components();
2448 /// assert_eq!(components.next(), Some(Component::RootDir));
2449 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2450 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2451 /// assert_eq!(components.next(), None)
2454 /// [`CurDir`]: Component::CurDir
2455 #[stable(feature = "rust1", since = "1.0.0")]
2456 pub fn components(&self) -> Components<'_> {
2457 let prefix = parse_prefix(self.as_os_str());
2459 path: self.as_u8_slice(),
2461 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2462 || has_redox_scheme(self.as_u8_slice()),
2463 front: State::Prefix,
2468 /// Produces an iterator over the path's components viewed as [`OsStr`]
2471 /// For more information about the particulars of how the path is separated
2472 /// into components, see [`components`].
2474 /// [`components`]: Path::components
2479 /// use std::path::{self, Path};
2480 /// use std::ffi::OsStr;
2482 /// let mut it = Path::new("/tmp/foo.txt").iter();
2483 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2484 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2485 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2486 /// assert_eq!(it.next(), None)
2488 #[stable(feature = "rust1", since = "1.0.0")]
2490 pub fn iter(&self) -> Iter<'_> {
2491 Iter { inner: self.components() }
2494 /// Returns an object that implements [`Display`] for safely printing paths
2495 /// that may contain non-Unicode data. This may perform lossy conversion,
2496 /// depending on the platform. If you would like an implementation which
2497 /// escapes the path please use [`Debug`] instead.
2499 /// [`Display`]: fmt::Display
2504 /// use std::path::Path;
2506 /// let path = Path::new("/tmp/foo.rs");
2508 /// println!("{}", path.display());
2510 #[stable(feature = "rust1", since = "1.0.0")]
2512 pub fn display(&self) -> Display<'_> {
2513 Display { path: self }
2516 /// Queries the file system to get information about a file, directory, etc.
2518 /// This function will traverse symbolic links to query information about the
2519 /// destination file.
2521 /// This is an alias to [`fs::metadata`].
2526 /// use std::path::Path;
2528 /// let path = Path::new("/Minas/tirith");
2529 /// let metadata = path.metadata().expect("metadata call failed");
2530 /// println!("{:?}", metadata.file_type());
2532 #[stable(feature = "path_ext", since = "1.5.0")]
2534 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2538 /// Queries the metadata about a file without following symlinks.
2540 /// This is an alias to [`fs::symlink_metadata`].
2545 /// use std::path::Path;
2547 /// let path = Path::new("/Minas/tirith");
2548 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2549 /// println!("{:?}", metadata.file_type());
2551 #[stable(feature = "path_ext", since = "1.5.0")]
2553 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2554 fs::symlink_metadata(self)
2557 /// Returns the canonical, absolute form of the path with all intermediate
2558 /// components normalized and symbolic links resolved.
2560 /// This is an alias to [`fs::canonicalize`].
2565 /// use std::path::{Path, PathBuf};
2567 /// let path = Path::new("/foo/test/../test/bar.rs");
2568 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2570 #[stable(feature = "path_ext", since = "1.5.0")]
2572 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2573 fs::canonicalize(self)
2576 /// Reads a symbolic link, returning the file that the link points to.
2578 /// This is an alias to [`fs::read_link`].
2583 /// use std::path::Path;
2585 /// let path = Path::new("/laputa/sky_castle.rs");
2586 /// let path_link = path.read_link().expect("read_link call failed");
2588 #[stable(feature = "path_ext", since = "1.5.0")]
2590 pub fn read_link(&self) -> io::Result<PathBuf> {
2594 /// Returns an iterator over the entries within a directory.
2596 /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. New
2597 /// errors may be encountered after an iterator is initially constructed.
2599 /// This is an alias to [`fs::read_dir`].
2604 /// use std::path::Path;
2606 /// let path = Path::new("/laputa");
2607 /// for entry in path.read_dir().expect("read_dir call failed") {
2608 /// if let Ok(entry) = entry {
2609 /// println!("{:?}", entry.path());
2613 #[stable(feature = "path_ext", since = "1.5.0")]
2615 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2619 /// Returns `true` if the path points at an existing entity.
2621 /// This function will traverse symbolic links to query information about the
2622 /// destination file.
2624 /// If you cannot access the metadata of the file, e.g. because of a
2625 /// permission error or broken symbolic links, this will return `false`.
2630 /// use std::path::Path;
2631 /// assert!(!Path::new("does_not_exist.txt").exists());
2636 /// This is a convenience function that coerces errors to false. If you want to
2637 /// check errors, call [`fs::metadata`].
2638 #[stable(feature = "path_ext", since = "1.5.0")]
2640 pub fn exists(&self) -> bool {
2641 fs::metadata(self).is_ok()
2644 /// Returns `Ok(true)` if the path points at an existing entity.
2646 /// This function will traverse symbolic links to query information about the
2647 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2649 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2650 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2651 /// denied on some of the parent directories.)
2656 /// #![feature(path_try_exists)]
2658 /// use std::path::Path;
2659 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2660 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2662 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2664 #[unstable(feature = "path_try_exists", issue = "83186")]
2666 pub fn try_exists(&self) -> io::Result<bool> {
2667 fs::try_exists(self)
2670 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2672 /// This function will traverse symbolic links to query information about the
2673 /// destination file.
2675 /// If you cannot access the metadata of the file, e.g. because of a
2676 /// permission error or broken symbolic links, this will return `false`.
2681 /// use std::path::Path;
2682 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2683 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2688 /// This is a convenience function that coerces errors to false. If you want to
2689 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2690 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2692 /// When the goal is simply to read from (or write to) the source, the most
2693 /// reliable way to test the source can be read (or written to) is to open
2694 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2695 /// a Unix-like system for example. See [`fs::File::open`] or
2696 /// [`fs::OpenOptions::open`] for more information.
2697 #[stable(feature = "path_ext", since = "1.5.0")]
2698 pub fn is_file(&self) -> bool {
2699 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2702 /// Returns `true` if the path exists on disk and is pointing at a directory.
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_eq!(Path::new("./is_a_directory/").is_dir(), true);
2715 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2720 /// This is a convenience function that coerces errors to false. If you want to
2721 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2722 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2723 #[stable(feature = "path_ext", since = "1.5.0")]
2724 pub fn is_dir(&self) -> bool {
2725 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2728 /// Returns true if the path exists on disk and is pointing at a symbolic link.
2730 /// This function will not traverse symbolic links.
2731 /// In case of a broken symbolic link this will also return true.
2733 /// If you cannot access the directory containing the file, e.g., because of a
2734 /// permission error, this will return false.
2738 #[cfg_attr(unix, doc = "```no_run")]
2739 #[cfg_attr(not(unix), doc = "```ignore")]
2740 /// #![feature(is_symlink)]
2741 /// use std::path::Path;
2742 /// use std::os::unix::fs::symlink;
2744 /// let link_path = Path::new("link");
2745 /// symlink("/origin_does_not_exists/", link_path).unwrap();
2746 /// assert_eq!(link_path.is_symlink(), true);
2747 /// assert_eq!(link_path.exists(), false);
2749 #[unstable(feature = "is_symlink", issue = "85748")]
2750 pub fn is_symlink(&self) -> bool {
2751 fs::symlink_metadata(self).map(|m| m.is_symlink()).unwrap_or(false)
2754 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2756 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2757 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2758 let rw = Box::into_raw(self) as *mut OsStr;
2759 let inner = unsafe { Box::from_raw(rw) };
2760 PathBuf { inner: OsString::from(inner) }
2764 #[stable(feature = "rust1", since = "1.0.0")]
2765 impl AsRef<OsStr> for Path {
2767 fn as_ref(&self) -> &OsStr {
2772 #[stable(feature = "rust1", since = "1.0.0")]
2773 impl fmt::Debug for Path {
2774 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2775 fmt::Debug::fmt(&self.inner, formatter)
2779 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2781 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2782 /// [`Display`] trait in a way that mitigates that. It is created by the
2783 /// [`display`](Path::display) method on [`Path`]. This may perform lossy
2784 /// conversion, depending on the platform. If you would like an implementation
2785 /// which escapes the path please use [`Debug`] instead.
2790 /// use std::path::Path;
2792 /// let path = Path::new("/tmp/foo.rs");
2794 /// println!("{}", path.display());
2797 /// [`Display`]: fmt::Display
2798 /// [`format!`]: crate::format
2799 #[stable(feature = "rust1", since = "1.0.0")]
2800 pub struct Display<'a> {
2804 #[stable(feature = "rust1", since = "1.0.0")]
2805 impl fmt::Debug for Display<'_> {
2806 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2807 fmt::Debug::fmt(&self.path, f)
2811 #[stable(feature = "rust1", since = "1.0.0")]
2812 impl fmt::Display for Display<'_> {
2813 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2814 self.path.inner.display(f)
2818 #[stable(feature = "rust1", since = "1.0.0")]
2819 impl cmp::PartialEq for Path {
2821 fn eq(&self, other: &Path) -> bool {
2822 self.components() == other.components()
2826 #[stable(feature = "rust1", since = "1.0.0")]
2827 impl Hash for Path {
2828 fn hash<H: Hasher>(&self, h: &mut H) {
2829 for component in self.components() {
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 impl cmp::Eq for Path {}
2838 #[stable(feature = "rust1", since = "1.0.0")]
2839 impl cmp::PartialOrd for Path {
2841 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2842 Some(compare_components(self.components(), other.components()))
2846 #[stable(feature = "rust1", since = "1.0.0")]
2847 impl cmp::Ord for Path {
2849 fn cmp(&self, other: &Path) -> cmp::Ordering {
2850 compare_components(self.components(), other.components())
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 impl AsRef<Path> for Path {
2857 fn as_ref(&self) -> &Path {
2862 #[stable(feature = "rust1", since = "1.0.0")]
2863 impl AsRef<Path> for OsStr {
2865 fn as_ref(&self) -> &Path {
2870 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2871 impl AsRef<Path> for Cow<'_, OsStr> {
2873 fn as_ref(&self) -> &Path {
2878 #[stable(feature = "rust1", since = "1.0.0")]
2879 impl AsRef<Path> for OsString {
2881 fn as_ref(&self) -> &Path {
2886 #[stable(feature = "rust1", since = "1.0.0")]
2887 impl AsRef<Path> for str {
2889 fn as_ref(&self) -> &Path {
2894 #[stable(feature = "rust1", since = "1.0.0")]
2895 impl AsRef<Path> for String {
2897 fn as_ref(&self) -> &Path {
2902 #[stable(feature = "rust1", since = "1.0.0")]
2903 impl AsRef<Path> for PathBuf {
2905 fn as_ref(&self) -> &Path {
2910 #[stable(feature = "path_into_iter", since = "1.6.0")]
2911 impl<'a> IntoIterator for &'a PathBuf {
2912 type Item = &'a OsStr;
2913 type IntoIter = Iter<'a>;
2915 fn into_iter(self) -> Iter<'a> {
2920 #[stable(feature = "path_into_iter", since = "1.6.0")]
2921 impl<'a> IntoIterator for &'a Path {
2922 type Item = &'a OsStr;
2923 type IntoIter = Iter<'a>;
2925 fn into_iter(self) -> Iter<'a> {
2930 macro_rules! impl_cmp {
2931 ($lhs:ty, $rhs: ty) => {
2932 #[stable(feature = "partialeq_path", since = "1.6.0")]
2933 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2935 fn eq(&self, other: &$rhs) -> bool {
2936 <Path as PartialEq>::eq(self, other)
2940 #[stable(feature = "partialeq_path", since = "1.6.0")]
2941 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2943 fn eq(&self, other: &$lhs) -> bool {
2944 <Path as PartialEq>::eq(self, other)
2948 #[stable(feature = "cmp_path", since = "1.8.0")]
2949 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2951 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2952 <Path as PartialOrd>::partial_cmp(self, other)
2956 #[stable(feature = "cmp_path", since = "1.8.0")]
2957 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2959 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2960 <Path as PartialOrd>::partial_cmp(self, other)
2966 impl_cmp!(PathBuf, Path);
2967 impl_cmp!(PathBuf, &'a Path);
2968 impl_cmp!(Cow<'a, Path>, Path);
2969 impl_cmp!(Cow<'a, Path>, &'b Path);
2970 impl_cmp!(Cow<'a, Path>, PathBuf);
2972 macro_rules! impl_cmp_os_str {
2973 ($lhs:ty, $rhs: ty) => {
2974 #[stable(feature = "cmp_path", since = "1.8.0")]
2975 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2977 fn eq(&self, other: &$rhs) -> bool {
2978 <Path as PartialEq>::eq(self, other.as_ref())
2982 #[stable(feature = "cmp_path", since = "1.8.0")]
2983 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2985 fn eq(&self, other: &$lhs) -> bool {
2986 <Path as PartialEq>::eq(self.as_ref(), other)
2990 #[stable(feature = "cmp_path", since = "1.8.0")]
2991 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2993 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2994 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2998 #[stable(feature = "cmp_path", since = "1.8.0")]
2999 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3001 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3002 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
3008 impl_cmp_os_str!(PathBuf, OsStr);
3009 impl_cmp_os_str!(PathBuf, &'a OsStr);
3010 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
3011 impl_cmp_os_str!(PathBuf, OsString);
3012 impl_cmp_os_str!(Path, OsStr);
3013 impl_cmp_os_str!(Path, &'a OsStr);
3014 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
3015 impl_cmp_os_str!(Path, OsString);
3016 impl_cmp_os_str!(&'a Path, OsStr);
3017 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
3018 impl_cmp_os_str!(&'a Path, OsString);
3019 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
3020 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
3021 impl_cmp_os_str!(Cow<'a, Path>, OsString);
3023 #[stable(since = "1.7.0", feature = "strip_prefix")]
3024 impl fmt::Display for StripPrefixError {
3025 #[allow(deprecated, deprecated_in_future)]
3026 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3027 self.description().fmt(f)
3031 #[stable(since = "1.7.0", feature = "strip_prefix")]
3032 impl Error for StripPrefixError {
3033 #[allow(deprecated)]
3034 fn description(&self) -> &str {