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")]
426 pub fn kind(&self) -> Prefix<'a> {
430 /// Returns the raw [`OsStr`] slice for this prefix.
431 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn as_os_str(&self) -> &'a OsStr {
439 #[stable(feature = "rust1", since = "1.0.0")]
440 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
442 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
443 cmp::PartialEq::eq(&self.parsed, &other.parsed)
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
450 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
451 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl cmp::Ord for PrefixComponent<'_> {
458 fn cmp(&self, other: &Self) -> cmp::Ordering {
459 cmp::Ord::cmp(&self.parsed, &other.parsed)
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl Hash for PrefixComponent<'_> {
465 fn hash<H: Hasher>(&self, h: &mut H) {
470 /// A single component of a path.
472 /// A `Component` roughly corresponds to a substring between path separators
475 /// This `enum` is created by iterating over [`Components`], which in turn is
476 /// created by the [`components`](Path::components) method on [`Path`].
481 /// use std::path::{Component, Path};
483 /// let path = Path::new("/tmp/foo/bar.txt");
484 /// let components = path.components().collect::<Vec<_>>();
485 /// assert_eq!(&components, &[
486 /// Component::RootDir,
487 /// Component::Normal("tmp".as_ref()),
488 /// Component::Normal("foo".as_ref()),
489 /// Component::Normal("bar.txt".as_ref()),
492 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub enum Component<'a> {
495 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
497 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
500 /// Does not occur on Unix.
501 #[stable(feature = "rust1", since = "1.0.0")]
502 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
504 /// The root directory component, appears after any prefix and before anything else.
506 /// It represents a separator that designates that a path starts from root.
507 #[stable(feature = "rust1", since = "1.0.0")]
510 /// A reference to the current directory, i.e., `.`.
511 #[stable(feature = "rust1", since = "1.0.0")]
514 /// A reference to the parent directory, i.e., `..`.
515 #[stable(feature = "rust1", since = "1.0.0")]
518 /// A normal component, e.g., `a` and `b` in `a/b`.
520 /// This variant is the most common one, it represents references to files
522 #[stable(feature = "rust1", since = "1.0.0")]
523 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
526 impl<'a> Component<'a> {
527 /// Extracts the underlying [`OsStr`] slice.
532 /// use std::path::Path;
534 /// let path = Path::new("./tmp/foo/bar.txt");
535 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
536 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
538 #[must_use = "`self` will be dropped if the result is not used"]
539 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn as_os_str(self) -> &'a OsStr {
542 Component::Prefix(p) => p.as_os_str(),
543 Component::RootDir => OsStr::new(MAIN_SEP_STR),
544 Component::CurDir => OsStr::new("."),
545 Component::ParentDir => OsStr::new(".."),
546 Component::Normal(path) => path,
551 #[stable(feature = "rust1", since = "1.0.0")]
552 impl AsRef<OsStr> for Component<'_> {
554 fn as_ref(&self) -> &OsStr {
559 #[stable(feature = "path_component_asref", since = "1.25.0")]
560 impl AsRef<Path> for Component<'_> {
562 fn as_ref(&self) -> &Path {
563 self.as_os_str().as_ref()
567 /// An iterator over the [`Component`]s of a [`Path`].
569 /// This `struct` is created by the [`components`] method on [`Path`].
570 /// See its documentation for more.
575 /// use std::path::Path;
577 /// let path = Path::new("/tmp/foo/bar.txt");
579 /// for component in path.components() {
580 /// println!("{:?}", component);
584 /// [`components`]: Path::components
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub struct Components<'a> {
588 // The path left to parse components from
591 // The prefix as it was originally parsed, if any
592 prefix: Option<Prefix<'a>>,
594 // true if path *physically* has a root separator; for most Windows
595 // prefixes, it may have a "logical" root separator for the purposes of
596 // normalization, e.g., \\server\share == \\server\share\.
597 has_physical_root: bool,
599 // The iterator is double-ended, and these two states keep track of what has
600 // been produced from either end
605 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
607 /// This `struct` is created by the [`iter`] method on [`Path`].
608 /// See its documentation for more.
610 /// [`iter`]: Path::iter
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub struct Iter<'a> {
614 inner: Components<'a>,
617 #[stable(feature = "path_components_debug", since = "1.13.0")]
618 impl fmt::Debug for Components<'_> {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 struct DebugHelper<'a>(&'a Path);
622 impl fmt::Debug for DebugHelper<'_> {
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 f.debug_list().entries(self.0.components()).finish()
628 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
632 impl<'a> Components<'a> {
633 // how long is the prefix, if any?
635 fn prefix_len(&self) -> usize {
636 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
640 fn prefix_verbatim(&self) -> bool {
641 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
644 /// how much of the prefix is left from the point of view of iteration?
646 fn prefix_remaining(&self) -> usize {
647 if self.front == State::Prefix { self.prefix_len() } else { 0 }
650 // Given the iteration so far, how much of the pre-State::Body path is left?
652 fn len_before_body(&self) -> usize {
653 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
654 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
655 self.prefix_remaining() + root + cur_dir
658 // is the iteration complete?
660 fn finished(&self) -> bool {
661 self.front == State::Done || self.back == State::Done || self.front > self.back
665 fn is_sep_byte(&self, b: u8) -> bool {
666 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
669 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
674 /// use std::path::Path;
676 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
677 /// components.next();
678 /// components.next();
680 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn as_path(&self) -> &'a Path {
685 let mut comps = self.clone();
686 if comps.front == State::Body {
689 if comps.back == State::Body {
692 unsafe { Path::from_u8_slice(comps.path) }
695 /// Is the *original* path rooted?
696 fn has_root(&self) -> bool {
697 if self.has_physical_root {
700 if let Some(p) = self.prefix {
701 if p.has_implicit_root() {
708 /// Should the normalized path include a leading . ?
709 fn include_cur_dir(&self) -> bool {
713 let mut iter = self.path[self.prefix_len()..].iter();
714 match (iter.next(), iter.next()) {
715 (Some(&b'.'), None) => true,
716 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
721 // parse a given byte sequence into the corresponding path component
722 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
724 b"." if self.prefix_verbatim() => Some(Component::CurDir),
725 b"." => None, // . components are normalized away, except at
726 // the beginning of a path, which is treated
727 // separately via `include_cur_dir`
728 b".." => Some(Component::ParentDir),
730 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
734 // parse a component from the left, saying how many bytes to consume to
735 // remove the component
736 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
737 debug_assert!(self.front == State::Body);
738 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
739 None => (0, self.path),
740 Some(i) => (1, &self.path[..i]),
742 (comp.len() + extra, self.parse_single_component(comp))
745 // parse a component from the right, saying how many bytes to consume to
746 // remove the component
747 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
748 debug_assert!(self.back == State::Body);
749 let start = self.len_before_body();
750 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
751 None => (0, &self.path[start..]),
752 Some(i) => (1, &self.path[start + i + 1..]),
754 (comp.len() + extra, self.parse_single_component(comp))
757 // trim away repeated separators (i.e., empty components) on the left
758 fn trim_left(&mut self) {
759 while !self.path.is_empty() {
760 let (size, comp) = self.parse_next_component();
764 self.path = &self.path[size..];
769 // trim away repeated separators (i.e., empty components) on the right
770 fn trim_right(&mut self) {
771 while self.path.len() > self.len_before_body() {
772 let (size, comp) = self.parse_next_component_back();
776 self.path = &self.path[..self.path.len() - size];
782 #[stable(feature = "rust1", since = "1.0.0")]
783 impl AsRef<Path> for Components<'_> {
785 fn as_ref(&self) -> &Path {
790 #[stable(feature = "rust1", since = "1.0.0")]
791 impl AsRef<OsStr> for Components<'_> {
793 fn as_ref(&self) -> &OsStr {
794 self.as_path().as_os_str()
798 #[stable(feature = "path_iter_debug", since = "1.13.0")]
799 impl fmt::Debug for Iter<'_> {
800 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801 struct DebugHelper<'a>(&'a Path);
803 impl fmt::Debug for DebugHelper<'_> {
804 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
805 f.debug_list().entries(self.0.iter()).finish()
809 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
814 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
819 /// use std::path::Path;
821 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
825 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
827 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn as_path(&self) -> &'a Path {
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl AsRef<Path> for Iter<'_> {
838 fn as_ref(&self) -> &Path {
843 #[stable(feature = "rust1", since = "1.0.0")]
844 impl AsRef<OsStr> for Iter<'_> {
846 fn as_ref(&self) -> &OsStr {
847 self.as_path().as_os_str()
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<'a> Iterator for Iter<'a> {
853 type Item = &'a OsStr;
856 fn next(&mut self) -> Option<&'a OsStr> {
857 self.inner.next().map(Component::as_os_str)
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<'a> DoubleEndedIterator for Iter<'a> {
864 fn next_back(&mut self) -> Option<&'a OsStr> {
865 self.inner.next_back().map(Component::as_os_str)
869 #[stable(feature = "fused", since = "1.26.0")]
870 impl FusedIterator for Iter<'_> {}
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a> Iterator for Components<'a> {
874 type Item = Component<'a>;
876 fn next(&mut self) -> Option<Component<'a>> {
877 while !self.finished() {
879 State::Prefix if self.prefix_len() > 0 => {
880 self.front = State::StartDir;
881 debug_assert!(self.prefix_len() <= self.path.len());
882 let raw = &self.path[..self.prefix_len()];
883 self.path = &self.path[self.prefix_len()..];
884 return Some(Component::Prefix(PrefixComponent {
885 raw: unsafe { u8_slice_as_os_str(raw) },
886 parsed: self.prefix.unwrap(),
890 self.front = State::StartDir;
893 self.front = State::Body;
894 if self.has_physical_root {
895 debug_assert!(!self.path.is_empty());
896 self.path = &self.path[1..];
897 return Some(Component::RootDir);
898 } else if let Some(p) = self.prefix {
899 if p.has_implicit_root() && !p.is_verbatim() {
900 return Some(Component::RootDir);
902 } else if self.include_cur_dir() {
903 debug_assert!(!self.path.is_empty());
904 self.path = &self.path[1..];
905 return Some(Component::CurDir);
908 State::Body if !self.path.is_empty() => {
909 let (size, comp) = self.parse_next_component();
910 self.path = &self.path[size..];
916 self.front = State::Done;
918 State::Done => unreachable!(),
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<'a> DoubleEndedIterator for Components<'a> {
927 fn next_back(&mut self) -> Option<Component<'a>> {
928 while !self.finished() {
930 State::Body if self.path.len() > self.len_before_body() => {
931 let (size, comp) = self.parse_next_component_back();
932 self.path = &self.path[..self.path.len() - size];
938 self.back = State::StartDir;
941 self.back = State::Prefix;
942 if self.has_physical_root {
943 self.path = &self.path[..self.path.len() - 1];
944 return Some(Component::RootDir);
945 } else if let Some(p) = self.prefix {
946 if p.has_implicit_root() && !p.is_verbatim() {
947 return Some(Component::RootDir);
949 } else if self.include_cur_dir() {
950 self.path = &self.path[..self.path.len() - 1];
951 return Some(Component::CurDir);
954 State::Prefix if self.prefix_len() > 0 => {
955 self.back = State::Done;
956 return Some(Component::Prefix(PrefixComponent {
957 raw: unsafe { u8_slice_as_os_str(self.path) },
958 parsed: self.prefix.unwrap(),
962 self.back = State::Done;
965 State::Done => unreachable!(),
972 #[stable(feature = "fused", since = "1.26.0")]
973 impl FusedIterator for Components<'_> {}
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<'a> cmp::PartialEq for Components<'a> {
978 fn eq(&self, other: &Components<'a>) -> bool {
979 Iterator::eq(self.clone().rev(), other.clone().rev())
983 #[stable(feature = "rust1", since = "1.0.0")]
984 impl cmp::Eq for Components<'_> {}
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<'a> cmp::PartialOrd for Components<'a> {
989 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
990 Some(compare_components(self.clone(), other.clone()))
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl cmp::Ord for Components<'_> {
997 fn cmp(&self, other: &Self) -> cmp::Ordering {
998 compare_components(self.clone(), other.clone())
1002 fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cmp::Ordering {
1003 // Fast path for long shared prefixes
1005 // - compare raw bytes to find first mismatch
1006 // - backtrack to find separator before mismatch to avoid ambiguous parsings of '.' or '..' characters
1007 // - if found update state to only do a component-wise comparison on the remainder,
1008 // otherwise do it on the full path
1010 // The fast path isn't taken for paths with a PrefixComponent to avoid backtracking into
1011 // the middle of one
1012 if left.prefix.is_none() && right.prefix.is_none() && left.front == right.front {
1013 // this might benefit from a [u8]::first_mismatch simd implementation, if it existed
1014 let first_difference =
1015 match left.path.iter().zip(right.path.iter()).position(|(&a, &b)| a != b) {
1016 None if left.path.len() == right.path.len() => return cmp::Ordering::Equal,
1017 None => left.path.len().min(right.path.len()),
1021 if let Some(previous_sep) =
1022 left.path[..first_difference].iter().rposition(|&b| left.is_sep_byte(b))
1024 let mismatched_component_start = previous_sep + 1;
1025 left.path = &left.path[mismatched_component_start..];
1026 left.front = State::Body;
1027 right.path = &right.path[mismatched_component_start..];
1028 right.front = State::Body;
1032 Iterator::cmp(left, right)
1035 /// An iterator over [`Path`] and its ancestors.
1037 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1038 /// See its documentation for more.
1043 /// use std::path::Path;
1045 /// let path = Path::new("/foo/bar");
1047 /// for ancestor in path.ancestors() {
1048 /// println!("{}", ancestor.display());
1052 /// [`ancestors`]: Path::ancestors
1053 #[derive(Copy, Clone, Debug)]
1054 #[stable(feature = "path_ancestors", since = "1.28.0")]
1055 pub struct Ancestors<'a> {
1056 next: Option<&'a Path>,
1059 #[stable(feature = "path_ancestors", since = "1.28.0")]
1060 impl<'a> Iterator for Ancestors<'a> {
1061 type Item = &'a Path;
1064 fn next(&mut self) -> Option<Self::Item> {
1065 let next = self.next;
1066 self.next = next.and_then(Path::parent);
1071 #[stable(feature = "path_ancestors", since = "1.28.0")]
1072 impl FusedIterator for Ancestors<'_> {}
1074 ////////////////////////////////////////////////////////////////////////////////
1075 // Basic types and traits
1076 ////////////////////////////////////////////////////////////////////////////////
1078 /// An owned, mutable path (akin to [`String`]).
1080 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1081 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1082 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1084 /// [`push`]: PathBuf::push
1085 /// [`set_extension`]: PathBuf::set_extension
1087 /// More details about the overall approach can be found in
1088 /// the [module documentation](self).
1092 /// You can use [`push`] to build up a `PathBuf` from
1096 /// use std::path::PathBuf;
1098 /// let mut path = PathBuf::new();
1100 /// path.push(r"C:\");
1101 /// path.push("windows");
1102 /// path.push("system32");
1104 /// path.set_extension("dll");
1107 /// However, [`push`] is best used for dynamic situations. This is a better way
1108 /// to do this when you know all of the components ahead of time:
1111 /// use std::path::PathBuf;
1113 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1116 /// We can still do better than this! Since these are all strings, we can use
1120 /// use std::path::PathBuf;
1122 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1125 /// Which method works best depends on what kind of situation you're in.
1126 #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1127 #[stable(feature = "rust1", since = "1.0.0")]
1129 // `PathBuf::as_mut_vec` current implementation relies
1130 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1131 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1132 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1133 // not documented and must not be relied upon.
1134 pub struct PathBuf {
1140 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1141 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1144 /// Allocates an empty `PathBuf`.
1149 /// use std::path::PathBuf;
1151 /// let path = PathBuf::new();
1153 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn new() -> PathBuf {
1157 PathBuf { inner: OsString::new() }
1160 /// Creates a new `PathBuf` with a given capacity used to create the
1161 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1166 /// use std::path::PathBuf;
1168 /// let mut path = PathBuf::with_capacity(10);
1169 /// let capacity = path.capacity();
1171 /// // This push is done without reallocating
1172 /// path.push(r"C:\");
1174 /// assert_eq!(capacity, path.capacity());
1177 /// [`with_capacity`]: OsString::with_capacity
1178 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1181 pub fn with_capacity(capacity: usize) -> PathBuf {
1182 PathBuf { inner: OsString::with_capacity(capacity) }
1185 /// Coerces to a [`Path`] slice.
1190 /// use std::path::{Path, PathBuf};
1192 /// let p = PathBuf::from("/test");
1193 /// assert_eq!(Path::new("/test"), p.as_path());
1195 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn as_path(&self) -> &Path {
1202 /// Extends `self` with `path`.
1204 /// If `path` is absolute, it replaces the current path.
1208 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1209 /// replaces everything except for the prefix (if any) of `self`.
1210 /// * if `path` has a prefix but no root, it replaces `self`.
1214 /// Pushing a relative path extends the existing path:
1217 /// use std::path::PathBuf;
1219 /// let mut path = PathBuf::from("/tmp");
1220 /// path.push("file.bk");
1221 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1224 /// Pushing an absolute path replaces the existing path:
1227 /// use std::path::PathBuf;
1229 /// let mut path = PathBuf::from("/tmp");
1230 /// path.push("/etc");
1231 /// assert_eq!(path, PathBuf::from("/etc"));
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1235 self._push(path.as_ref())
1238 fn _push(&mut self, path: &Path) {
1239 // in general, a separator is needed if the rightmost byte is not a separator
1240 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1242 // in the special case of `C:` on Windows, do *not* add a separator
1243 let comps = self.components();
1245 if comps.prefix_len() > 0
1246 && comps.prefix_len() == comps.path.len()
1247 && comps.prefix.unwrap().is_drive()
1252 // absolute `path` replaces `self`
1253 if path.is_absolute() || path.prefix().is_some() {
1254 self.as_mut_vec().truncate(0);
1256 // verbatim paths need . and .. removed
1257 } else if comps.prefix_verbatim() {
1258 let mut buf: Vec<_> = comps.collect();
1259 for c in path.components() {
1261 Component::RootDir => {
1265 Component::CurDir => (),
1266 Component::ParentDir => {
1267 if let Some(Component::Normal(_)) = buf.last() {
1275 let mut res = OsString::new();
1276 let mut need_sep = false;
1279 if need_sep && c != Component::RootDir {
1280 res.push(MAIN_SEP_STR);
1282 res.push(c.as_os_str());
1284 need_sep = match c {
1285 Component::RootDir => false,
1286 Component::Prefix(prefix) => {
1287 !prefix.parsed.is_drive() && prefix.parsed.len() > 0
1296 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1297 } else if path.has_root() {
1298 let prefix_len = self.components().prefix_remaining();
1299 self.as_mut_vec().truncate(prefix_len);
1301 // `path` is a pure relative path
1302 } else if need_sep {
1303 self.inner.push(MAIN_SEP_STR);
1306 self.inner.push(path);
1309 /// Truncates `self` to [`self.parent`].
1311 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1312 /// Otherwise, returns `true`.
1314 /// [`self.parent`]: Path::parent
1319 /// use std::path::{Path, PathBuf};
1321 /// let mut p = PathBuf::from("/spirited/away.rs");
1324 /// assert_eq!(Path::new("/spirited"), p);
1326 /// assert_eq!(Path::new("/"), p);
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 pub fn pop(&mut self) -> bool {
1330 match self.parent().map(|p| p.as_u8_slice().len()) {
1332 self.as_mut_vec().truncate(len);
1339 /// Updates [`self.file_name`] to `file_name`.
1341 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1344 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1345 /// `file_name`. The new path will be a sibling of the original path.
1346 /// (That is, it will have the same parent.)
1348 /// [`self.file_name`]: Path::file_name
1349 /// [`pop`]: PathBuf::pop
1354 /// use std::path::PathBuf;
1356 /// let mut buf = PathBuf::from("/");
1357 /// assert!(buf.file_name() == None);
1358 /// buf.set_file_name("bar");
1359 /// assert!(buf == PathBuf::from("/bar"));
1360 /// assert!(buf.file_name().is_some());
1361 /// buf.set_file_name("baz.txt");
1362 /// assert!(buf == PathBuf::from("/baz.txt"));
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1366 self._set_file_name(file_name.as_ref())
1369 fn _set_file_name(&mut self, file_name: &OsStr) {
1370 if self.file_name().is_some() {
1371 let popped = self.pop();
1372 debug_assert!(popped);
1374 self.push(file_name);
1377 /// Updates [`self.extension`] to `extension`.
1379 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1380 /// returns `true` and updates the extension otherwise.
1382 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1385 /// [`self.file_name`]: Path::file_name
1386 /// [`self.extension`]: Path::extension
1391 /// use std::path::{Path, PathBuf};
1393 /// let mut p = PathBuf::from("/feel/the");
1395 /// p.set_extension("force");
1396 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1398 /// p.set_extension("dark_side");
1399 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1403 self._set_extension(extension.as_ref())
1406 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1407 let file_stem = match self.file_stem() {
1408 None => return false,
1409 Some(f) => os_str_as_u8_slice(f),
1412 // truncate until right after the file stem
1413 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1414 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1415 let v = self.as_mut_vec();
1416 v.truncate(end_file_stem.wrapping_sub(start));
1418 // add the new extension, if any
1419 let new = os_str_as_u8_slice(extension);
1420 if !new.is_empty() {
1421 v.reserve_exact(new.len() + 1);
1423 v.extend_from_slice(new);
1429 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1434 /// use std::path::PathBuf;
1436 /// let p = PathBuf::from("/the/head");
1437 /// let os_str = p.into_os_string();
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 #[must_use = "`self` will be dropped if the result is not used"]
1442 pub fn into_os_string(self) -> OsString {
1446 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1447 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1448 #[must_use = "`self` will be dropped if the result is not used"]
1450 pub fn into_boxed_path(self) -> Box<Path> {
1451 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1452 unsafe { Box::from_raw(rw) }
1455 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1457 /// [`capacity`]: OsString::capacity
1458 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1460 pub fn capacity(&self) -> usize {
1461 self.inner.capacity()
1464 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1466 /// [`clear`]: OsString::clear
1467 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1469 pub fn clear(&mut self) {
1473 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1475 /// [`reserve`]: OsString::reserve
1476 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1478 pub fn reserve(&mut self, additional: usize) {
1479 self.inner.reserve(additional)
1482 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1484 /// [`reserve_exact`]: OsString::reserve_exact
1485 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1487 pub fn reserve_exact(&mut self, additional: usize) {
1488 self.inner.reserve_exact(additional)
1491 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1493 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1494 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1496 pub fn shrink_to_fit(&mut self) {
1497 self.inner.shrink_to_fit()
1500 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1502 /// [`shrink_to`]: OsString::shrink_to
1503 #[stable(feature = "shrink_to", since = "1.56.0")]
1505 pub fn shrink_to(&mut self, min_capacity: usize) {
1506 self.inner.shrink_to(min_capacity)
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 impl Clone for PathBuf {
1513 fn clone(&self) -> Self {
1514 PathBuf { inner: self.inner.clone() }
1518 fn clone_from(&mut self, source: &Self) {
1519 self.inner.clone_from(&source.inner)
1523 #[stable(feature = "box_from_path", since = "1.17.0")]
1524 impl From<&Path> for Box<Path> {
1525 /// Creates a boxed [`Path`] from a reference.
1527 /// This will allocate and clone `path` to it.
1528 fn from(path: &Path) -> Box<Path> {
1529 let boxed: Box<OsStr> = path.inner.into();
1530 let rw = Box::into_raw(boxed) as *mut Path;
1531 unsafe { Box::from_raw(rw) }
1535 #[stable(feature = "box_from_cow", since = "1.45.0")]
1536 impl From<Cow<'_, Path>> for Box<Path> {
1537 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1539 /// Converting from a `Cow::Owned` does not clone or allocate.
1541 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1543 Cow::Borrowed(path) => Box::from(path),
1544 Cow::Owned(path) => Box::from(path),
1549 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1550 impl From<Box<Path>> for PathBuf {
1551 /// Converts a `Box<Path>` into a `PathBuf`
1553 /// This conversion does not allocate or copy memory.
1555 fn from(boxed: Box<Path>) -> PathBuf {
1556 boxed.into_path_buf()
1560 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1561 impl From<PathBuf> for Box<Path> {
1562 /// Converts a `PathBuf` into a `Box<Path>`
1564 /// This conversion currently should not allocate memory,
1565 /// but this behavior is not guaranteed on all platforms or in all future versions.
1567 fn from(p: PathBuf) -> Box<Path> {
1572 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1573 impl Clone for Box<Path> {
1575 fn clone(&self) -> Self {
1576 self.to_path_buf().into_boxed_path()
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1582 /// Converts a borrowed `OsStr` to a `PathBuf`.
1584 /// Allocates a [`PathBuf`] and copies the data into it.
1586 fn from(s: &T) -> PathBuf {
1587 PathBuf::from(s.as_ref().to_os_string())
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl From<OsString> for PathBuf {
1593 /// Converts an [`OsString`] into a [`PathBuf`]
1595 /// This conversion does not allocate or copy memory.
1597 fn from(s: OsString) -> PathBuf {
1598 PathBuf { inner: s }
1602 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1603 impl From<PathBuf> for OsString {
1604 /// Converts a [`PathBuf`] into an [`OsString`]
1606 /// This conversion does not allocate or copy memory.
1608 fn from(path_buf: PathBuf) -> OsString {
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl From<String> for PathBuf {
1615 /// Converts a [`String`] into a [`PathBuf`]
1617 /// This conversion does not allocate or copy memory.
1619 fn from(s: String) -> PathBuf {
1620 PathBuf::from(OsString::from(s))
1624 #[stable(feature = "path_from_str", since = "1.32.0")]
1625 impl FromStr for PathBuf {
1626 type Err = core::convert::Infallible;
1629 fn from_str(s: &str) -> Result<Self, Self::Err> {
1630 Ok(PathBuf::from(s))
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1636 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1637 let mut buf = PathBuf::new();
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1645 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1646 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1650 fn extend_one(&mut self, p: P) {
1651 self.push(p.as_ref());
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl fmt::Debug for PathBuf {
1657 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1658 fmt::Debug::fmt(&**self, formatter)
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl ops::Deref for PathBuf {
1666 fn deref(&self) -> &Path {
1667 Path::new(&self.inner)
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl Borrow<Path> for PathBuf {
1674 fn borrow(&self) -> &Path {
1679 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1680 impl Default for PathBuf {
1682 fn default() -> Self {
1687 #[stable(feature = "cow_from_path", since = "1.6.0")]
1688 impl<'a> From<&'a Path> for Cow<'a, Path> {
1689 /// Creates a clone-on-write pointer from a reference to
1692 /// This conversion does not clone or allocate.
1694 fn from(s: &'a Path) -> Cow<'a, Path> {
1699 #[stable(feature = "cow_from_path", since = "1.6.0")]
1700 impl<'a> From<PathBuf> for Cow<'a, Path> {
1701 /// Creates a clone-on-write pointer from an owned
1702 /// instance of [`PathBuf`].
1704 /// This conversion does not clone or allocate.
1706 fn from(s: PathBuf) -> Cow<'a, Path> {
1711 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1712 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1713 /// Creates a clone-on-write pointer from a reference to
1716 /// This conversion does not clone or allocate.
1718 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1719 Cow::Borrowed(p.as_path())
1723 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1724 impl<'a> From<Cow<'a, Path>> for PathBuf {
1725 /// Converts a clone-on-write pointer to an owned path.
1727 /// Converting from a `Cow::Owned` does not clone or allocate.
1729 fn from(p: Cow<'a, Path>) -> Self {
1734 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1735 impl From<PathBuf> for Arc<Path> {
1736 /// Converts a [`PathBuf`] into an [`Arc`] by moving the [`PathBuf`] data into a new [`Arc`] buffer.
1738 fn from(s: PathBuf) -> Arc<Path> {
1739 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1740 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1744 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1745 impl From<&Path> for Arc<Path> {
1746 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
1748 fn from(s: &Path) -> Arc<Path> {
1749 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1750 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1754 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1755 impl From<PathBuf> for Rc<Path> {
1756 /// Converts a [`PathBuf`] into an [`Rc`] by moving the [`PathBuf`] data into a new `Rc` buffer.
1758 fn from(s: PathBuf) -> Rc<Path> {
1759 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1760 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1764 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1765 impl From<&Path> for Rc<Path> {
1766 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new `Rc` buffer.
1768 fn from(s: &Path) -> Rc<Path> {
1769 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1770 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 impl ToOwned for Path {
1776 type Owned = PathBuf;
1778 fn to_owned(&self) -> PathBuf {
1782 fn clone_into(&self, target: &mut PathBuf) {
1783 self.inner.clone_into(&mut target.inner);
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 impl cmp::PartialEq for PathBuf {
1790 fn eq(&self, other: &PathBuf) -> bool {
1791 self.components() == other.components()
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl Hash for PathBuf {
1797 fn hash<H: Hasher>(&self, h: &mut H) {
1798 self.as_path().hash(h)
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl cmp::Eq for PathBuf {}
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 impl cmp::PartialOrd for PathBuf {
1808 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1809 Some(compare_components(self.components(), other.components()))
1813 #[stable(feature = "rust1", since = "1.0.0")]
1814 impl cmp::Ord for PathBuf {
1816 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1817 compare_components(self.components(), other.components())
1821 #[stable(feature = "rust1", since = "1.0.0")]
1822 impl AsRef<OsStr> for PathBuf {
1824 fn as_ref(&self) -> &OsStr {
1829 /// A slice of a path (akin to [`str`]).
1831 /// This type supports a number of operations for inspecting a path, including
1832 /// breaking the path into its components (separated by `/` on Unix and by either
1833 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1834 /// is absolute, and so on.
1836 /// This is an *unsized* type, meaning that it must always be used behind a
1837 /// pointer like `&` or [`Box`]. For an owned version of this type,
1838 /// see [`PathBuf`].
1840 /// More details about the overall approach can be found in
1841 /// the [module documentation](self).
1846 /// use std::path::Path;
1847 /// use std::ffi::OsStr;
1849 /// // Note: this example does work on Windows
1850 /// let path = Path::new("./foo/bar.txt");
1852 /// let parent = path.parent();
1853 /// assert_eq!(parent, Some(Path::new("./foo")));
1855 /// let file_stem = path.file_stem();
1856 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1858 /// let extension = path.extension();
1859 /// assert_eq!(extension, Some(OsStr::new("txt")));
1861 #[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
1862 #[stable(feature = "rust1", since = "1.0.0")]
1864 // `Path::new` current implementation relies
1865 // on `Path` being layout-compatible with `OsStr`.
1866 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1867 // Anyway, `Path` representation and layout are considered implementation detail, are
1868 // not documented and must not be relied upon.
1873 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1875 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1876 /// See its documentation for more.
1878 /// [`strip_prefix`]: Path::strip_prefix
1879 #[derive(Debug, Clone, PartialEq, Eq)]
1880 #[stable(since = "1.7.0", feature = "strip_prefix")]
1881 pub struct StripPrefixError(());
1884 // The following (private!) function allows construction of a path from a u8
1885 // slice, which is only safe when it is known to follow the OsStr encoding.
1886 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1887 unsafe { Path::new(u8_slice_as_os_str(s)) }
1889 // The following (private!) function reveals the byte encoding used for OsStr.
1890 fn as_u8_slice(&self) -> &[u8] {
1891 os_str_as_u8_slice(&self.inner)
1894 /// Directly wraps a string slice as a `Path` slice.
1896 /// This is a cost-free conversion.
1901 /// use std::path::Path;
1903 /// Path::new("foo.txt");
1906 /// You can create `Path`s from `String`s, or even other `Path`s:
1909 /// use std::path::Path;
1911 /// let string = String::from("foo.txt");
1912 /// let from_string = Path::new(&string);
1913 /// let from_path = Path::new(&from_string);
1914 /// assert_eq!(from_string, from_path);
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1918 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1921 /// Yields the underlying [`OsStr`] slice.
1926 /// use std::path::Path;
1928 /// let os_str = Path::new("foo.txt").as_os_str();
1929 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1931 #[stable(feature = "rust1", since = "1.0.0")]
1934 pub fn as_os_str(&self) -> &OsStr {
1938 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1940 /// This conversion may entail doing a check for UTF-8 validity.
1941 /// Note that validation is performed because non-UTF-8 strings are
1942 /// perfectly valid for some OS.
1949 /// use std::path::Path;
1951 /// let path = Path::new("foo.txt");
1952 /// assert_eq!(path.to_str(), Some("foo.txt"));
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 #[must_use = "this returns the result of the operation, \
1956 without modifying the original"]
1958 pub fn to_str(&self) -> Option<&str> {
1962 /// Converts a `Path` to a [`Cow<str>`].
1964 /// Any non-Unicode sequences are replaced with
1965 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1967 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1971 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1974 /// use std::path::Path;
1976 /// let path = Path::new("foo.txt");
1977 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1980 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1981 /// have returned `"fo�.txt"`.
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 #[must_use = "this returns the result of the operation, \
1984 without modifying the original"]
1986 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1987 self.inner.to_string_lossy()
1990 /// Converts a `Path` to an owned [`PathBuf`].
1995 /// use std::path::Path;
1997 /// let path_buf = Path::new("foo.txt").to_path_buf();
1998 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
2000 #[rustc_conversion_suggestion]
2001 #[must_use = "this returns the result of the operation, \
2002 without modifying the original"]
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 pub fn to_path_buf(&self) -> PathBuf {
2005 PathBuf::from(self.inner.to_os_string())
2008 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
2009 /// the current directory.
2011 /// * On Unix, a path is absolute if it starts with the root, so
2012 /// `is_absolute` and [`has_root`] are equivalent.
2014 /// * On Windows, a path is absolute if it has a prefix and starts with the
2015 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
2020 /// use std::path::Path;
2022 /// assert!(!Path::new("foo.txt").is_absolute());
2025 /// [`has_root`]: Path::has_root
2026 #[stable(feature = "rust1", since = "1.0.0")]
2028 #[allow(deprecated)]
2029 pub fn is_absolute(&self) -> bool {
2030 if cfg!(target_os = "redox") {
2031 // FIXME: Allow Redox prefixes
2032 self.has_root() || has_redox_scheme(self.as_u8_slice())
2034 self.has_root() && (cfg!(any(unix, target_os = "wasi")) || self.prefix().is_some())
2038 /// Returns `true` if the `Path` is relative, i.e., not absolute.
2040 /// See [`is_absolute`]'s documentation for more details.
2045 /// use std::path::Path;
2047 /// assert!(Path::new("foo.txt").is_relative());
2050 /// [`is_absolute`]: Path::is_absolute
2051 #[stable(feature = "rust1", since = "1.0.0")]
2054 pub fn is_relative(&self) -> bool {
2058 fn prefix(&self) -> Option<Prefix<'_>> {
2059 self.components().prefix
2062 /// Returns `true` if the `Path` has a root.
2064 /// * On Unix, a path has a root if it begins with `/`.
2066 /// * On Windows, a path has a root if it:
2067 /// * has no prefix and begins with a separator, e.g., `\windows`
2068 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
2069 /// * has any non-disk prefix, e.g., `\\server\share`
2074 /// use std::path::Path;
2076 /// assert!(Path::new("/etc/passwd").has_root());
2078 #[stable(feature = "rust1", since = "1.0.0")]
2081 pub fn has_root(&self) -> bool {
2082 self.components().has_root()
2085 /// Returns the `Path` without its final component, if there is one.
2087 /// Returns [`None`] if the path terminates in a root or prefix.
2092 /// use std::path::Path;
2094 /// let path = Path::new("/foo/bar");
2095 /// let parent = path.parent().unwrap();
2096 /// assert_eq!(parent, Path::new("/foo"));
2098 /// let grand_parent = parent.parent().unwrap();
2099 /// assert_eq!(grand_parent, Path::new("/"));
2100 /// assert_eq!(grand_parent.parent(), None);
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 pub fn parent(&self) -> Option<&Path> {
2104 let mut comps = self.components();
2105 let comp = comps.next_back();
2106 comp.and_then(|p| match p {
2107 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
2108 Some(comps.as_path())
2114 /// Produces an iterator over `Path` and its ancestors.
2116 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2117 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2118 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2119 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2125 /// use std::path::Path;
2127 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2128 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2129 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2130 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2131 /// assert_eq!(ancestors.next(), None);
2133 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2134 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2135 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2136 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2137 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2138 /// assert_eq!(ancestors.next(), None);
2141 /// [`parent`]: Path::parent
2142 #[stable(feature = "path_ancestors", since = "1.28.0")]
2144 pub fn ancestors(&self) -> Ancestors<'_> {
2145 Ancestors { next: Some(&self) }
2148 /// Returns the final component of the `Path`, if there is one.
2150 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2151 /// is the directory name.
2153 /// Returns [`None`] if the path terminates in `..`.
2158 /// use std::path::Path;
2159 /// use std::ffi::OsStr;
2161 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2162 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2163 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2164 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2165 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2166 /// assert_eq!(None, Path::new("/").file_name());
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 pub fn file_name(&self) -> Option<&OsStr> {
2170 self.components().next_back().and_then(|p| match p {
2171 Component::Normal(p) => Some(p),
2176 /// Returns a path that, when joined onto `base`, yields `self`.
2180 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2181 /// returns `false`), returns [`Err`].
2183 /// [`starts_with`]: Path::starts_with
2188 /// use std::path::{Path, PathBuf};
2190 /// let path = Path::new("/test/haha/foo.txt");
2192 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2193 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2194 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2195 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2196 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2198 /// assert!(path.strip_prefix("test").is_err());
2199 /// assert!(path.strip_prefix("/haha").is_err());
2201 /// let prefix = PathBuf::from("/test/");
2202 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2204 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2205 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2209 self._strip_prefix(base.as_ref())
2212 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2213 iter_after(self.components(), base.components())
2214 .map(|c| c.as_path())
2215 .ok_or(StripPrefixError(()))
2218 /// Determines whether `base` is a prefix of `self`.
2220 /// Only considers whole path components to match.
2225 /// use std::path::Path;
2227 /// let path = Path::new("/etc/passwd");
2229 /// assert!(path.starts_with("/etc"));
2230 /// assert!(path.starts_with("/etc/"));
2231 /// assert!(path.starts_with("/etc/passwd"));
2232 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2233 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2235 /// assert!(!path.starts_with("/e"));
2236 /// assert!(!path.starts_with("/etc/passwd.txt"));
2238 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2242 self._starts_with(base.as_ref())
2245 fn _starts_with(&self, base: &Path) -> bool {
2246 iter_after(self.components(), base.components()).is_some()
2249 /// Determines whether `child` is a suffix of `self`.
2251 /// Only considers whole path components to match.
2256 /// use std::path::Path;
2258 /// let path = Path::new("/etc/resolv.conf");
2260 /// assert!(path.ends_with("resolv.conf"));
2261 /// assert!(path.ends_with("etc/resolv.conf"));
2262 /// assert!(path.ends_with("/etc/resolv.conf"));
2264 /// assert!(!path.ends_with("/resolv.conf"));
2265 /// assert!(!path.ends_with("conf")); // use .extension() instead
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2269 self._ends_with(child.as_ref())
2272 fn _ends_with(&self, child: &Path) -> bool {
2273 iter_after(self.components().rev(), child.components().rev()).is_some()
2276 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2278 /// [`self.file_name`]: Path::file_name
2282 /// * [`None`], if there is no file name;
2283 /// * The entire file name if there is no embedded `.`;
2284 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2285 /// * Otherwise, the portion of the file name before the final `.`
2290 /// use std::path::Path;
2292 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2293 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2297 /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
2298 /// before the *first* `.`
2300 /// [`Path::file_prefix`]: Path::file_prefix
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 pub fn file_stem(&self) -> Option<&OsStr> {
2304 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2307 /// Extracts the prefix of [`self.file_name`].
2311 /// * [`None`], if there is no file name;
2312 /// * The entire file name if there is no embedded `.`;
2313 /// * The portion of the file name before the first non-beginning `.`;
2314 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2315 /// * The portion of the file name before the second `.` if the file name begins with `.`
2317 /// [`self.file_name`]: Path::file_name
2322 /// # #![feature(path_file_prefix)]
2323 /// use std::path::Path;
2325 /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
2326 /// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
2330 /// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
2331 /// before the *last* `.`
2333 /// [`Path::file_stem`]: Path::file_stem
2335 #[unstable(feature = "path_file_prefix", issue = "86319")]
2336 pub fn file_prefix(&self) -> Option<&OsStr> {
2337 self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before))
2340 /// Extracts the extension of [`self.file_name`], if possible.
2342 /// The extension is:
2344 /// * [`None`], if there is no file name;
2345 /// * [`None`], if there is no embedded `.`;
2346 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2347 /// * Otherwise, the portion of the file name after the final `.`
2349 /// [`self.file_name`]: Path::file_name
2354 /// use std::path::Path;
2356 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2357 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 pub fn extension(&self) -> Option<&OsStr> {
2361 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
2364 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2366 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2371 /// use std::path::{Path, PathBuf};
2373 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2375 #[stable(feature = "rust1", since = "1.0.0")]
2377 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2378 self._join(path.as_ref())
2381 fn _join(&self, path: &Path) -> PathBuf {
2382 let mut buf = self.to_path_buf();
2387 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2389 /// See [`PathBuf::set_file_name`] for more details.
2394 /// use std::path::{Path, PathBuf};
2396 /// let path = Path::new("/tmp/foo.txt");
2397 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2399 /// let path = Path::new("/tmp");
2400 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2402 #[stable(feature = "rust1", since = "1.0.0")]
2403 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2404 self._with_file_name(file_name.as_ref())
2407 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2408 let mut buf = self.to_path_buf();
2409 buf.set_file_name(file_name);
2413 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2415 /// See [`PathBuf::set_extension`] for more details.
2420 /// use std::path::{Path, PathBuf};
2422 /// let path = Path::new("foo.rs");
2423 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2425 /// let path = Path::new("foo.tar.gz");
2426 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2427 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2428 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2430 #[stable(feature = "rust1", since = "1.0.0")]
2431 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2432 self._with_extension(extension.as_ref())
2435 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2436 let mut buf = self.to_path_buf();
2437 buf.set_extension(extension);
2441 /// Produces an iterator over the [`Component`]s of the path.
2443 /// When parsing the path, there is a small amount of normalization:
2445 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2446 /// `a` and `b` as components.
2448 /// * Occurrences of `.` are normalized away, except if they are at the
2449 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2450 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2451 /// an additional [`CurDir`] component.
2453 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2455 /// Note that no other normalization takes place; in particular, `a/c`
2456 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2457 /// is a symbolic link (so its parent isn't `a`).
2462 /// use std::path::{Path, Component};
2463 /// use std::ffi::OsStr;
2465 /// let mut components = Path::new("/tmp/foo.txt").components();
2467 /// assert_eq!(components.next(), Some(Component::RootDir));
2468 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2469 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2470 /// assert_eq!(components.next(), None)
2473 /// [`CurDir`]: Component::CurDir
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 pub fn components(&self) -> Components<'_> {
2476 let prefix = parse_prefix(self.as_os_str());
2478 path: self.as_u8_slice(),
2480 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2481 || has_redox_scheme(self.as_u8_slice()),
2482 front: State::Prefix,
2487 /// Produces an iterator over the path's components viewed as [`OsStr`]
2490 /// For more information about the particulars of how the path is separated
2491 /// into components, see [`components`].
2493 /// [`components`]: Path::components
2498 /// use std::path::{self, Path};
2499 /// use std::ffi::OsStr;
2501 /// let mut it = Path::new("/tmp/foo.txt").iter();
2502 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2503 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2504 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2505 /// assert_eq!(it.next(), None)
2507 #[stable(feature = "rust1", since = "1.0.0")]
2509 pub fn iter(&self) -> Iter<'_> {
2510 Iter { inner: self.components() }
2513 /// Returns an object that implements [`Display`] for safely printing paths
2514 /// that may contain non-Unicode data. This may perform lossy conversion,
2515 /// depending on the platform. If you would like an implementation which
2516 /// escapes the path please use [`Debug`] instead.
2518 /// [`Display`]: fmt::Display
2523 /// use std::path::Path;
2525 /// let path = Path::new("/tmp/foo.rs");
2527 /// println!("{}", path.display());
2529 #[stable(feature = "rust1", since = "1.0.0")]
2530 #[must_use = "this does not display the path, \
2531 it returns an object that can be displayed"]
2533 pub fn display(&self) -> Display<'_> {
2534 Display { path: self }
2537 /// Queries the file system to get information about a file, directory, etc.
2539 /// This function will traverse symbolic links to query information about the
2540 /// destination file.
2542 /// This is an alias to [`fs::metadata`].
2547 /// use std::path::Path;
2549 /// let path = Path::new("/Minas/tirith");
2550 /// let metadata = path.metadata().expect("metadata call failed");
2551 /// println!("{:?}", metadata.file_type());
2553 #[stable(feature = "path_ext", since = "1.5.0")]
2555 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2559 /// Queries the metadata about a file without following symlinks.
2561 /// This is an alias to [`fs::symlink_metadata`].
2566 /// use std::path::Path;
2568 /// let path = Path::new("/Minas/tirith");
2569 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2570 /// println!("{:?}", metadata.file_type());
2572 #[stable(feature = "path_ext", since = "1.5.0")]
2574 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2575 fs::symlink_metadata(self)
2578 /// Returns the canonical, absolute form of the path with all intermediate
2579 /// components normalized and symbolic links resolved.
2581 /// This is an alias to [`fs::canonicalize`].
2586 /// use std::path::{Path, PathBuf};
2588 /// let path = Path::new("/foo/test/../test/bar.rs");
2589 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2591 #[stable(feature = "path_ext", since = "1.5.0")]
2593 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2594 fs::canonicalize(self)
2597 /// Reads a symbolic link, returning the file that the link points to.
2599 /// This is an alias to [`fs::read_link`].
2604 /// use std::path::Path;
2606 /// let path = Path::new("/laputa/sky_castle.rs");
2607 /// let path_link = path.read_link().expect("read_link call failed");
2609 #[stable(feature = "path_ext", since = "1.5.0")]
2611 pub fn read_link(&self) -> io::Result<PathBuf> {
2615 /// Returns an iterator over the entries within a directory.
2617 /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. New
2618 /// errors may be encountered after an iterator is initially constructed.
2620 /// This is an alias to [`fs::read_dir`].
2625 /// use std::path::Path;
2627 /// let path = Path::new("/laputa");
2628 /// for entry in path.read_dir().expect("read_dir call failed") {
2629 /// if let Ok(entry) = entry {
2630 /// println!("{:?}", entry.path());
2634 #[stable(feature = "path_ext", since = "1.5.0")]
2636 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2640 /// Returns `true` if the path points at an existing entity.
2642 /// This function will traverse symbolic links to query information about the
2643 /// destination file.
2645 /// If you cannot access the metadata of the file, e.g. because of a
2646 /// permission error or broken symbolic links, this will return `false`.
2651 /// use std::path::Path;
2652 /// assert!(!Path::new("does_not_exist.txt").exists());
2657 /// This is a convenience function that coerces errors to false. If you want to
2658 /// check errors, call [`fs::metadata`].
2659 #[stable(feature = "path_ext", since = "1.5.0")]
2661 pub fn exists(&self) -> bool {
2662 fs::metadata(self).is_ok()
2665 /// Returns `Ok(true)` if the path points at an existing entity.
2667 /// This function will traverse symbolic links to query information about the
2668 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2670 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2671 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2672 /// denied on some of the parent directories.)
2677 /// #![feature(path_try_exists)]
2679 /// use std::path::Path;
2680 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2681 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2683 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2685 #[unstable(feature = "path_try_exists", issue = "83186")]
2687 pub fn try_exists(&self) -> io::Result<bool> {
2688 fs::try_exists(self)
2691 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2693 /// This function will traverse symbolic links to query information about the
2694 /// destination file.
2696 /// If you cannot access the metadata of the file, e.g. because of a
2697 /// permission error or broken symbolic links, this will return `false`.
2702 /// use std::path::Path;
2703 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2704 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2709 /// This is a convenience function that coerces errors to false. If you want to
2710 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2711 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2713 /// When the goal is simply to read from (or write to) the source, the most
2714 /// reliable way to test the source can be read (or written to) is to open
2715 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2716 /// a Unix-like system for example. See [`fs::File::open`] or
2717 /// [`fs::OpenOptions::open`] for more information.
2718 #[stable(feature = "path_ext", since = "1.5.0")]
2720 pub fn is_file(&self) -> bool {
2721 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2724 /// Returns `true` if the path exists on disk and is pointing at a directory.
2726 /// This function will traverse symbolic links to query information about the
2727 /// destination file.
2729 /// If you cannot access the metadata of the file, e.g. because of a
2730 /// permission error or broken symbolic links, this will return `false`.
2735 /// use std::path::Path;
2736 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2737 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2742 /// This is a convenience function that coerces errors to false. If you want to
2743 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2744 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2745 #[stable(feature = "path_ext", since = "1.5.0")]
2747 pub fn is_dir(&self) -> bool {
2748 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2751 /// Returns true if the path exists on disk and is pointing at a symbolic link.
2753 /// This function will not traverse symbolic links.
2754 /// In case of a broken symbolic link this will also return true.
2756 /// If you cannot access the directory containing the file, e.g., because of a
2757 /// permission error, this will return false.
2761 #[cfg_attr(unix, doc = "```no_run")]
2762 #[cfg_attr(not(unix), doc = "```ignore")]
2763 /// #![feature(is_symlink)]
2764 /// use std::path::Path;
2765 /// use std::os::unix::fs::symlink;
2767 /// let link_path = Path::new("link");
2768 /// symlink("/origin_does_not_exists/", link_path).unwrap();
2769 /// assert_eq!(link_path.is_symlink(), true);
2770 /// assert_eq!(link_path.exists(), false);
2772 #[unstable(feature = "is_symlink", issue = "85748")]
2774 pub fn is_symlink(&self) -> bool {
2775 fs::symlink_metadata(self).map(|m| m.is_symlink()).unwrap_or(false)
2778 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2780 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2781 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2782 let rw = Box::into_raw(self) as *mut OsStr;
2783 let inner = unsafe { Box::from_raw(rw) };
2784 PathBuf { inner: OsString::from(inner) }
2788 #[stable(feature = "rust1", since = "1.0.0")]
2789 impl AsRef<OsStr> for Path {
2791 fn as_ref(&self) -> &OsStr {
2796 #[stable(feature = "rust1", since = "1.0.0")]
2797 impl fmt::Debug for Path {
2798 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2799 fmt::Debug::fmt(&self.inner, formatter)
2803 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2805 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2806 /// [`Display`] trait in a way that mitigates that. It is created by the
2807 /// [`display`](Path::display) method on [`Path`]. This may perform lossy
2808 /// conversion, depending on the platform. If you would like an implementation
2809 /// which escapes the path please use [`Debug`] instead.
2814 /// use std::path::Path;
2816 /// let path = Path::new("/tmp/foo.rs");
2818 /// println!("{}", path.display());
2821 /// [`Display`]: fmt::Display
2822 /// [`format!`]: crate::format
2823 #[stable(feature = "rust1", since = "1.0.0")]
2824 pub struct Display<'a> {
2828 #[stable(feature = "rust1", since = "1.0.0")]
2829 impl fmt::Debug for Display<'_> {
2830 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2831 fmt::Debug::fmt(&self.path, f)
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 impl fmt::Display for Display<'_> {
2837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2838 self.path.inner.display(f)
2842 #[stable(feature = "rust1", since = "1.0.0")]
2843 impl cmp::PartialEq for Path {
2845 fn eq(&self, other: &Path) -> bool {
2846 self.components() == other.components()
2850 #[stable(feature = "rust1", since = "1.0.0")]
2851 impl Hash for Path {
2852 fn hash<H: Hasher>(&self, h: &mut H) {
2853 for component in self.components() {
2859 #[stable(feature = "rust1", since = "1.0.0")]
2860 impl cmp::Eq for Path {}
2862 #[stable(feature = "rust1", since = "1.0.0")]
2863 impl cmp::PartialOrd for Path {
2865 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2866 Some(compare_components(self.components(), other.components()))
2870 #[stable(feature = "rust1", since = "1.0.0")]
2871 impl cmp::Ord for Path {
2873 fn cmp(&self, other: &Path) -> cmp::Ordering {
2874 compare_components(self.components(), other.components())
2878 #[stable(feature = "rust1", since = "1.0.0")]
2879 impl AsRef<Path> for Path {
2881 fn as_ref(&self) -> &Path {
2886 #[stable(feature = "rust1", since = "1.0.0")]
2887 impl AsRef<Path> for OsStr {
2889 fn as_ref(&self) -> &Path {
2894 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2895 impl AsRef<Path> for Cow<'_, OsStr> {
2897 fn as_ref(&self) -> &Path {
2902 #[stable(feature = "rust1", since = "1.0.0")]
2903 impl AsRef<Path> for OsString {
2905 fn as_ref(&self) -> &Path {
2910 #[stable(feature = "rust1", since = "1.0.0")]
2911 impl AsRef<Path> for str {
2913 fn as_ref(&self) -> &Path {
2918 #[stable(feature = "rust1", since = "1.0.0")]
2919 impl AsRef<Path> for String {
2921 fn as_ref(&self) -> &Path {
2926 #[stable(feature = "rust1", since = "1.0.0")]
2927 impl AsRef<Path> for PathBuf {
2929 fn as_ref(&self) -> &Path {
2934 #[stable(feature = "path_into_iter", since = "1.6.0")]
2935 impl<'a> IntoIterator for &'a PathBuf {
2936 type Item = &'a OsStr;
2937 type IntoIter = Iter<'a>;
2939 fn into_iter(self) -> Iter<'a> {
2944 #[stable(feature = "path_into_iter", since = "1.6.0")]
2945 impl<'a> IntoIterator for &'a Path {
2946 type Item = &'a OsStr;
2947 type IntoIter = Iter<'a>;
2949 fn into_iter(self) -> Iter<'a> {
2954 macro_rules! impl_cmp {
2955 ($lhs:ty, $rhs: ty) => {
2956 #[stable(feature = "partialeq_path", since = "1.6.0")]
2957 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2959 fn eq(&self, other: &$rhs) -> bool {
2960 <Path as PartialEq>::eq(self, other)
2964 #[stable(feature = "partialeq_path", since = "1.6.0")]
2965 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2967 fn eq(&self, other: &$lhs) -> bool {
2968 <Path as PartialEq>::eq(self, other)
2972 #[stable(feature = "cmp_path", since = "1.8.0")]
2973 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2975 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2976 <Path as PartialOrd>::partial_cmp(self, other)
2980 #[stable(feature = "cmp_path", since = "1.8.0")]
2981 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2983 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2984 <Path as PartialOrd>::partial_cmp(self, other)
2990 impl_cmp!(PathBuf, Path);
2991 impl_cmp!(PathBuf, &'a Path);
2992 impl_cmp!(Cow<'a, Path>, Path);
2993 impl_cmp!(Cow<'a, Path>, &'b Path);
2994 impl_cmp!(Cow<'a, Path>, PathBuf);
2996 macro_rules! impl_cmp_os_str {
2997 ($lhs:ty, $rhs: ty) => {
2998 #[stable(feature = "cmp_path", since = "1.8.0")]
2999 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3001 fn eq(&self, other: &$rhs) -> bool {
3002 <Path as PartialEq>::eq(self, other.as_ref())
3006 #[stable(feature = "cmp_path", since = "1.8.0")]
3007 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3009 fn eq(&self, other: &$lhs) -> bool {
3010 <Path as PartialEq>::eq(self.as_ref(), other)
3014 #[stable(feature = "cmp_path", since = "1.8.0")]
3015 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3017 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3018 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
3022 #[stable(feature = "cmp_path", since = "1.8.0")]
3023 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3025 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3026 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
3032 impl_cmp_os_str!(PathBuf, OsStr);
3033 impl_cmp_os_str!(PathBuf, &'a OsStr);
3034 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
3035 impl_cmp_os_str!(PathBuf, OsString);
3036 impl_cmp_os_str!(Path, OsStr);
3037 impl_cmp_os_str!(Path, &'a OsStr);
3038 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
3039 impl_cmp_os_str!(Path, OsString);
3040 impl_cmp_os_str!(&'a Path, OsStr);
3041 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
3042 impl_cmp_os_str!(&'a Path, OsString);
3043 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
3044 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
3045 impl_cmp_os_str!(Cow<'a, Path>, OsString);
3047 #[stable(since = "1.7.0", feature = "strip_prefix")]
3048 impl fmt::Display for StripPrefixError {
3049 #[allow(deprecated, deprecated_in_future)]
3050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3051 self.description().fmt(f)
3055 #[stable(since = "1.7.0", feature = "strip_prefix")]
3056 impl Error for StripPrefixError {
3057 #[allow(deprecated)]
3058 fn description(&self) -> &str {