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());
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn is_verbatim(&self) -> bool {
222 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
226 fn is_drive(&self) -> bool {
227 matches!(*self, Prefix::Disk(_))
231 fn has_implicit_root(&self) -> bool {
236 ////////////////////////////////////////////////////////////////////////////////
237 // Exposed parsing helpers
238 ////////////////////////////////////////////////////////////////////////////////
240 /// Determines whether the character is one of the permitted path
241 /// separators for the current platform.
248 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
249 /// assert!(!path::is_separator('❤'));
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn is_separator(c: char) -> bool {
254 c.is_ascii() && is_sep_byte(c as u8)
257 /// The primary separator of path components for the current platform.
259 /// For example, `/` on Unix and `\` on Windows.
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
263 ////////////////////////////////////////////////////////////////////////////////
265 ////////////////////////////////////////////////////////////////////////////////
267 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
268 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
269 // `iter` after having exhausted `prefix`.
270 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
272 I: Iterator<Item = Component<'a>> + Clone,
273 J: Iterator<Item = Component<'b>>,
276 let mut iter_next = iter.clone();
277 match (iter_next.next(), prefix.next()) {
278 (Some(ref x), Some(ref y)) if x == y => (),
279 (Some(_), Some(_)) => return None,
280 (Some(_), None) => return Some(iter),
281 (None, None) => return Some(iter),
282 (None, Some(_)) => return None,
288 // See note at the top of this module to understand why these are used:
290 // These casts are safe as OsStr is internally a wrapper around [u8] on all
293 // Note that currently this relies on the special knowledge that libstd has;
294 // these types are single-element structs but are not marked repr(transparent)
295 // or repr(C) which would make these casts allowable outside std.
296 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
297 unsafe { &*(s as *const OsStr as *const [u8]) }
299 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
300 // SAFETY: see the comment of `os_str_as_u8_slice`
301 unsafe { &*(s as *const [u8] as *const OsStr) }
304 // Detect scheme on Redox
305 fn has_redox_scheme(s: &[u8]) -> bool {
306 cfg!(target_os = "redox") && s.contains(&b':')
309 ////////////////////////////////////////////////////////////////////////////////
310 // Cross-platform, iterator-independent parsing
311 ////////////////////////////////////////////////////////////////////////////////
313 /// Says whether the first byte after the prefix is a separator.
314 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
315 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
316 !path.is_empty() && is_sep_byte(path[0])
319 // basic workhorse for splitting stem and extension
320 fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
321 if os_str_as_u8_slice(file) == b".." {
322 return (Some(file), None);
325 // The unsafety here stems from converting between &OsStr and &[u8]
326 // and back. This is safe to do because (1) we only look at ASCII
327 // contents of the encoding and (2) new &OsStr values are produced
328 // only from ASCII-bounded slices of existing &OsStr values.
329 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
330 let after = iter.next();
331 let before = iter.next();
332 if before == Some(b"") {
335 unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
339 fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
340 let slice = os_str_as_u8_slice(file);
345 // The unsafety here stems from converting between &OsStr and &[u8]
346 // and back. This is safe to do because (1) we only look at ASCII
347 // contents of the encoding and (2) new &OsStr values are produced
348 // only from ASCII-bounded slices of existing &OsStr values.
349 let i = match slice[1..].iter().position(|b| *b == b'.') {
351 None => return (file, None),
353 let before = &slice[..i];
354 let after = &slice[i + 1..];
355 unsafe { (u8_slice_as_os_str(before), Some(u8_slice_as_os_str(after))) }
358 ////////////////////////////////////////////////////////////////////////////////
359 // The core iterators
360 ////////////////////////////////////////////////////////////////////////////////
362 /// Component parsing works by a double-ended state machine; the cursors at the
363 /// front and back of the path each keep track of what parts of the path have
364 /// been consumed so far.
366 /// Going front to back, a path is made up of a prefix, a starting
367 /// directory component, and a body (of normal components)
368 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
371 StartDir = 1, // / or . or nothing
372 Body = 2, // foo/bar/baz
376 /// A structure wrapping a Windows path prefix as well as its unparsed string
379 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
380 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
381 /// returned by [`as_os_str`].
383 /// Instances of this `struct` can be obtained by matching against the
384 /// [`Prefix` variant] on [`Component`].
386 /// Does not occur on Unix.
391 /// # if cfg!(windows) {
392 /// use std::path::{Component, Path, Prefix};
393 /// use std::ffi::OsStr;
395 /// let path = Path::new(r"c:\you\later\");
396 /// match path.components().next().unwrap() {
397 /// Component::Prefix(prefix_component) => {
398 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
399 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
401 /// _ => unreachable!(),
406 /// [`as_os_str`]: PrefixComponent::as_os_str
407 /// [`kind`]: PrefixComponent::kind
408 /// [`Prefix` variant]: Component::Prefix
409 #[stable(feature = "rust1", since = "1.0.0")]
410 #[derive(Copy, Clone, Eq, Debug)]
411 pub struct PrefixComponent<'a> {
412 /// The prefix as an unparsed `OsStr` slice.
415 /// The parsed prefix data.
419 impl<'a> PrefixComponent<'a> {
420 /// Returns the parsed prefix data.
422 /// See [`Prefix`]'s documentation for more information on the different
423 /// kinds of prefixes.
424 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn kind(&self) -> Prefix<'a> {
431 /// Returns the raw [`OsStr`] slice for this prefix.
432 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn as_os_str(&self) -> &'a OsStr {
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
443 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
444 cmp::PartialEq::eq(&self.parsed, &other.parsed)
448 #[stable(feature = "rust1", since = "1.0.0")]
449 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
451 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
452 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl cmp::Ord for PrefixComponent<'_> {
459 fn cmp(&self, other: &Self) -> cmp::Ordering {
460 cmp::Ord::cmp(&self.parsed, &other.parsed)
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl Hash for PrefixComponent<'_> {
466 fn hash<H: Hasher>(&self, h: &mut H) {
471 /// A single component of a path.
473 /// A `Component` roughly corresponds to a substring between path separators
476 /// This `enum` is created by iterating over [`Components`], which in turn is
477 /// created by the [`components`](Path::components) method on [`Path`].
482 /// use std::path::{Component, Path};
484 /// let path = Path::new("/tmp/foo/bar.txt");
485 /// let components = path.components().collect::<Vec<_>>();
486 /// assert_eq!(&components, &[
487 /// Component::RootDir,
488 /// Component::Normal("tmp".as_ref()),
489 /// Component::Normal("foo".as_ref()),
490 /// Component::Normal("bar.txt".as_ref()),
493 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub enum Component<'a> {
496 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
498 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
501 /// Does not occur on Unix.
502 #[stable(feature = "rust1", since = "1.0.0")]
503 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
505 /// The root directory component, appears after any prefix and before anything else.
507 /// It represents a separator that designates that a path starts from root.
508 #[stable(feature = "rust1", since = "1.0.0")]
511 /// A reference to the current directory, i.e., `.`.
512 #[stable(feature = "rust1", since = "1.0.0")]
515 /// A reference to the parent directory, i.e., `..`.
516 #[stable(feature = "rust1", since = "1.0.0")]
519 /// A normal component, e.g., `a` and `b` in `a/b`.
521 /// This variant is the most common one, it represents references to files
523 #[stable(feature = "rust1", since = "1.0.0")]
524 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
527 impl<'a> Component<'a> {
528 /// Extracts the underlying [`OsStr`] slice.
533 /// use std::path::Path;
535 /// let path = Path::new("./tmp/foo/bar.txt");
536 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
537 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
539 #[must_use = "`self` will be dropped if the result is not used"]
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn as_os_str(self) -> &'a OsStr {
543 Component::Prefix(p) => p.as_os_str(),
544 Component::RootDir => OsStr::new(MAIN_SEP_STR),
545 Component::CurDir => OsStr::new("."),
546 Component::ParentDir => OsStr::new(".."),
547 Component::Normal(path) => path,
552 #[stable(feature = "rust1", since = "1.0.0")]
553 impl AsRef<OsStr> for Component<'_> {
555 fn as_ref(&self) -> &OsStr {
560 #[stable(feature = "path_component_asref", since = "1.25.0")]
561 impl AsRef<Path> for Component<'_> {
563 fn as_ref(&self) -> &Path {
564 self.as_os_str().as_ref()
568 /// An iterator over the [`Component`]s of a [`Path`].
570 /// This `struct` is created by the [`components`] method on [`Path`].
571 /// See its documentation for more.
576 /// use std::path::Path;
578 /// let path = Path::new("/tmp/foo/bar.txt");
580 /// for component in path.components() {
581 /// println!("{:?}", component);
585 /// [`components`]: Path::components
587 #[must_use = "iterators are lazy and do nothing unless consumed"]
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub struct Components<'a> {
590 // The path left to parse components from
593 // The prefix as it was originally parsed, if any
594 prefix: Option<Prefix<'a>>,
596 // true if path *physically* has a root separator; for most Windows
597 // prefixes, it may have a "logical" root separator for the purposes of
598 // normalization, e.g., \\server\share == \\server\share\.
599 has_physical_root: bool,
601 // The iterator is double-ended, and these two states keep track of what has
602 // been produced from either end
607 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
609 /// This `struct` is created by the [`iter`] method on [`Path`].
610 /// See its documentation for more.
612 /// [`iter`]: Path::iter
614 #[must_use = "iterators are lazy and do nothing unless consumed"]
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub struct Iter<'a> {
617 inner: Components<'a>,
620 #[stable(feature = "path_components_debug", since = "1.13.0")]
621 impl fmt::Debug for Components<'_> {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 struct DebugHelper<'a>(&'a Path);
625 impl fmt::Debug for DebugHelper<'_> {
626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 f.debug_list().entries(self.0.components()).finish()
631 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
635 impl<'a> Components<'a> {
636 // how long is the prefix, if any?
638 fn prefix_len(&self) -> usize {
639 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
643 fn prefix_verbatim(&self) -> bool {
644 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
647 /// how much of the prefix is left from the point of view of iteration?
649 fn prefix_remaining(&self) -> usize {
650 if self.front == State::Prefix { self.prefix_len() } else { 0 }
653 // Given the iteration so far, how much of the pre-State::Body path is left?
655 fn len_before_body(&self) -> usize {
656 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
657 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
658 self.prefix_remaining() + root + cur_dir
661 // is the iteration complete?
663 fn finished(&self) -> bool {
664 self.front == State::Done || self.back == State::Done || self.front > self.back
668 fn is_sep_byte(&self, b: u8) -> bool {
669 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
672 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
677 /// use std::path::Path;
679 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
680 /// components.next();
681 /// components.next();
683 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn as_path(&self) -> &'a Path {
688 let mut comps = self.clone();
689 if comps.front == State::Body {
692 if comps.back == State::Body {
695 unsafe { Path::from_u8_slice(comps.path) }
698 /// Is the *original* path rooted?
699 fn has_root(&self) -> bool {
700 if self.has_physical_root {
703 if let Some(p) = self.prefix {
704 if p.has_implicit_root() {
711 /// Should the normalized path include a leading . ?
712 fn include_cur_dir(&self) -> bool {
716 let mut iter = self.path[self.prefix_len()..].iter();
717 match (iter.next(), iter.next()) {
718 (Some(&b'.'), None) => true,
719 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
724 // parse a given byte sequence into the corresponding path component
725 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
727 b"." if self.prefix_verbatim() => Some(Component::CurDir),
728 b"." => None, // . components are normalized away, except at
729 // the beginning of a path, which is treated
730 // separately via `include_cur_dir`
731 b".." => Some(Component::ParentDir),
733 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
737 // parse a component from the left, saying how many bytes to consume to
738 // remove the component
739 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
740 debug_assert!(self.front == State::Body);
741 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
742 None => (0, self.path),
743 Some(i) => (1, &self.path[..i]),
745 (comp.len() + extra, self.parse_single_component(comp))
748 // parse a component from the right, saying how many bytes to consume to
749 // remove the component
750 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
751 debug_assert!(self.back == State::Body);
752 let start = self.len_before_body();
753 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
754 None => (0, &self.path[start..]),
755 Some(i) => (1, &self.path[start + i + 1..]),
757 (comp.len() + extra, self.parse_single_component(comp))
760 // trim away repeated separators (i.e., empty components) on the left
761 fn trim_left(&mut self) {
762 while !self.path.is_empty() {
763 let (size, comp) = self.parse_next_component();
767 self.path = &self.path[size..];
772 // trim away repeated separators (i.e., empty components) on the right
773 fn trim_right(&mut self) {
774 while self.path.len() > self.len_before_body() {
775 let (size, comp) = self.parse_next_component_back();
779 self.path = &self.path[..self.path.len() - size];
785 #[stable(feature = "rust1", since = "1.0.0")]
786 impl AsRef<Path> for Components<'_> {
788 fn as_ref(&self) -> &Path {
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl AsRef<OsStr> for Components<'_> {
796 fn as_ref(&self) -> &OsStr {
797 self.as_path().as_os_str()
801 #[stable(feature = "path_iter_debug", since = "1.13.0")]
802 impl fmt::Debug for Iter<'_> {
803 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804 struct DebugHelper<'a>(&'a Path);
806 impl fmt::Debug for DebugHelper<'_> {
807 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
808 f.debug_list().entries(self.0.iter()).finish()
812 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
817 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
822 /// use std::path::Path;
824 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
828 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
830 #[stable(feature = "rust1", since = "1.0.0")]
833 pub fn as_path(&self) -> &'a Path {
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl AsRef<Path> for Iter<'_> {
841 fn as_ref(&self) -> &Path {
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl AsRef<OsStr> for Iter<'_> {
849 fn as_ref(&self) -> &OsStr {
850 self.as_path().as_os_str()
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<'a> Iterator for Iter<'a> {
856 type Item = &'a OsStr;
859 fn next(&mut self) -> Option<&'a OsStr> {
860 self.inner.next().map(Component::as_os_str)
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<'a> DoubleEndedIterator for Iter<'a> {
867 fn next_back(&mut self) -> Option<&'a OsStr> {
868 self.inner.next_back().map(Component::as_os_str)
872 #[stable(feature = "fused", since = "1.26.0")]
873 impl FusedIterator for Iter<'_> {}
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl<'a> Iterator for Components<'a> {
877 type Item = Component<'a>;
879 fn next(&mut self) -> Option<Component<'a>> {
880 while !self.finished() {
882 State::Prefix if self.prefix_len() > 0 => {
883 self.front = State::StartDir;
884 debug_assert!(self.prefix_len() <= self.path.len());
885 let raw = &self.path[..self.prefix_len()];
886 self.path = &self.path[self.prefix_len()..];
887 return Some(Component::Prefix(PrefixComponent {
888 raw: unsafe { u8_slice_as_os_str(raw) },
889 parsed: self.prefix.unwrap(),
893 self.front = State::StartDir;
896 self.front = State::Body;
897 if self.has_physical_root {
898 debug_assert!(!self.path.is_empty());
899 self.path = &self.path[1..];
900 return Some(Component::RootDir);
901 } else if let Some(p) = self.prefix {
902 if p.has_implicit_root() && !p.is_verbatim() {
903 return Some(Component::RootDir);
905 } else if self.include_cur_dir() {
906 debug_assert!(!self.path.is_empty());
907 self.path = &self.path[1..];
908 return Some(Component::CurDir);
911 State::Body if !self.path.is_empty() => {
912 let (size, comp) = self.parse_next_component();
913 self.path = &self.path[size..];
919 self.front = State::Done;
921 State::Done => unreachable!(),
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<'a> DoubleEndedIterator for Components<'a> {
930 fn next_back(&mut self) -> Option<Component<'a>> {
931 while !self.finished() {
933 State::Body if self.path.len() > self.len_before_body() => {
934 let (size, comp) = self.parse_next_component_back();
935 self.path = &self.path[..self.path.len() - size];
941 self.back = State::StartDir;
944 self.back = State::Prefix;
945 if self.has_physical_root {
946 self.path = &self.path[..self.path.len() - 1];
947 return Some(Component::RootDir);
948 } else if let Some(p) = self.prefix {
949 if p.has_implicit_root() && !p.is_verbatim() {
950 return Some(Component::RootDir);
952 } else if self.include_cur_dir() {
953 self.path = &self.path[..self.path.len() - 1];
954 return Some(Component::CurDir);
957 State::Prefix if self.prefix_len() > 0 => {
958 self.back = State::Done;
959 return Some(Component::Prefix(PrefixComponent {
960 raw: unsafe { u8_slice_as_os_str(self.path) },
961 parsed: self.prefix.unwrap(),
965 self.back = State::Done;
968 State::Done => unreachable!(),
975 #[stable(feature = "fused", since = "1.26.0")]
976 impl FusedIterator for Components<'_> {}
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl<'a> cmp::PartialEq for Components<'a> {
981 fn eq(&self, other: &Components<'a>) -> bool {
982 let Components { path: _, front: _, back: _, has_physical_root: _, prefix: _ } = self;
984 // Fast path for exact matches, e.g. for hashmap lookups.
985 // Don't explicitly compare the prefix or has_physical_root fields since they'll
986 // either be covered by the `path` buffer or are only relevant for `prefix_verbatim()`.
987 if self.path.len() == other.path.len()
988 && self.front == other.front
989 && self.back == State::Body
990 && other.back == State::Body
991 && self.prefix_verbatim() == other.prefix_verbatim()
993 // possible future improvement: this could bail out earlier if there were a
994 // reverse memcmp/bcmp comparing back to front
995 if self.path == other.path {
1000 // compare back to front since absolute paths often share long prefixes
1001 Iterator::eq(self.clone().rev(), other.clone().rev())
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 impl cmp::Eq for Components<'_> {}
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<'a> cmp::PartialOrd for Components<'a> {
1011 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1012 Some(compare_components(self.clone(), other.clone()))
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl cmp::Ord for Components<'_> {
1019 fn cmp(&self, other: &Self) -> cmp::Ordering {
1020 compare_components(self.clone(), other.clone())
1024 fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cmp::Ordering {
1025 // Fast path for long shared prefixes
1027 // - compare raw bytes to find first mismatch
1028 // - backtrack to find separator before mismatch to avoid ambiguous parsings of '.' or '..' characters
1029 // - if found update state to only do a component-wise comparison on the remainder,
1030 // otherwise do it on the full path
1032 // The fast path isn't taken for paths with a PrefixComponent to avoid backtracking into
1033 // the middle of one
1034 if left.prefix.is_none() && right.prefix.is_none() && left.front == right.front {
1035 // possible future improvement: a [u8]::first_mismatch simd implementation
1036 let first_difference =
1037 match left.path.iter().zip(right.path.iter()).position(|(&a, &b)| a != b) {
1038 None if left.path.len() == right.path.len() => return cmp::Ordering::Equal,
1039 None => left.path.len().min(right.path.len()),
1043 if let Some(previous_sep) =
1044 left.path[..first_difference].iter().rposition(|&b| left.is_sep_byte(b))
1046 let mismatched_component_start = previous_sep + 1;
1047 left.path = &left.path[mismatched_component_start..];
1048 left.front = State::Body;
1049 right.path = &right.path[mismatched_component_start..];
1050 right.front = State::Body;
1054 Iterator::cmp(left, right)
1057 /// An iterator over [`Path`] and its ancestors.
1059 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1060 /// See its documentation for more.
1065 /// use std::path::Path;
1067 /// let path = Path::new("/foo/bar");
1069 /// for ancestor in path.ancestors() {
1070 /// println!("{}", ancestor.display());
1074 /// [`ancestors`]: Path::ancestors
1075 #[derive(Copy, Clone, Debug)]
1076 #[must_use = "iterators are lazy and do nothing unless consumed"]
1077 #[stable(feature = "path_ancestors", since = "1.28.0")]
1078 pub struct Ancestors<'a> {
1079 next: Option<&'a Path>,
1082 #[stable(feature = "path_ancestors", since = "1.28.0")]
1083 impl<'a> Iterator for Ancestors<'a> {
1084 type Item = &'a Path;
1087 fn next(&mut self) -> Option<Self::Item> {
1088 let next = self.next;
1089 self.next = next.and_then(Path::parent);
1094 #[stable(feature = "path_ancestors", since = "1.28.0")]
1095 impl FusedIterator for Ancestors<'_> {}
1097 ////////////////////////////////////////////////////////////////////////////////
1098 // Basic types and traits
1099 ////////////////////////////////////////////////////////////////////////////////
1101 /// An owned, mutable path (akin to [`String`]).
1103 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1104 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1105 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1107 /// [`push`]: PathBuf::push
1108 /// [`set_extension`]: PathBuf::set_extension
1110 /// More details about the overall approach can be found in
1111 /// the [module documentation](self).
1115 /// You can use [`push`] to build up a `PathBuf` from
1119 /// use std::path::PathBuf;
1121 /// let mut path = PathBuf::new();
1123 /// path.push(r"C:\");
1124 /// path.push("windows");
1125 /// path.push("system32");
1127 /// path.set_extension("dll");
1130 /// However, [`push`] is best used for dynamic situations. This is a better way
1131 /// to do this when you know all of the components ahead of time:
1134 /// use std::path::PathBuf;
1136 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1139 /// We can still do better than this! Since these are all strings, we can use
1143 /// use std::path::PathBuf;
1145 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1148 /// Which method works best depends on what kind of situation you're in.
1149 #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1150 #[stable(feature = "rust1", since = "1.0.0")]
1152 // `PathBuf::as_mut_vec` current implementation relies
1153 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1154 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1155 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1156 // not documented and must not be relied upon.
1157 pub struct PathBuf {
1163 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1164 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1167 /// Allocates an empty `PathBuf`.
1172 /// use std::path::PathBuf;
1174 /// let path = PathBuf::new();
1176 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub fn new() -> PathBuf {
1180 PathBuf { inner: OsString::new() }
1183 /// Creates a new `PathBuf` with a given capacity used to create the
1184 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1189 /// use std::path::PathBuf;
1191 /// let mut path = PathBuf::with_capacity(10);
1192 /// let capacity = path.capacity();
1194 /// // This push is done without reallocating
1195 /// path.push(r"C:\");
1197 /// assert_eq!(capacity, path.capacity());
1200 /// [`with_capacity`]: OsString::with_capacity
1201 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1204 pub fn with_capacity(capacity: usize) -> PathBuf {
1205 PathBuf { inner: OsString::with_capacity(capacity) }
1208 /// Coerces to a [`Path`] slice.
1213 /// use std::path::{Path, PathBuf};
1215 /// let p = PathBuf::from("/test");
1216 /// assert_eq!(Path::new("/test"), p.as_path());
1218 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn as_path(&self) -> &Path {
1225 /// Extends `self` with `path`.
1227 /// If `path` is absolute, it replaces the current path.
1231 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1232 /// replaces everything except for the prefix (if any) of `self`.
1233 /// * if `path` has a prefix but no root, it replaces `self`.
1234 /// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
1235 /// and `path` is not empty, the new path is normalized: all references
1236 /// to `.` and `..` are removed.
1240 /// Pushing a relative path extends the existing path:
1243 /// use std::path::PathBuf;
1245 /// let mut path = PathBuf::from("/tmp");
1246 /// path.push("file.bk");
1247 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1250 /// Pushing an absolute path replaces the existing path:
1253 /// use std::path::PathBuf;
1255 /// let mut path = PathBuf::from("/tmp");
1256 /// path.push("/etc");
1257 /// assert_eq!(path, PathBuf::from("/etc"));
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1261 self._push(path.as_ref())
1264 fn _push(&mut self, path: &Path) {
1265 // in general, a separator is needed if the rightmost byte is not a separator
1266 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1268 // in the special case of `C:` on Windows, do *not* add a separator
1269 let comps = self.components();
1271 if comps.prefix_len() > 0
1272 && comps.prefix_len() == comps.path.len()
1273 && comps.prefix.unwrap().is_drive()
1278 // absolute `path` replaces `self`
1279 if path.is_absolute() || path.prefix().is_some() {
1280 self.as_mut_vec().truncate(0);
1282 // verbatim paths need . and .. removed
1283 } else if comps.prefix_verbatim() && !path.inner.is_empty() {
1284 let mut buf: Vec<_> = comps.collect();
1285 for c in path.components() {
1287 Component::RootDir => {
1291 Component::CurDir => (),
1292 Component::ParentDir => {
1293 if let Some(Component::Normal(_)) = buf.last() {
1301 let mut res = OsString::new();
1302 let mut need_sep = false;
1305 if need_sep && c != Component::RootDir {
1306 res.push(MAIN_SEP_STR);
1308 res.push(c.as_os_str());
1310 need_sep = match c {
1311 Component::RootDir => false,
1312 Component::Prefix(prefix) => {
1313 !prefix.parsed.is_drive() && prefix.parsed.len() > 0
1322 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1323 } else if path.has_root() {
1324 let prefix_len = self.components().prefix_remaining();
1325 self.as_mut_vec().truncate(prefix_len);
1327 // `path` is a pure relative path
1328 } else if need_sep {
1329 self.inner.push(MAIN_SEP_STR);
1332 self.inner.push(path);
1335 /// Truncates `self` to [`self.parent`].
1337 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1338 /// Otherwise, returns `true`.
1340 /// [`self.parent`]: Path::parent
1345 /// use std::path::{Path, PathBuf};
1347 /// let mut p = PathBuf::from("/spirited/away.rs");
1350 /// assert_eq!(Path::new("/spirited"), p);
1352 /// assert_eq!(Path::new("/"), p);
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 pub fn pop(&mut self) -> bool {
1356 match self.parent().map(|p| p.as_u8_slice().len()) {
1358 self.as_mut_vec().truncate(len);
1365 /// Updates [`self.file_name`] to `file_name`.
1367 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1370 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1371 /// `file_name`. The new path will be a sibling of the original path.
1372 /// (That is, it will have the same parent.)
1374 /// [`self.file_name`]: Path::file_name
1375 /// [`pop`]: PathBuf::pop
1380 /// use std::path::PathBuf;
1382 /// let mut buf = PathBuf::from("/");
1383 /// assert!(buf.file_name() == None);
1384 /// buf.set_file_name("bar");
1385 /// assert!(buf == PathBuf::from("/bar"));
1386 /// assert!(buf.file_name().is_some());
1387 /// buf.set_file_name("baz.txt");
1388 /// assert!(buf == PathBuf::from("/baz.txt"));
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1392 self._set_file_name(file_name.as_ref())
1395 fn _set_file_name(&mut self, file_name: &OsStr) {
1396 if self.file_name().is_some() {
1397 let popped = self.pop();
1398 debug_assert!(popped);
1400 self.push(file_name);
1403 /// Updates [`self.extension`] to `extension`.
1405 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1406 /// returns `true` and updates the extension otherwise.
1408 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1411 /// [`self.file_name`]: Path::file_name
1412 /// [`self.extension`]: Path::extension
1417 /// use std::path::{Path, PathBuf};
1419 /// let mut p = PathBuf::from("/feel/the");
1421 /// p.set_extension("force");
1422 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1424 /// p.set_extension("dark_side");
1425 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1429 self._set_extension(extension.as_ref())
1432 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1433 let file_stem = match self.file_stem() {
1434 None => return false,
1435 Some(f) => os_str_as_u8_slice(f),
1438 // truncate until right after the file stem
1439 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1440 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1441 let v = self.as_mut_vec();
1442 v.truncate(end_file_stem.wrapping_sub(start));
1444 // add the new extension, if any
1445 let new = os_str_as_u8_slice(extension);
1446 if !new.is_empty() {
1447 v.reserve_exact(new.len() + 1);
1449 v.extend_from_slice(new);
1455 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1460 /// use std::path::PathBuf;
1462 /// let p = PathBuf::from("/the/head");
1463 /// let os_str = p.into_os_string();
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 #[must_use = "`self` will be dropped if the result is not used"]
1468 pub fn into_os_string(self) -> OsString {
1472 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1473 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1474 #[must_use = "`self` will be dropped if the result is not used"]
1476 pub fn into_boxed_path(self) -> Box<Path> {
1477 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1478 unsafe { Box::from_raw(rw) }
1481 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1483 /// [`capacity`]: OsString::capacity
1484 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1487 pub fn capacity(&self) -> usize {
1488 self.inner.capacity()
1491 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1493 /// [`clear`]: OsString::clear
1494 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1496 pub fn clear(&mut self) {
1500 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1502 /// [`reserve`]: OsString::reserve
1503 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1505 pub fn reserve(&mut self, additional: usize) {
1506 self.inner.reserve(additional)
1509 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1511 /// [`reserve_exact`]: OsString::reserve_exact
1512 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1514 pub fn reserve_exact(&mut self, additional: usize) {
1515 self.inner.reserve_exact(additional)
1518 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1520 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1521 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1523 pub fn shrink_to_fit(&mut self) {
1524 self.inner.shrink_to_fit()
1527 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1529 /// [`shrink_to`]: OsString::shrink_to
1530 #[stable(feature = "shrink_to", since = "1.56.0")]
1532 pub fn shrink_to(&mut self, min_capacity: usize) {
1533 self.inner.shrink_to(min_capacity)
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl Clone for PathBuf {
1540 fn clone(&self) -> Self {
1541 PathBuf { inner: self.inner.clone() }
1545 fn clone_from(&mut self, source: &Self) {
1546 self.inner.clone_from(&source.inner)
1550 #[stable(feature = "box_from_path", since = "1.17.0")]
1551 impl From<&Path> for Box<Path> {
1552 /// Creates a boxed [`Path`] from a reference.
1554 /// This will allocate and clone `path` to it.
1555 fn from(path: &Path) -> Box<Path> {
1556 let boxed: Box<OsStr> = path.inner.into();
1557 let rw = Box::into_raw(boxed) as *mut Path;
1558 unsafe { Box::from_raw(rw) }
1562 #[stable(feature = "box_from_cow", since = "1.45.0")]
1563 impl From<Cow<'_, Path>> for Box<Path> {
1564 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1566 /// Converting from a `Cow::Owned` does not clone or allocate.
1568 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1570 Cow::Borrowed(path) => Box::from(path),
1571 Cow::Owned(path) => Box::from(path),
1576 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1577 impl From<Box<Path>> for PathBuf {
1578 /// Converts a `Box<Path>` into a `PathBuf`
1580 /// This conversion does not allocate or copy memory.
1582 fn from(boxed: Box<Path>) -> PathBuf {
1583 boxed.into_path_buf()
1587 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1588 impl From<PathBuf> for Box<Path> {
1589 /// Converts a `PathBuf` into a `Box<Path>`
1591 /// This conversion currently should not allocate memory,
1592 /// but this behavior is not guaranteed on all platforms or in all future versions.
1594 fn from(p: PathBuf) -> Box<Path> {
1599 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1600 impl Clone for Box<Path> {
1602 fn clone(&self) -> Self {
1603 self.to_path_buf().into_boxed_path()
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1609 /// Converts a borrowed `OsStr` to a `PathBuf`.
1611 /// Allocates a [`PathBuf`] and copies the data into it.
1613 fn from(s: &T) -> PathBuf {
1614 PathBuf::from(s.as_ref().to_os_string())
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 impl From<OsString> for PathBuf {
1620 /// Converts an [`OsString`] into a [`PathBuf`]
1622 /// This conversion does not allocate or copy memory.
1624 fn from(s: OsString) -> PathBuf {
1625 PathBuf { inner: s }
1629 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1630 impl From<PathBuf> for OsString {
1631 /// Converts a [`PathBuf`] into an [`OsString`]
1633 /// This conversion does not allocate or copy memory.
1635 fn from(path_buf: PathBuf) -> OsString {
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 impl From<String> for PathBuf {
1642 /// Converts a [`String`] into a [`PathBuf`]
1644 /// This conversion does not allocate or copy memory.
1646 fn from(s: String) -> PathBuf {
1647 PathBuf::from(OsString::from(s))
1651 #[stable(feature = "path_from_str", since = "1.32.0")]
1652 impl FromStr for PathBuf {
1653 type Err = core::convert::Infallible;
1656 fn from_str(s: &str) -> Result<Self, Self::Err> {
1657 Ok(PathBuf::from(s))
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1663 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1664 let mut buf = PathBuf::new();
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1672 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1673 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1677 fn extend_one(&mut self, p: P) {
1678 self.push(p.as_ref());
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 impl fmt::Debug for PathBuf {
1684 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1685 fmt::Debug::fmt(&**self, formatter)
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl ops::Deref for PathBuf {
1693 fn deref(&self) -> &Path {
1694 Path::new(&self.inner)
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 impl Borrow<Path> for PathBuf {
1701 fn borrow(&self) -> &Path {
1706 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1707 impl Default for PathBuf {
1709 fn default() -> Self {
1714 #[stable(feature = "cow_from_path", since = "1.6.0")]
1715 impl<'a> From<&'a Path> for Cow<'a, Path> {
1716 /// Creates a clone-on-write pointer from a reference to
1719 /// This conversion does not clone or allocate.
1721 fn from(s: &'a Path) -> Cow<'a, Path> {
1726 #[stable(feature = "cow_from_path", since = "1.6.0")]
1727 impl<'a> From<PathBuf> for Cow<'a, Path> {
1728 /// Creates a clone-on-write pointer from an owned
1729 /// instance of [`PathBuf`].
1731 /// This conversion does not clone or allocate.
1733 fn from(s: PathBuf) -> Cow<'a, Path> {
1738 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1739 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1740 /// Creates a clone-on-write pointer from a reference to
1743 /// This conversion does not clone or allocate.
1745 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1746 Cow::Borrowed(p.as_path())
1750 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1751 impl<'a> From<Cow<'a, Path>> for PathBuf {
1752 /// Converts a clone-on-write pointer to an owned path.
1754 /// Converting from a `Cow::Owned` does not clone or allocate.
1756 fn from(p: Cow<'a, Path>) -> Self {
1761 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1762 impl From<PathBuf> for Arc<Path> {
1763 /// Converts a [`PathBuf`] into an [`Arc`] by moving the [`PathBuf`] data into a new [`Arc`] buffer.
1765 fn from(s: PathBuf) -> Arc<Path> {
1766 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1767 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1771 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1772 impl From<&Path> for Arc<Path> {
1773 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
1775 fn from(s: &Path) -> Arc<Path> {
1776 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1777 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1781 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1782 impl From<PathBuf> for Rc<Path> {
1783 /// Converts a [`PathBuf`] into an [`Rc`] by moving the [`PathBuf`] data into a new `Rc` buffer.
1785 fn from(s: PathBuf) -> Rc<Path> {
1786 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1787 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1791 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1792 impl From<&Path> for Rc<Path> {
1793 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new `Rc` buffer.
1795 fn from(s: &Path) -> Rc<Path> {
1796 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1797 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl ToOwned for Path {
1803 type Owned = PathBuf;
1805 fn to_owned(&self) -> PathBuf {
1809 fn clone_into(&self, target: &mut PathBuf) {
1810 self.inner.clone_into(&mut target.inner);
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 impl cmp::PartialEq for PathBuf {
1817 fn eq(&self, other: &PathBuf) -> bool {
1818 self.components() == other.components()
1822 #[stable(feature = "rust1", since = "1.0.0")]
1823 impl Hash for PathBuf {
1824 fn hash<H: Hasher>(&self, h: &mut H) {
1825 self.as_path().hash(h)
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 impl cmp::Eq for PathBuf {}
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl cmp::PartialOrd for PathBuf {
1835 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1836 Some(compare_components(self.components(), other.components()))
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 impl cmp::Ord for PathBuf {
1843 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1844 compare_components(self.components(), other.components())
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 impl AsRef<OsStr> for PathBuf {
1851 fn as_ref(&self) -> &OsStr {
1856 /// A slice of a path (akin to [`str`]).
1858 /// This type supports a number of operations for inspecting a path, including
1859 /// breaking the path into its components (separated by `/` on Unix and by either
1860 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1861 /// is absolute, and so on.
1863 /// This is an *unsized* type, meaning that it must always be used behind a
1864 /// pointer like `&` or [`Box`]. For an owned version of this type,
1865 /// see [`PathBuf`].
1867 /// More details about the overall approach can be found in
1868 /// the [module documentation](self).
1873 /// use std::path::Path;
1874 /// use std::ffi::OsStr;
1876 /// // Note: this example does work on Windows
1877 /// let path = Path::new("./foo/bar.txt");
1879 /// let parent = path.parent();
1880 /// assert_eq!(parent, Some(Path::new("./foo")));
1882 /// let file_stem = path.file_stem();
1883 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1885 /// let extension = path.extension();
1886 /// assert_eq!(extension, Some(OsStr::new("txt")));
1888 #[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
1889 #[stable(feature = "rust1", since = "1.0.0")]
1891 // `Path::new` current implementation relies
1892 // on `Path` being layout-compatible with `OsStr`.
1893 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1894 // Anyway, `Path` representation and layout are considered implementation detail, are
1895 // not documented and must not be relied upon.
1900 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1902 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1903 /// See its documentation for more.
1905 /// [`strip_prefix`]: Path::strip_prefix
1906 #[derive(Debug, Clone, PartialEq, Eq)]
1907 #[stable(since = "1.7.0", feature = "strip_prefix")]
1908 pub struct StripPrefixError(());
1911 // The following (private!) function allows construction of a path from a u8
1912 // slice, which is only safe when it is known to follow the OsStr encoding.
1913 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1914 unsafe { Path::new(u8_slice_as_os_str(s)) }
1916 // The following (private!) function reveals the byte encoding used for OsStr.
1917 fn as_u8_slice(&self) -> &[u8] {
1918 os_str_as_u8_slice(&self.inner)
1921 /// Directly wraps a string slice as a `Path` slice.
1923 /// This is a cost-free conversion.
1928 /// use std::path::Path;
1930 /// Path::new("foo.txt");
1933 /// You can create `Path`s from `String`s, or even other `Path`s:
1936 /// use std::path::Path;
1938 /// let string = String::from("foo.txt");
1939 /// let from_string = Path::new(&string);
1940 /// let from_path = Path::new(&from_string);
1941 /// assert_eq!(from_string, from_path);
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1945 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1948 /// Yields the underlying [`OsStr`] slice.
1953 /// use std::path::Path;
1955 /// let os_str = Path::new("foo.txt").as_os_str();
1956 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1958 #[stable(feature = "rust1", since = "1.0.0")]
1961 pub fn as_os_str(&self) -> &OsStr {
1965 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1967 /// This conversion may entail doing a check for UTF-8 validity.
1968 /// Note that validation is performed because non-UTF-8 strings are
1969 /// perfectly valid for some OS.
1976 /// use std::path::Path;
1978 /// let path = Path::new("foo.txt");
1979 /// assert_eq!(path.to_str(), Some("foo.txt"));
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 #[must_use = "this returns the result of the operation, \
1983 without modifying the original"]
1985 pub fn to_str(&self) -> Option<&str> {
1989 /// Converts a `Path` to a [`Cow<str>`].
1991 /// Any non-Unicode sequences are replaced with
1992 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1994 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1998 /// Calling `to_string_lossy` on a `Path` with valid unicode:
2001 /// use std::path::Path;
2003 /// let path = Path::new("foo.txt");
2004 /// assert_eq!(path.to_string_lossy(), "foo.txt");
2007 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
2008 /// have returned `"fo�.txt"`.
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 #[must_use = "this returns the result of the operation, \
2011 without modifying the original"]
2013 pub fn to_string_lossy(&self) -> Cow<'_, str> {
2014 self.inner.to_string_lossy()
2017 /// Converts a `Path` to an owned [`PathBuf`].
2022 /// use std::path::Path;
2024 /// let path_buf = Path::new("foo.txt").to_path_buf();
2025 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
2027 #[rustc_conversion_suggestion]
2028 #[must_use = "this returns the result of the operation, \
2029 without modifying the original"]
2030 #[stable(feature = "rust1", since = "1.0.0")]
2031 pub fn to_path_buf(&self) -> PathBuf {
2032 PathBuf::from(self.inner.to_os_string())
2035 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
2036 /// the current directory.
2038 /// * On Unix, a path is absolute if it starts with the root, so
2039 /// `is_absolute` and [`has_root`] are equivalent.
2041 /// * On Windows, a path is absolute if it has a prefix and starts with the
2042 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
2047 /// use std::path::Path;
2049 /// assert!(!Path::new("foo.txt").is_absolute());
2052 /// [`has_root`]: Path::has_root
2053 #[stable(feature = "rust1", since = "1.0.0")]
2055 #[allow(deprecated)]
2056 pub fn is_absolute(&self) -> bool {
2057 if cfg!(target_os = "redox") {
2058 // FIXME: Allow Redox prefixes
2059 self.has_root() || has_redox_scheme(self.as_u8_slice())
2061 self.has_root() && (cfg!(any(unix, target_os = "wasi")) || self.prefix().is_some())
2065 /// Returns `true` if the `Path` is relative, i.e., not absolute.
2067 /// See [`is_absolute`]'s documentation for more details.
2072 /// use std::path::Path;
2074 /// assert!(Path::new("foo.txt").is_relative());
2077 /// [`is_absolute`]: Path::is_absolute
2078 #[stable(feature = "rust1", since = "1.0.0")]
2081 pub fn is_relative(&self) -> bool {
2085 fn prefix(&self) -> Option<Prefix<'_>> {
2086 self.components().prefix
2089 /// Returns `true` if the `Path` has a root.
2091 /// * On Unix, a path has a root if it begins with `/`.
2093 /// * On Windows, a path has a root if it:
2094 /// * has no prefix and begins with a separator, e.g., `\windows`
2095 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
2096 /// * has any non-disk prefix, e.g., `\\server\share`
2101 /// use std::path::Path;
2103 /// assert!(Path::new("/etc/passwd").has_root());
2105 #[stable(feature = "rust1", since = "1.0.0")]
2108 pub fn has_root(&self) -> bool {
2109 self.components().has_root()
2112 /// Returns the `Path` without its final component, if there is one.
2114 /// Returns [`None`] if the path terminates in a root or prefix.
2119 /// use std::path::Path;
2121 /// let path = Path::new("/foo/bar");
2122 /// let parent = path.parent().unwrap();
2123 /// assert_eq!(parent, Path::new("/foo"));
2125 /// let grand_parent = parent.parent().unwrap();
2126 /// assert_eq!(grand_parent, Path::new("/"));
2127 /// assert_eq!(grand_parent.parent(), None);
2129 #[stable(feature = "rust1", since = "1.0.0")]
2131 pub fn parent(&self) -> Option<&Path> {
2132 let mut comps = self.components();
2133 let comp = comps.next_back();
2134 comp.and_then(|p| match p {
2135 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
2136 Some(comps.as_path())
2142 /// Produces an iterator over `Path` and its ancestors.
2144 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2145 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2146 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2147 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2153 /// use std::path::Path;
2155 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2156 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2157 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2158 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2159 /// assert_eq!(ancestors.next(), None);
2161 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2162 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2163 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2164 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2165 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2166 /// assert_eq!(ancestors.next(), None);
2169 /// [`parent`]: Path::parent
2170 #[stable(feature = "path_ancestors", since = "1.28.0")]
2172 pub fn ancestors(&self) -> Ancestors<'_> {
2173 Ancestors { next: Some(&self) }
2176 /// Returns the final component of the `Path`, if there is one.
2178 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2179 /// is the directory name.
2181 /// Returns [`None`] if the path terminates in `..`.
2186 /// use std::path::Path;
2187 /// use std::ffi::OsStr;
2189 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2190 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2191 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2192 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2193 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2194 /// assert_eq!(None, Path::new("/").file_name());
2196 #[stable(feature = "rust1", since = "1.0.0")]
2198 pub fn file_name(&self) -> Option<&OsStr> {
2199 self.components().next_back().and_then(|p| match p {
2200 Component::Normal(p) => Some(p),
2205 /// Returns a path that, when joined onto `base`, yields `self`.
2209 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2210 /// returns `false`), returns [`Err`].
2212 /// [`starts_with`]: Path::starts_with
2217 /// use std::path::{Path, PathBuf};
2219 /// let path = Path::new("/test/haha/foo.txt");
2221 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2222 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2223 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2224 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2225 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2227 /// assert!(path.strip_prefix("test").is_err());
2228 /// assert!(path.strip_prefix("/haha").is_err());
2230 /// let prefix = PathBuf::from("/test/");
2231 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2233 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2234 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2238 self._strip_prefix(base.as_ref())
2241 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2242 iter_after(self.components(), base.components())
2243 .map(|c| c.as_path())
2244 .ok_or(StripPrefixError(()))
2247 /// Determines whether `base` is a prefix of `self`.
2249 /// Only considers whole path components to match.
2254 /// use std::path::Path;
2256 /// let path = Path::new("/etc/passwd");
2258 /// assert!(path.starts_with("/etc"));
2259 /// assert!(path.starts_with("/etc/"));
2260 /// assert!(path.starts_with("/etc/passwd"));
2261 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2262 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2264 /// assert!(!path.starts_with("/e"));
2265 /// assert!(!path.starts_with("/etc/passwd.txt"));
2267 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2269 #[stable(feature = "rust1", since = "1.0.0")]
2271 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2272 self._starts_with(base.as_ref())
2275 fn _starts_with(&self, base: &Path) -> bool {
2276 iter_after(self.components(), base.components()).is_some()
2279 /// Determines whether `child` is a suffix of `self`.
2281 /// Only considers whole path components to match.
2286 /// use std::path::Path;
2288 /// let path = Path::new("/etc/resolv.conf");
2290 /// assert!(path.ends_with("resolv.conf"));
2291 /// assert!(path.ends_with("etc/resolv.conf"));
2292 /// assert!(path.ends_with("/etc/resolv.conf"));
2294 /// assert!(!path.ends_with("/resolv.conf"));
2295 /// assert!(!path.ends_with("conf")); // use .extension() instead
2297 #[stable(feature = "rust1", since = "1.0.0")]
2299 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2300 self._ends_with(child.as_ref())
2303 fn _ends_with(&self, child: &Path) -> bool {
2304 iter_after(self.components().rev(), child.components().rev()).is_some()
2307 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2309 /// [`self.file_name`]: Path::file_name
2313 /// * [`None`], if there is no file name;
2314 /// * The entire file name if there is no embedded `.`;
2315 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2316 /// * Otherwise, the portion of the file name before the final `.`
2321 /// use std::path::Path;
2323 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2324 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2328 /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
2329 /// before the *first* `.`
2331 /// [`Path::file_prefix`]: Path::file_prefix
2333 #[stable(feature = "rust1", since = "1.0.0")]
2335 pub fn file_stem(&self) -> Option<&OsStr> {
2336 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2339 /// Extracts the prefix of [`self.file_name`].
2343 /// * [`None`], if there is no file name;
2344 /// * The entire file name if there is no embedded `.`;
2345 /// * The portion of the file name before the first non-beginning `.`;
2346 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2347 /// * The portion of the file name before the second `.` if the file name begins with `.`
2349 /// [`self.file_name`]: Path::file_name
2354 /// # #![feature(path_file_prefix)]
2355 /// use std::path::Path;
2357 /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
2358 /// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
2362 /// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
2363 /// before the *last* `.`
2365 /// [`Path::file_stem`]: Path::file_stem
2367 #[unstable(feature = "path_file_prefix", issue = "86319")]
2369 pub fn file_prefix(&self) -> Option<&OsStr> {
2370 self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before))
2373 /// Extracts the extension of [`self.file_name`], if possible.
2375 /// The extension is:
2377 /// * [`None`], if there is no file name;
2378 /// * [`None`], if there is no embedded `.`;
2379 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2380 /// * Otherwise, the portion of the file name after the final `.`
2382 /// [`self.file_name`]: Path::file_name
2387 /// use std::path::Path;
2389 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2390 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2392 #[stable(feature = "rust1", since = "1.0.0")]
2394 pub fn extension(&self) -> Option<&OsStr> {
2395 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
2398 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2400 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2405 /// use std::path::{Path, PathBuf};
2407 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2409 #[stable(feature = "rust1", since = "1.0.0")]
2411 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2412 self._join(path.as_ref())
2415 fn _join(&self, path: &Path) -> PathBuf {
2416 let mut buf = self.to_path_buf();
2421 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2423 /// See [`PathBuf::set_file_name`] for more details.
2428 /// use std::path::{Path, PathBuf};
2430 /// let path = Path::new("/tmp/foo.txt");
2431 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2433 /// let path = Path::new("/tmp");
2434 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2436 #[stable(feature = "rust1", since = "1.0.0")]
2438 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2439 self._with_file_name(file_name.as_ref())
2442 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2443 let mut buf = self.to_path_buf();
2444 buf.set_file_name(file_name);
2448 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2450 /// See [`PathBuf::set_extension`] for more details.
2455 /// use std::path::{Path, PathBuf};
2457 /// let path = Path::new("foo.rs");
2458 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2460 /// let path = Path::new("foo.tar.gz");
2461 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2462 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2463 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2467 self._with_extension(extension.as_ref())
2470 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2471 let mut buf = self.to_path_buf();
2472 buf.set_extension(extension);
2476 /// Produces an iterator over the [`Component`]s of the path.
2478 /// When parsing the path, there is a small amount of normalization:
2480 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2481 /// `a` and `b` as components.
2483 /// * Occurrences of `.` are normalized away, except if they are at the
2484 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2485 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2486 /// an additional [`CurDir`] component.
2488 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2490 /// Note that no other normalization takes place; in particular, `a/c`
2491 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2492 /// is a symbolic link (so its parent isn't `a`).
2497 /// use std::path::{Path, Component};
2498 /// use std::ffi::OsStr;
2500 /// let mut components = Path::new("/tmp/foo.txt").components();
2502 /// assert_eq!(components.next(), Some(Component::RootDir));
2503 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2504 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2505 /// assert_eq!(components.next(), None)
2508 /// [`CurDir`]: Component::CurDir
2509 #[stable(feature = "rust1", since = "1.0.0")]
2510 pub fn components(&self) -> Components<'_> {
2511 let prefix = parse_prefix(self.as_os_str());
2513 path: self.as_u8_slice(),
2515 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2516 || has_redox_scheme(self.as_u8_slice()),
2517 front: State::Prefix,
2522 /// Produces an iterator over the path's components viewed as [`OsStr`]
2525 /// For more information about the particulars of how the path is separated
2526 /// into components, see [`components`].
2528 /// [`components`]: Path::components
2533 /// use std::path::{self, Path};
2534 /// use std::ffi::OsStr;
2536 /// let mut it = Path::new("/tmp/foo.txt").iter();
2537 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2538 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2539 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2540 /// assert_eq!(it.next(), None)
2542 #[stable(feature = "rust1", since = "1.0.0")]
2544 pub fn iter(&self) -> Iter<'_> {
2545 Iter { inner: self.components() }
2548 /// Returns an object that implements [`Display`] for safely printing paths
2549 /// that may contain non-Unicode data. This may perform lossy conversion,
2550 /// depending on the platform. If you would like an implementation which
2551 /// escapes the path please use [`Debug`] instead.
2553 /// [`Display`]: fmt::Display
2558 /// use std::path::Path;
2560 /// let path = Path::new("/tmp/foo.rs");
2562 /// println!("{}", path.display());
2564 #[stable(feature = "rust1", since = "1.0.0")]
2565 #[must_use = "this does not display the path, \
2566 it returns an object that can be displayed"]
2568 pub fn display(&self) -> Display<'_> {
2569 Display { path: self }
2572 /// Queries the file system to get information about a file, directory, etc.
2574 /// This function will traverse symbolic links to query information about the
2575 /// destination file.
2577 /// This is an alias to [`fs::metadata`].
2582 /// use std::path::Path;
2584 /// let path = Path::new("/Minas/tirith");
2585 /// let metadata = path.metadata().expect("metadata call failed");
2586 /// println!("{:?}", metadata.file_type());
2588 #[stable(feature = "path_ext", since = "1.5.0")]
2590 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2594 /// Queries the metadata about a file without following symlinks.
2596 /// This is an alias to [`fs::symlink_metadata`].
2601 /// use std::path::Path;
2603 /// let path = Path::new("/Minas/tirith");
2604 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2605 /// println!("{:?}", metadata.file_type());
2607 #[stable(feature = "path_ext", since = "1.5.0")]
2609 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2610 fs::symlink_metadata(self)
2613 /// Returns the canonical, absolute form of the path with all intermediate
2614 /// components normalized and symbolic links resolved.
2616 /// This is an alias to [`fs::canonicalize`].
2621 /// use std::path::{Path, PathBuf};
2623 /// let path = Path::new("/foo/test/../test/bar.rs");
2624 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2626 #[stable(feature = "path_ext", since = "1.5.0")]
2628 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2629 fs::canonicalize(self)
2632 /// Reads a symbolic link, returning the file that the link points to.
2634 /// This is an alias to [`fs::read_link`].
2639 /// use std::path::Path;
2641 /// let path = Path::new("/laputa/sky_castle.rs");
2642 /// let path_link = path.read_link().expect("read_link call failed");
2644 #[stable(feature = "path_ext", since = "1.5.0")]
2646 pub fn read_link(&self) -> io::Result<PathBuf> {
2650 /// Returns an iterator over the entries within a directory.
2652 /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. New
2653 /// errors may be encountered after an iterator is initially constructed.
2655 /// This is an alias to [`fs::read_dir`].
2660 /// use std::path::Path;
2662 /// let path = Path::new("/laputa");
2663 /// for entry in path.read_dir().expect("read_dir call failed") {
2664 /// if let Ok(entry) = entry {
2665 /// println!("{:?}", entry.path());
2669 #[stable(feature = "path_ext", since = "1.5.0")]
2671 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2675 /// Returns `true` if the path points at an existing entity.
2677 /// This function will traverse symbolic links to query information about the
2678 /// destination file.
2680 /// If you cannot access the metadata of the file, e.g. because of a
2681 /// permission error or broken symbolic links, this will return `false`.
2686 /// use std::path::Path;
2687 /// assert!(!Path::new("does_not_exist.txt").exists());
2692 /// This is a convenience function that coerces errors to false. If you want to
2693 /// check errors, call [`fs::metadata`].
2694 #[stable(feature = "path_ext", since = "1.5.0")]
2697 pub fn exists(&self) -> bool {
2698 fs::metadata(self).is_ok()
2701 /// Returns `Ok(true)` if the path points at an existing entity.
2703 /// This function will traverse symbolic links to query information about the
2704 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2706 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2707 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2708 /// denied on some of the parent directories.)
2713 /// #![feature(path_try_exists)]
2715 /// use std::path::Path;
2716 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2717 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2719 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2721 #[unstable(feature = "path_try_exists", issue = "83186")]
2723 pub fn try_exists(&self) -> io::Result<bool> {
2724 fs::try_exists(self)
2727 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2729 /// This function will traverse symbolic links to query information about the
2730 /// destination file.
2732 /// If you cannot access the metadata of the file, e.g. because of a
2733 /// permission error or broken symbolic links, this will return `false`.
2738 /// use std::path::Path;
2739 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2740 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2745 /// This is a convenience function that coerces errors to false. If you want to
2746 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2747 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2749 /// When the goal is simply to read from (or write to) the source, the most
2750 /// reliable way to test the source can be read (or written to) is to open
2751 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2752 /// a Unix-like system for example. See [`fs::File::open`] or
2753 /// [`fs::OpenOptions::open`] for more information.
2754 #[stable(feature = "path_ext", since = "1.5.0")]
2756 pub fn is_file(&self) -> bool {
2757 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2760 /// Returns `true` if the path exists on disk and is pointing at a directory.
2762 /// This function will traverse symbolic links to query information about the
2763 /// destination file.
2765 /// If you cannot access the metadata of the file, e.g. because of a
2766 /// permission error or broken symbolic links, this will return `false`.
2771 /// use std::path::Path;
2772 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2773 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2778 /// This is a convenience function that coerces errors to false. If you want to
2779 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2780 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2781 #[stable(feature = "path_ext", since = "1.5.0")]
2783 pub fn is_dir(&self) -> bool {
2784 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2787 /// Returns `true` if the path exists on disk and is pointing at a symbolic link.
2789 /// This function will not traverse symbolic links.
2790 /// In case of a broken symbolic link this will also return true.
2792 /// If you cannot access the directory containing the file, e.g., because of a
2793 /// permission error, this will return false.
2797 #[cfg_attr(unix, doc = "```no_run")]
2798 #[cfg_attr(not(unix), doc = "```ignore")]
2799 /// use std::path::Path;
2800 /// use std::os::unix::fs::symlink;
2802 /// let link_path = Path::new("link");
2803 /// symlink("/origin_does_not_exists/", link_path).unwrap();
2804 /// assert_eq!(link_path.is_symlink(), true);
2805 /// assert_eq!(link_path.exists(), false);
2810 /// This is a convenience function that coerces errors to false. If you want to
2811 /// check errors, call [`fs::symlink_metadata`] and handle its [`Result`]. Then call
2812 /// [`fs::Metadata::is_symlink`] if it was [`Ok`].
2814 #[stable(feature = "is_symlink", since = "1.57.0")]
2815 pub fn is_symlink(&self) -> bool {
2816 fs::symlink_metadata(self).map(|m| m.is_symlink()).unwrap_or(false)
2819 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2821 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2822 #[must_use = "`self` will be dropped if the result is not used"]
2823 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2824 let rw = Box::into_raw(self) as *mut OsStr;
2825 let inner = unsafe { Box::from_raw(rw) };
2826 PathBuf { inner: OsString::from(inner) }
2830 #[stable(feature = "rust1", since = "1.0.0")]
2831 impl AsRef<OsStr> for Path {
2833 fn as_ref(&self) -> &OsStr {
2838 #[stable(feature = "rust1", since = "1.0.0")]
2839 impl fmt::Debug for Path {
2840 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2841 fmt::Debug::fmt(&self.inner, formatter)
2845 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2847 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2848 /// [`Display`] trait in a way that mitigates that. It is created by the
2849 /// [`display`](Path::display) method on [`Path`]. This may perform lossy
2850 /// conversion, depending on the platform. If you would like an implementation
2851 /// which escapes the path please use [`Debug`] instead.
2856 /// use std::path::Path;
2858 /// let path = Path::new("/tmp/foo.rs");
2860 /// println!("{}", path.display());
2863 /// [`Display`]: fmt::Display
2864 /// [`format!`]: crate::format
2865 #[stable(feature = "rust1", since = "1.0.0")]
2866 pub struct Display<'a> {
2870 #[stable(feature = "rust1", since = "1.0.0")]
2871 impl fmt::Debug for Display<'_> {
2872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2873 fmt::Debug::fmt(&self.path, f)
2877 #[stable(feature = "rust1", since = "1.0.0")]
2878 impl fmt::Display for Display<'_> {
2879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2880 self.path.inner.display(f)
2884 #[stable(feature = "rust1", since = "1.0.0")]
2885 impl cmp::PartialEq for Path {
2887 fn eq(&self, other: &Path) -> bool {
2888 self.components() == other.components()
2892 #[stable(feature = "rust1", since = "1.0.0")]
2893 impl Hash for Path {
2894 fn hash<H: Hasher>(&self, h: &mut H) {
2895 let bytes = self.as_u8_slice();
2897 let mut component_start = 0;
2898 let mut bytes_hashed = 0;
2900 for i in 0..bytes.len() {
2901 if is_sep_byte(bytes[i]) {
2902 if i > component_start {
2903 let to_hash = &bytes[component_start..i];
2905 bytes_hashed += to_hash.len();
2908 // skip over separator and optionally a following CurDir item
2909 // since components() would normalize these away
2910 component_start = i + match bytes[i..] {
2911 [_, b'.', b'/', ..] | [_, b'.'] => 2,
2917 if component_start < bytes.len() {
2918 let to_hash = &bytes[component_start..];
2920 bytes_hashed += to_hash.len();
2923 h.write_usize(bytes_hashed);
2927 #[stable(feature = "rust1", since = "1.0.0")]
2928 impl cmp::Eq for Path {}
2930 #[stable(feature = "rust1", since = "1.0.0")]
2931 impl cmp::PartialOrd for Path {
2933 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2934 Some(compare_components(self.components(), other.components()))
2938 #[stable(feature = "rust1", since = "1.0.0")]
2939 impl cmp::Ord for Path {
2941 fn cmp(&self, other: &Path) -> cmp::Ordering {
2942 compare_components(self.components(), other.components())
2946 #[stable(feature = "rust1", since = "1.0.0")]
2947 impl AsRef<Path> for Path {
2949 fn as_ref(&self) -> &Path {
2954 #[stable(feature = "rust1", since = "1.0.0")]
2955 impl AsRef<Path> for OsStr {
2957 fn as_ref(&self) -> &Path {
2962 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2963 impl AsRef<Path> for Cow<'_, OsStr> {
2965 fn as_ref(&self) -> &Path {
2970 #[stable(feature = "rust1", since = "1.0.0")]
2971 impl AsRef<Path> for OsString {
2973 fn as_ref(&self) -> &Path {
2978 #[stable(feature = "rust1", since = "1.0.0")]
2979 impl AsRef<Path> for str {
2981 fn as_ref(&self) -> &Path {
2986 #[stable(feature = "rust1", since = "1.0.0")]
2987 impl AsRef<Path> for String {
2989 fn as_ref(&self) -> &Path {
2994 #[stable(feature = "rust1", since = "1.0.0")]
2995 impl AsRef<Path> for PathBuf {
2997 fn as_ref(&self) -> &Path {
3002 #[stable(feature = "path_into_iter", since = "1.6.0")]
3003 impl<'a> IntoIterator for &'a PathBuf {
3004 type Item = &'a OsStr;
3005 type IntoIter = Iter<'a>;
3007 fn into_iter(self) -> Iter<'a> {
3012 #[stable(feature = "path_into_iter", since = "1.6.0")]
3013 impl<'a> IntoIterator for &'a Path {
3014 type Item = &'a OsStr;
3015 type IntoIter = Iter<'a>;
3017 fn into_iter(self) -> Iter<'a> {
3022 macro_rules! impl_cmp {
3023 ($lhs:ty, $rhs: ty) => {
3024 #[stable(feature = "partialeq_path", since = "1.6.0")]
3025 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3027 fn eq(&self, other: &$rhs) -> bool {
3028 <Path as PartialEq>::eq(self, other)
3032 #[stable(feature = "partialeq_path", since = "1.6.0")]
3033 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3035 fn eq(&self, other: &$lhs) -> bool {
3036 <Path as PartialEq>::eq(self, other)
3040 #[stable(feature = "cmp_path", since = "1.8.0")]
3041 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3043 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3044 <Path as PartialOrd>::partial_cmp(self, other)
3048 #[stable(feature = "cmp_path", since = "1.8.0")]
3049 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3051 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3052 <Path as PartialOrd>::partial_cmp(self, other)
3058 impl_cmp!(PathBuf, Path);
3059 impl_cmp!(PathBuf, &'a Path);
3060 impl_cmp!(Cow<'a, Path>, Path);
3061 impl_cmp!(Cow<'a, Path>, &'b Path);
3062 impl_cmp!(Cow<'a, Path>, PathBuf);
3064 macro_rules! impl_cmp_os_str {
3065 ($lhs:ty, $rhs: ty) => {
3066 #[stable(feature = "cmp_path", since = "1.8.0")]
3067 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3069 fn eq(&self, other: &$rhs) -> bool {
3070 <Path as PartialEq>::eq(self, other.as_ref())
3074 #[stable(feature = "cmp_path", since = "1.8.0")]
3075 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3077 fn eq(&self, other: &$lhs) -> bool {
3078 <Path as PartialEq>::eq(self.as_ref(), other)
3082 #[stable(feature = "cmp_path", since = "1.8.0")]
3083 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3085 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3086 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
3090 #[stable(feature = "cmp_path", since = "1.8.0")]
3091 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3093 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3094 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
3100 impl_cmp_os_str!(PathBuf, OsStr);
3101 impl_cmp_os_str!(PathBuf, &'a OsStr);
3102 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
3103 impl_cmp_os_str!(PathBuf, OsString);
3104 impl_cmp_os_str!(Path, OsStr);
3105 impl_cmp_os_str!(Path, &'a OsStr);
3106 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
3107 impl_cmp_os_str!(Path, OsString);
3108 impl_cmp_os_str!(&'a Path, OsStr);
3109 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
3110 impl_cmp_os_str!(&'a Path, OsString);
3111 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
3112 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
3113 impl_cmp_os_str!(Cow<'a, Path>, OsString);
3115 #[stable(since = "1.7.0", feature = "strip_prefix")]
3116 impl fmt::Display for StripPrefixError {
3117 #[allow(deprecated, deprecated_in_future)]
3118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3119 self.description().fmt(f)
3123 #[stable(since = "1.7.0", feature = "strip_prefix")]
3124 impl Error for StripPrefixError {
3125 #[allow(deprecated)]
3126 fn description(&self) -> &str {