1 //! Cross-platform path manipulation.
3 //! This module provides two types, [`PathBuf`] and [`Path`] (akin to [`String`]
4 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
5 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
6 //! on strings according to the local platform's path syntax.
8 //! Paths can be parsed into [`Component`]s by iterating over the structure
9 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
10 //! correspond to the substrings between path separators (`/` or `\`). You can
11 //! reconstruct an equivalent path from components with the [`push`] method on
12 //! [`PathBuf`]; note that the paths may differ syntactically by the
13 //! normalization described in the documentation for the [`components`] method.
15 //! ## Case sensitivity
17 //! Unless otherwise indicated path methods that do not access the filesystem,
18 //! such as [`Path::starts_with`] and [`Path::ends_with`], are case sensitive no
19 //! matter the platform or filesystem. An exception to this is made for Windows
24 //! Path manipulation includes both parsing components from slices and building
27 //! To parse a path, you can create a [`Path`] slice from a [`str`]
28 //! slice and start asking questions:
31 //! use std::path::Path;
32 //! use std::ffi::OsStr;
34 //! let path = Path::new("/tmp/foo/bar.txt");
36 //! let parent = path.parent();
37 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
39 //! let file_stem = path.file_stem();
40 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
42 //! let extension = path.extension();
43 //! assert_eq!(extension, Some(OsStr::new("txt")));
46 //! To build or modify paths, use [`PathBuf`]:
49 //! use std::path::PathBuf;
51 //! // This way works...
52 //! let mut path = PathBuf::from("c:\\");
54 //! path.push("windows");
55 //! path.push("system32");
57 //! path.set_extension("dll");
59 //! // ... but push is best used if you don't know everything up
60 //! // front. If you do, this way is better:
61 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
64 //! [`components`]: Path::components
65 //! [`push`]: PathBuf::push
67 #![stable(feature = "rust1", since = "1.0.0")]
68 #![deny(unsafe_op_in_unsafe_fn)]
73 use crate::borrow::{Borrow, Cow};
75 use crate::error::Error;
78 use crate::hash::{Hash, Hasher};
80 use crate::iter::{self, FusedIterator};
81 use crate::ops::{self, Deref};
83 use crate::str::FromStr;
86 use crate::ffi::{OsStr, OsString};
88 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
90 ////////////////////////////////////////////////////////////////////////////////
92 ////////////////////////////////////////////////////////////////////////////////
94 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
95 // taking advantage of the fact that OsStr always encodes ASCII characters
96 // as-is. Eventually, this transmutation should be replaced by direct uses of
97 // OsStr APIs for parsing, but it will take a while for those to become
100 ////////////////////////////////////////////////////////////////////////////////
102 ////////////////////////////////////////////////////////////////////////////////
104 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
106 /// Windows uses a variety of path prefix styles, including references to drive
107 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
108 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
109 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
110 /// no normalization is performed.
115 /// use std::path::{Component, Path, Prefix};
116 /// use std::path::Prefix::*;
117 /// use std::ffi::OsStr;
119 /// fn get_path_prefix(s: &str) -> Prefix {
120 /// let path = Path::new(s);
121 /// match path.components().next().unwrap() {
122 /// Component::Prefix(prefix_component) => prefix_component.kind(),
127 /// # if cfg!(windows) {
128 /// assert_eq!(Verbatim(OsStr::new("pictures")),
129 /// get_path_prefix(r"\\?\pictures\kittens"));
130 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
131 /// get_path_prefix(r"\\?\UNC\server\share"));
132 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
133 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
134 /// get_path_prefix(r"\\.\BrainInterface"));
135 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
136 /// get_path_prefix(r"\\server\share"));
137 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
140 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub enum Prefix<'a> {
143 /// Verbatim prefix, e.g., `\\?\cat_pics`.
145 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
147 #[stable(feature = "rust1", since = "1.0.0")]
148 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
150 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
151 /// e.g., `\\?\UNC\server\share`.
153 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
154 /// server's hostname and a share name.
155 #[stable(feature = "rust1", since = "1.0.0")]
157 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
158 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
161 /// Verbatim disk prefix, e.g., `\\?\C:`.
163 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
164 /// drive letter and `:`.
165 #[stable(feature = "rust1", since = "1.0.0")]
166 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
168 /// Device namespace prefix, e.g., `\\.\COM42`.
170 /// Device namespace prefixes consist of `\\.\` immediately followed by the
172 #[stable(feature = "rust1", since = "1.0.0")]
173 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
175 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
176 /// `\\server\share`.
178 /// UNC prefixes consist of the server's hostname and a share name.
179 #[stable(feature = "rust1", since = "1.0.0")]
181 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
182 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
185 /// Prefix `C:` for the given disk drive.
186 #[stable(feature = "rust1", since = "1.0.0")]
187 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
190 impl<'a> Prefix<'a> {
192 fn len(&self) -> usize {
194 fn os_str_len(s: &OsStr) -> usize {
195 os_str_as_u8_slice(s).len()
198 Verbatim(x) => 4 + os_str_len(x),
199 VerbatimUNC(x, y) => {
200 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
202 VerbatimDisk(_) => 6,
203 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
204 DeviceNS(x) => 4 + os_str_len(x),
209 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
214 /// use std::path::Prefix::*;
215 /// use std::ffi::OsStr;
217 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
218 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
219 /// assert!(VerbatimDisk(b'C').is_verbatim());
220 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
221 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
222 /// assert!(!Disk(b'C').is_verbatim());
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub fn is_verbatim(&self) -> bool {
229 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
233 fn is_drive(&self) -> bool {
234 matches!(*self, Prefix::Disk(_))
238 fn has_implicit_root(&self) -> bool {
243 ////////////////////////////////////////////////////////////////////////////////
244 // Exposed parsing helpers
245 ////////////////////////////////////////////////////////////////////////////////
247 /// Determines whether the character is one of the permitted path
248 /// separators for the current platform.
255 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
256 /// assert!(!path::is_separator('❤'));
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn is_separator(c: char) -> bool {
261 c.is_ascii() && is_sep_byte(c as u8)
264 /// The primary separator of path components for the current platform.
266 /// For example, `/` on Unix and `\` on Windows.
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
270 ////////////////////////////////////////////////////////////////////////////////
272 ////////////////////////////////////////////////////////////////////////////////
274 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
275 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
276 // `iter` after having exhausted `prefix`.
277 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
279 I: Iterator<Item = Component<'a>> + Clone,
280 J: Iterator<Item = Component<'b>>,
283 let mut iter_next = iter.clone();
284 match (iter_next.next(), prefix.next()) {
285 (Some(ref x), Some(ref y)) if x == y => (),
286 (Some(_), Some(_)) => return None,
287 (Some(_), None) => return Some(iter),
288 (None, None) => return Some(iter),
289 (None, Some(_)) => return None,
295 // See note at the top of this module to understand why these are used:
297 // These casts are safe as OsStr is internally a wrapper around [u8] on all
300 // Note that currently this relies on the special knowledge that libstd has;
301 // these types are single-element structs but are not marked repr(transparent)
302 // or repr(C) which would make these casts allowable outside std.
303 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
304 unsafe { &*(s as *const OsStr as *const [u8]) }
306 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
307 // SAFETY: see the comment of `os_str_as_u8_slice`
308 unsafe { &*(s as *const [u8] as *const OsStr) }
311 // Detect scheme on Redox
312 fn has_redox_scheme(s: &[u8]) -> bool {
313 cfg!(target_os = "redox") && s.contains(&b':')
316 ////////////////////////////////////////////////////////////////////////////////
317 // Cross-platform, iterator-independent parsing
318 ////////////////////////////////////////////////////////////////////////////////
320 /// Says whether the first byte after the prefix is a separator.
321 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
322 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
323 !path.is_empty() && is_sep_byte(path[0])
326 // basic workhorse for splitting stem and extension
327 fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
328 if os_str_as_u8_slice(file) == b".." {
329 return (Some(file), None);
332 // The unsafety here stems from converting between &OsStr and &[u8]
333 // and back. This is safe to do because (1) we only look at ASCII
334 // contents of the encoding and (2) new &OsStr values are produced
335 // only from ASCII-bounded slices of existing &OsStr values.
336 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
337 let after = iter.next();
338 let before = iter.next();
339 if before == Some(b"") {
342 unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
346 fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
347 let slice = os_str_as_u8_slice(file);
352 // The unsafety here stems from converting between &OsStr and &[u8]
353 // and back. This is safe to do because (1) we only look at ASCII
354 // contents of the encoding and (2) new &OsStr values are produced
355 // only from ASCII-bounded slices of existing &OsStr values.
356 let i = match slice[1..].iter().position(|b| *b == b'.') {
358 None => return (file, None),
360 let before = &slice[..i];
361 let after = &slice[i + 1..];
362 unsafe { (u8_slice_as_os_str(before), Some(u8_slice_as_os_str(after))) }
365 ////////////////////////////////////////////////////////////////////////////////
366 // The core iterators
367 ////////////////////////////////////////////////////////////////////////////////
369 /// Component parsing works by a double-ended state machine; the cursors at the
370 /// front and back of the path each keep track of what parts of the path have
371 /// been consumed so far.
373 /// Going front to back, a path is made up of a prefix, a starting
374 /// directory component, and a body (of normal components)
375 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
378 StartDir = 1, // / or . or nothing
379 Body = 2, // foo/bar/baz
383 /// A structure wrapping a Windows path prefix as well as its unparsed string
386 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
387 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
388 /// returned by [`as_os_str`].
390 /// Instances of this `struct` can be obtained by matching against the
391 /// [`Prefix` variant] on [`Component`].
393 /// Does not occur on Unix.
398 /// # if cfg!(windows) {
399 /// use std::path::{Component, Path, Prefix};
400 /// use std::ffi::OsStr;
402 /// let path = Path::new(r"c:\you\later\");
403 /// match path.components().next().unwrap() {
404 /// Component::Prefix(prefix_component) => {
405 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
406 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
408 /// _ => unreachable!(),
413 /// [`as_os_str`]: PrefixComponent::as_os_str
414 /// [`kind`]: PrefixComponent::kind
415 /// [`Prefix` variant]: Component::Prefix
416 #[stable(feature = "rust1", since = "1.0.0")]
417 #[derive(Copy, Clone, Eq, Debug)]
418 pub struct PrefixComponent<'a> {
419 /// The prefix as an unparsed `OsStr` slice.
422 /// The parsed prefix data.
426 impl<'a> PrefixComponent<'a> {
427 /// Returns the parsed prefix data.
429 /// See [`Prefix`]'s documentation for more information on the different
430 /// kinds of prefixes.
431 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn kind(&self) -> Prefix<'a> {
438 /// Returns the raw [`OsStr`] slice for this prefix.
439 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn as_os_str(&self) -> &'a OsStr {
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
450 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
451 cmp::PartialEq::eq(&self.parsed, &other.parsed)
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
458 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
459 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl cmp::Ord for PrefixComponent<'_> {
466 fn cmp(&self, other: &Self) -> cmp::Ordering {
467 cmp::Ord::cmp(&self.parsed, &other.parsed)
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl Hash for PrefixComponent<'_> {
473 fn hash<H: Hasher>(&self, h: &mut H) {
478 /// A single component of a path.
480 /// A `Component` roughly corresponds to a substring between path separators
483 /// This `enum` is created by iterating over [`Components`], which in turn is
484 /// created by the [`components`](Path::components) method on [`Path`].
489 /// use std::path::{Component, Path};
491 /// let path = Path::new("/tmp/foo/bar.txt");
492 /// let components = path.components().collect::<Vec<_>>();
493 /// assert_eq!(&components, &[
494 /// Component::RootDir,
495 /// Component::Normal("tmp".as_ref()),
496 /// Component::Normal("foo".as_ref()),
497 /// Component::Normal("bar.txt".as_ref()),
500 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub enum Component<'a> {
503 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
505 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
508 /// Does not occur on Unix.
509 #[stable(feature = "rust1", since = "1.0.0")]
510 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
512 /// The root directory component, appears after any prefix and before anything else.
514 /// It represents a separator that designates that a path starts from root.
515 #[stable(feature = "rust1", since = "1.0.0")]
518 /// A reference to the current directory, i.e., `.`.
519 #[stable(feature = "rust1", since = "1.0.0")]
522 /// A reference to the parent directory, i.e., `..`.
523 #[stable(feature = "rust1", since = "1.0.0")]
526 /// A normal component, e.g., `a` and `b` in `a/b`.
528 /// This variant is the most common one, it represents references to files
530 #[stable(feature = "rust1", since = "1.0.0")]
531 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
534 impl<'a> Component<'a> {
535 /// Extracts the underlying [`OsStr`] slice.
540 /// use std::path::Path;
542 /// let path = Path::new("./tmp/foo/bar.txt");
543 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
544 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
546 #[must_use = "`self` will be dropped if the result is not used"]
547 #[stable(feature = "rust1", since = "1.0.0")]
548 pub fn as_os_str(self) -> &'a OsStr {
550 Component::Prefix(p) => p.as_os_str(),
551 Component::RootDir => OsStr::new(MAIN_SEP_STR),
552 Component::CurDir => OsStr::new("."),
553 Component::ParentDir => OsStr::new(".."),
554 Component::Normal(path) => path,
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl AsRef<OsStr> for Component<'_> {
562 fn as_ref(&self) -> &OsStr {
567 #[stable(feature = "path_component_asref", since = "1.25.0")]
568 impl AsRef<Path> for Component<'_> {
570 fn as_ref(&self) -> &Path {
571 self.as_os_str().as_ref()
575 /// An iterator over the [`Component`]s of a [`Path`].
577 /// This `struct` is created by the [`components`] method on [`Path`].
578 /// See its documentation for more.
583 /// use std::path::Path;
585 /// let path = Path::new("/tmp/foo/bar.txt");
587 /// for component in path.components() {
588 /// println!("{:?}", component);
592 /// [`components`]: Path::components
594 #[must_use = "iterators are lazy and do nothing unless consumed"]
595 #[stable(feature = "rust1", since = "1.0.0")]
596 pub struct Components<'a> {
597 // The path left to parse components from
600 // The prefix as it was originally parsed, if any
601 prefix: Option<Prefix<'a>>,
603 // true if path *physically* has a root separator; for most Windows
604 // prefixes, it may have a "logical" root separator for the purposes of
605 // normalization, e.g., \\server\share == \\server\share\.
606 has_physical_root: bool,
608 // The iterator is double-ended, and these two states keep track of what has
609 // been produced from either end
614 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
616 /// This `struct` is created by the [`iter`] method on [`Path`].
617 /// See its documentation for more.
619 /// [`iter`]: Path::iter
621 #[must_use = "iterators are lazy and do nothing unless consumed"]
622 #[stable(feature = "rust1", since = "1.0.0")]
623 pub struct Iter<'a> {
624 inner: Components<'a>,
627 #[stable(feature = "path_components_debug", since = "1.13.0")]
628 impl fmt::Debug for Components<'_> {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 struct DebugHelper<'a>(&'a Path);
632 impl fmt::Debug for DebugHelper<'_> {
633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634 f.debug_list().entries(self.0.components()).finish()
638 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
642 impl<'a> Components<'a> {
643 // how long is the prefix, if any?
645 fn prefix_len(&self) -> usize {
646 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
650 fn prefix_verbatim(&self) -> bool {
651 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
654 /// how much of the prefix is left from the point of view of iteration?
656 fn prefix_remaining(&self) -> usize {
657 if self.front == State::Prefix { self.prefix_len() } else { 0 }
660 // Given the iteration so far, how much of the pre-State::Body path is left?
662 fn len_before_body(&self) -> usize {
663 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
664 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
665 self.prefix_remaining() + root + cur_dir
668 // is the iteration complete?
670 fn finished(&self) -> bool {
671 self.front == State::Done || self.back == State::Done || self.front > self.back
675 fn is_sep_byte(&self, b: u8) -> bool {
676 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
679 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
684 /// use std::path::Path;
686 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
687 /// components.next();
688 /// components.next();
690 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
693 #[stable(feature = "rust1", since = "1.0.0")]
694 pub fn as_path(&self) -> &'a Path {
695 let mut comps = self.clone();
696 if comps.front == State::Body {
699 if comps.back == State::Body {
702 unsafe { Path::from_u8_slice(comps.path) }
705 /// Is the *original* path rooted?
706 fn has_root(&self) -> bool {
707 if self.has_physical_root {
710 if let Some(p) = self.prefix {
711 if p.has_implicit_root() {
718 /// Should the normalized path include a leading . ?
719 fn include_cur_dir(&self) -> bool {
723 let mut iter = self.path[self.prefix_len()..].iter();
724 match (iter.next(), iter.next()) {
725 (Some(&b'.'), None) => true,
726 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
731 // parse a given byte sequence into the corresponding path component
732 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
734 b"." if self.prefix_verbatim() => Some(Component::CurDir),
735 b"." => None, // . components are normalized away, except at
736 // the beginning of a path, which is treated
737 // separately via `include_cur_dir`
738 b".." => Some(Component::ParentDir),
740 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
744 // parse a component from the left, saying how many bytes to consume to
745 // remove the component
746 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
747 debug_assert!(self.front == State::Body);
748 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
749 None => (0, self.path),
750 Some(i) => (1, &self.path[..i]),
752 (comp.len() + extra, self.parse_single_component(comp))
755 // parse a component from the right, saying how many bytes to consume to
756 // remove the component
757 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
758 debug_assert!(self.back == State::Body);
759 let start = self.len_before_body();
760 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
761 None => (0, &self.path[start..]),
762 Some(i) => (1, &self.path[start + i + 1..]),
764 (comp.len() + extra, self.parse_single_component(comp))
767 // trim away repeated separators (i.e., empty components) on the left
768 fn trim_left(&mut self) {
769 while !self.path.is_empty() {
770 let (size, comp) = self.parse_next_component();
774 self.path = &self.path[size..];
779 // trim away repeated separators (i.e., empty components) on the right
780 fn trim_right(&mut self) {
781 while self.path.len() > self.len_before_body() {
782 let (size, comp) = self.parse_next_component_back();
786 self.path = &self.path[..self.path.len() - size];
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl AsRef<Path> for Components<'_> {
795 fn as_ref(&self) -> &Path {
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl AsRef<OsStr> for Components<'_> {
803 fn as_ref(&self) -> &OsStr {
804 self.as_path().as_os_str()
808 #[stable(feature = "path_iter_debug", since = "1.13.0")]
809 impl fmt::Debug for Iter<'_> {
810 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
811 struct DebugHelper<'a>(&'a Path);
813 impl fmt::Debug for DebugHelper<'_> {
814 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815 f.debug_list().entries(self.0.iter()).finish()
819 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
824 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
829 /// use std::path::Path;
831 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
835 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
837 #[stable(feature = "rust1", since = "1.0.0")]
840 pub fn as_path(&self) -> &'a Path {
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl AsRef<Path> for Iter<'_> {
848 fn as_ref(&self) -> &Path {
853 #[stable(feature = "rust1", since = "1.0.0")]
854 impl AsRef<OsStr> for Iter<'_> {
856 fn as_ref(&self) -> &OsStr {
857 self.as_path().as_os_str()
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<'a> Iterator for Iter<'a> {
863 type Item = &'a OsStr;
866 fn next(&mut self) -> Option<&'a OsStr> {
867 self.inner.next().map(Component::as_os_str)
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl<'a> DoubleEndedIterator for Iter<'a> {
874 fn next_back(&mut self) -> Option<&'a OsStr> {
875 self.inner.next_back().map(Component::as_os_str)
879 #[stable(feature = "fused", since = "1.26.0")]
880 impl FusedIterator for Iter<'_> {}
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<'a> Iterator for Components<'a> {
884 type Item = Component<'a>;
886 fn next(&mut self) -> Option<Component<'a>> {
887 while !self.finished() {
889 State::Prefix if self.prefix_len() > 0 => {
890 self.front = State::StartDir;
891 debug_assert!(self.prefix_len() <= self.path.len());
892 let raw = &self.path[..self.prefix_len()];
893 self.path = &self.path[self.prefix_len()..];
894 return Some(Component::Prefix(PrefixComponent {
895 raw: unsafe { u8_slice_as_os_str(raw) },
896 parsed: self.prefix.unwrap(),
900 self.front = State::StartDir;
903 self.front = State::Body;
904 if self.has_physical_root {
905 debug_assert!(!self.path.is_empty());
906 self.path = &self.path[1..];
907 return Some(Component::RootDir);
908 } else if let Some(p) = self.prefix {
909 if p.has_implicit_root() && !p.is_verbatim() {
910 return Some(Component::RootDir);
912 } else if self.include_cur_dir() {
913 debug_assert!(!self.path.is_empty());
914 self.path = &self.path[1..];
915 return Some(Component::CurDir);
918 State::Body if !self.path.is_empty() => {
919 let (size, comp) = self.parse_next_component();
920 self.path = &self.path[size..];
926 self.front = State::Done;
928 State::Done => unreachable!(),
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<'a> DoubleEndedIterator for Components<'a> {
937 fn next_back(&mut self) -> Option<Component<'a>> {
938 while !self.finished() {
940 State::Body if self.path.len() > self.len_before_body() => {
941 let (size, comp) = self.parse_next_component_back();
942 self.path = &self.path[..self.path.len() - size];
948 self.back = State::StartDir;
951 self.back = State::Prefix;
952 if self.has_physical_root {
953 self.path = &self.path[..self.path.len() - 1];
954 return Some(Component::RootDir);
955 } else if let Some(p) = self.prefix {
956 if p.has_implicit_root() && !p.is_verbatim() {
957 return Some(Component::RootDir);
959 } else if self.include_cur_dir() {
960 self.path = &self.path[..self.path.len() - 1];
961 return Some(Component::CurDir);
964 State::Prefix if self.prefix_len() > 0 => {
965 self.back = State::Done;
966 return Some(Component::Prefix(PrefixComponent {
967 raw: unsafe { u8_slice_as_os_str(self.path) },
968 parsed: self.prefix.unwrap(),
972 self.back = State::Done;
975 State::Done => unreachable!(),
982 #[stable(feature = "fused", since = "1.26.0")]
983 impl FusedIterator for Components<'_> {}
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<'a> cmp::PartialEq for Components<'a> {
988 fn eq(&self, other: &Components<'a>) -> bool {
989 let Components { path: _, front: _, back: _, has_physical_root: _, prefix: _ } = self;
991 // Fast path for exact matches, e.g. for hashmap lookups.
992 // Don't explicitly compare the prefix or has_physical_root fields since they'll
993 // either be covered by the `path` buffer or are only relevant for `prefix_verbatim()`.
994 if self.path.len() == other.path.len()
995 && self.front == other.front
996 && self.back == State::Body
997 && other.back == State::Body
998 && self.prefix_verbatim() == other.prefix_verbatim()
1000 // possible future improvement: this could bail out earlier if there were a
1001 // reverse memcmp/bcmp comparing back to front
1002 if self.path == other.path {
1007 // compare back to front since absolute paths often share long prefixes
1008 Iterator::eq(self.clone().rev(), other.clone().rev())
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl cmp::Eq for Components<'_> {}
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<'a> cmp::PartialOrd for Components<'a> {
1018 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1019 Some(compare_components(self.clone(), other.clone()))
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 impl cmp::Ord for Components<'_> {
1026 fn cmp(&self, other: &Self) -> cmp::Ordering {
1027 compare_components(self.clone(), other.clone())
1031 fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cmp::Ordering {
1032 // Fast path for long shared prefixes
1034 // - compare raw bytes to find first mismatch
1035 // - backtrack to find separator before mismatch to avoid ambiguous parsings of '.' or '..' characters
1036 // - if found update state to only do a component-wise comparison on the remainder,
1037 // otherwise do it on the full path
1039 // The fast path isn't taken for paths with a PrefixComponent to avoid backtracking into
1040 // the middle of one
1041 if left.prefix.is_none() && right.prefix.is_none() && left.front == right.front {
1042 // possible future improvement: a [u8]::first_mismatch simd implementation
1043 let first_difference = match left.path.iter().zip(right.path).position(|(&a, &b)| a != b) {
1044 None if left.path.len() == right.path.len() => return cmp::Ordering::Equal,
1045 None => left.path.len().min(right.path.len()),
1049 if let Some(previous_sep) =
1050 left.path[..first_difference].iter().rposition(|&b| left.is_sep_byte(b))
1052 let mismatched_component_start = previous_sep + 1;
1053 left.path = &left.path[mismatched_component_start..];
1054 left.front = State::Body;
1055 right.path = &right.path[mismatched_component_start..];
1056 right.front = State::Body;
1060 Iterator::cmp(left, right)
1063 /// An iterator over [`Path`] and its ancestors.
1065 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1066 /// See its documentation for more.
1071 /// use std::path::Path;
1073 /// let path = Path::new("/foo/bar");
1075 /// for ancestor in path.ancestors() {
1076 /// println!("{}", ancestor.display());
1080 /// [`ancestors`]: Path::ancestors
1081 #[derive(Copy, Clone, Debug)]
1082 #[must_use = "iterators are lazy and do nothing unless consumed"]
1083 #[stable(feature = "path_ancestors", since = "1.28.0")]
1084 pub struct Ancestors<'a> {
1085 next: Option<&'a Path>,
1088 #[stable(feature = "path_ancestors", since = "1.28.0")]
1089 impl<'a> Iterator for Ancestors<'a> {
1090 type Item = &'a Path;
1093 fn next(&mut self) -> Option<Self::Item> {
1094 let next = self.next;
1095 self.next = next.and_then(Path::parent);
1100 #[stable(feature = "path_ancestors", since = "1.28.0")]
1101 impl FusedIterator for Ancestors<'_> {}
1103 ////////////////////////////////////////////////////////////////////////////////
1104 // Basic types and traits
1105 ////////////////////////////////////////////////////////////////////////////////
1107 /// An owned, mutable path (akin to [`String`]).
1109 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1110 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1111 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1113 /// [`push`]: PathBuf::push
1114 /// [`set_extension`]: PathBuf::set_extension
1116 /// More details about the overall approach can be found in
1117 /// the [module documentation](self).
1121 /// You can use [`push`] to build up a `PathBuf` from
1125 /// use std::path::PathBuf;
1127 /// let mut path = PathBuf::new();
1129 /// path.push(r"C:\");
1130 /// path.push("windows");
1131 /// path.push("system32");
1133 /// path.set_extension("dll");
1136 /// However, [`push`] is best used for dynamic situations. This is a better way
1137 /// to do this when you know all of the components ahead of time:
1140 /// use std::path::PathBuf;
1142 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1145 /// We can still do better than this! Since these are all strings, we can use
1149 /// use std::path::PathBuf;
1151 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1154 /// Which method works best depends on what kind of situation you're in.
1155 #[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1156 #[stable(feature = "rust1", since = "1.0.0")]
1158 // `PathBuf::as_mut_vec` current implementation relies
1159 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1160 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1161 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1162 // not documented and must not be relied upon.
1163 pub struct PathBuf {
1169 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1170 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1173 /// Allocates an empty `PathBuf`.
1178 /// use std::path::PathBuf;
1180 /// let path = PathBuf::new();
1182 #[stable(feature = "rust1", since = "1.0.0")]
1185 pub fn new() -> PathBuf {
1186 PathBuf { inner: OsString::new() }
1189 /// Creates a new `PathBuf` with a given capacity used to create the
1190 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1195 /// use std::path::PathBuf;
1197 /// let mut path = PathBuf::with_capacity(10);
1198 /// let capacity = path.capacity();
1200 /// // This push is done without reallocating
1201 /// path.push(r"C:\");
1203 /// assert_eq!(capacity, path.capacity());
1206 /// [`with_capacity`]: OsString::with_capacity
1207 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1210 pub fn with_capacity(capacity: usize) -> PathBuf {
1211 PathBuf { inner: OsString::with_capacity(capacity) }
1214 /// Coerces to a [`Path`] slice.
1219 /// use std::path::{Path, PathBuf};
1221 /// let p = PathBuf::from("/test");
1222 /// assert_eq!(Path::new("/test"), p.as_path());
1224 #[stable(feature = "rust1", since = "1.0.0")]
1227 pub fn as_path(&self) -> &Path {
1231 /// Extends `self` with `path`.
1233 /// If `path` is absolute, it replaces the current path.
1237 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1238 /// replaces everything except for the prefix (if any) of `self`.
1239 /// * if `path` has a prefix but no root, it replaces `self`.
1240 /// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
1241 /// and `path` is not empty, the new path is normalized: all references
1242 /// to `.` and `..` are removed.
1246 /// Pushing a relative path extends the existing path:
1249 /// use std::path::PathBuf;
1251 /// let mut path = PathBuf::from("/tmp");
1252 /// path.push("file.bk");
1253 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1256 /// Pushing an absolute path replaces the existing path:
1259 /// use std::path::PathBuf;
1261 /// let mut path = PathBuf::from("/tmp");
1262 /// path.push("/etc");
1263 /// assert_eq!(path, PathBuf::from("/etc"));
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1267 self._push(path.as_ref())
1270 fn _push(&mut self, path: &Path) {
1271 // in general, a separator is needed if the rightmost byte is not a separator
1272 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1274 // in the special case of `C:` on Windows, do *not* add a separator
1275 let comps = self.components();
1277 if comps.prefix_len() > 0
1278 && comps.prefix_len() == comps.path.len()
1279 && comps.prefix.unwrap().is_drive()
1284 // absolute `path` replaces `self`
1285 if path.is_absolute() || path.prefix().is_some() {
1286 self.as_mut_vec().truncate(0);
1288 // verbatim paths need . and .. removed
1289 } else if comps.prefix_verbatim() && !path.inner.is_empty() {
1290 let mut buf: Vec<_> = comps.collect();
1291 for c in path.components() {
1293 Component::RootDir => {
1297 Component::CurDir => (),
1298 Component::ParentDir => {
1299 if let Some(Component::Normal(_)) = buf.last() {
1307 let mut res = OsString::new();
1308 let mut need_sep = false;
1311 if need_sep && c != Component::RootDir {
1312 res.push(MAIN_SEP_STR);
1314 res.push(c.as_os_str());
1316 need_sep = match c {
1317 Component::RootDir => false,
1318 Component::Prefix(prefix) => {
1319 !prefix.parsed.is_drive() && prefix.parsed.len() > 0
1328 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1329 } else if path.has_root() {
1330 let prefix_len = self.components().prefix_remaining();
1331 self.as_mut_vec().truncate(prefix_len);
1333 // `path` is a pure relative path
1334 } else if need_sep {
1335 self.inner.push(MAIN_SEP_STR);
1338 self.inner.push(path);
1341 /// Truncates `self` to [`self.parent`].
1343 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1344 /// Otherwise, returns `true`.
1346 /// [`self.parent`]: Path::parent
1351 /// use std::path::{Path, PathBuf};
1353 /// let mut p = PathBuf::from("/spirited/away.rs");
1356 /// assert_eq!(Path::new("/spirited"), p);
1358 /// assert_eq!(Path::new("/"), p);
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 pub fn pop(&mut self) -> bool {
1362 match self.parent().map(|p| p.as_u8_slice().len()) {
1364 self.as_mut_vec().truncate(len);
1371 /// Updates [`self.file_name`] to `file_name`.
1373 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1376 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1377 /// `file_name`. The new path will be a sibling of the original path.
1378 /// (That is, it will have the same parent.)
1380 /// [`self.file_name`]: Path::file_name
1381 /// [`pop`]: PathBuf::pop
1386 /// use std::path::PathBuf;
1388 /// let mut buf = PathBuf::from("/");
1389 /// assert!(buf.file_name() == None);
1390 /// buf.set_file_name("bar");
1391 /// assert!(buf == PathBuf::from("/bar"));
1392 /// assert!(buf.file_name().is_some());
1393 /// buf.set_file_name("baz.txt");
1394 /// assert!(buf == PathBuf::from("/baz.txt"));
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1398 self._set_file_name(file_name.as_ref())
1401 fn _set_file_name(&mut self, file_name: &OsStr) {
1402 if self.file_name().is_some() {
1403 let popped = self.pop();
1404 debug_assert!(popped);
1406 self.push(file_name);
1409 /// Updates [`self.extension`] to `extension`.
1411 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1412 /// returns `true` and updates the extension otherwise.
1414 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1417 /// [`self.file_name`]: Path::file_name
1418 /// [`self.extension`]: Path::extension
1423 /// use std::path::{Path, PathBuf};
1425 /// let mut p = PathBuf::from("/feel/the");
1427 /// p.set_extension("force");
1428 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1430 /// p.set_extension("dark_side");
1431 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1435 self._set_extension(extension.as_ref())
1438 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1439 let file_stem = match self.file_stem() {
1440 None => return false,
1441 Some(f) => os_str_as_u8_slice(f),
1444 // truncate until right after the file stem
1445 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1446 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1447 let v = self.as_mut_vec();
1448 v.truncate(end_file_stem.wrapping_sub(start));
1450 // add the new extension, if any
1451 let new = os_str_as_u8_slice(extension);
1452 if !new.is_empty() {
1453 v.reserve_exact(new.len() + 1);
1455 v.extend_from_slice(new);
1461 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1466 /// use std::path::PathBuf;
1468 /// let p = PathBuf::from("/the/head");
1469 /// let os_str = p.into_os_string();
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 #[must_use = "`self` will be dropped if the result is not used"]
1474 pub fn into_os_string(self) -> OsString {
1478 /// Converts this `PathBuf` into a [boxed](Box) [`Path`].
1479 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1480 #[must_use = "`self` will be dropped if the result is not used"]
1482 pub fn into_boxed_path(self) -> Box<Path> {
1483 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1484 unsafe { Box::from_raw(rw) }
1487 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1489 /// [`capacity`]: OsString::capacity
1490 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1493 pub fn capacity(&self) -> usize {
1494 self.inner.capacity()
1497 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1499 /// [`clear`]: OsString::clear
1500 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1502 pub fn clear(&mut self) {
1506 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1508 /// [`reserve`]: OsString::reserve
1509 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1511 pub fn reserve(&mut self, additional: usize) {
1512 self.inner.reserve(additional)
1515 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1517 /// [`reserve_exact`]: OsString::reserve_exact
1518 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1520 pub fn reserve_exact(&mut self, additional: usize) {
1521 self.inner.reserve_exact(additional)
1524 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1526 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1527 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1529 pub fn shrink_to_fit(&mut self) {
1530 self.inner.shrink_to_fit()
1533 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1535 /// [`shrink_to`]: OsString::shrink_to
1536 #[stable(feature = "shrink_to", since = "1.56.0")]
1538 pub fn shrink_to(&mut self, min_capacity: usize) {
1539 self.inner.shrink_to(min_capacity)
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl Clone for PathBuf {
1546 fn clone(&self) -> Self {
1547 PathBuf { inner: self.inner.clone() }
1551 fn clone_from(&mut self, source: &Self) {
1552 self.inner.clone_from(&source.inner)
1556 #[stable(feature = "box_from_path", since = "1.17.0")]
1557 impl From<&Path> for Box<Path> {
1558 /// Creates a boxed [`Path`] from a reference.
1560 /// This will allocate and clone `path` to it.
1561 fn from(path: &Path) -> Box<Path> {
1562 let boxed: Box<OsStr> = path.inner.into();
1563 let rw = Box::into_raw(boxed) as *mut Path;
1564 unsafe { Box::from_raw(rw) }
1568 #[stable(feature = "box_from_cow", since = "1.45.0")]
1569 impl From<Cow<'_, Path>> for Box<Path> {
1570 /// Creates a boxed [`Path`] from a clone-on-write pointer.
1572 /// Converting from a `Cow::Owned` does not clone or allocate.
1574 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1576 Cow::Borrowed(path) => Box::from(path),
1577 Cow::Owned(path) => Box::from(path),
1582 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1583 impl From<Box<Path>> for PathBuf {
1584 /// Converts a `Box<Path>` into a `PathBuf`
1586 /// This conversion does not allocate or copy memory.
1588 fn from(boxed: Box<Path>) -> PathBuf {
1589 boxed.into_path_buf()
1593 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1594 impl From<PathBuf> for Box<Path> {
1595 /// Converts a `PathBuf` into a `Box<Path>`
1597 /// This conversion currently should not allocate memory,
1598 /// but this behavior is not guaranteed on all platforms or in all future versions.
1600 fn from(p: PathBuf) -> Box<Path> {
1605 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1606 impl Clone for Box<Path> {
1608 fn clone(&self) -> Self {
1609 self.to_path_buf().into_boxed_path()
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1615 /// Converts a borrowed `OsStr` to a `PathBuf`.
1617 /// Allocates a [`PathBuf`] and copies the data into it.
1619 fn from(s: &T) -> PathBuf {
1620 PathBuf::from(s.as_ref().to_os_string())
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl From<OsString> for PathBuf {
1626 /// Converts an [`OsString`] into a [`PathBuf`]
1628 /// This conversion does not allocate or copy memory.
1630 fn from(s: OsString) -> PathBuf {
1631 PathBuf { inner: s }
1635 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1636 impl From<PathBuf> for OsString {
1637 /// Converts a [`PathBuf`] into an [`OsString`]
1639 /// This conversion does not allocate or copy memory.
1641 fn from(path_buf: PathBuf) -> OsString {
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl From<String> for PathBuf {
1648 /// Converts a [`String`] into a [`PathBuf`]
1650 /// This conversion does not allocate or copy memory.
1652 fn from(s: String) -> PathBuf {
1653 PathBuf::from(OsString::from(s))
1657 #[stable(feature = "path_from_str", since = "1.32.0")]
1658 impl FromStr for PathBuf {
1659 type Err = core::convert::Infallible;
1662 fn from_str(s: &str) -> Result<Self, Self::Err> {
1663 Ok(PathBuf::from(s))
1667 #[stable(feature = "rust1", since = "1.0.0")]
1668 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1669 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1670 let mut buf = PathBuf::new();
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1678 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1679 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1683 fn extend_one(&mut self, p: P) {
1684 self.push(p.as_ref());
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl fmt::Debug for PathBuf {
1690 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1691 fmt::Debug::fmt(&**self, formatter)
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl ops::Deref for PathBuf {
1699 fn deref(&self) -> &Path {
1700 Path::new(&self.inner)
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 impl Borrow<Path> for PathBuf {
1707 fn borrow(&self) -> &Path {
1712 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1713 impl Default for PathBuf {
1715 fn default() -> Self {
1720 #[stable(feature = "cow_from_path", since = "1.6.0")]
1721 impl<'a> From<&'a Path> for Cow<'a, Path> {
1722 /// Creates a clone-on-write pointer from a reference to
1725 /// This conversion does not clone or allocate.
1727 fn from(s: &'a Path) -> Cow<'a, Path> {
1732 #[stable(feature = "cow_from_path", since = "1.6.0")]
1733 impl<'a> From<PathBuf> for Cow<'a, Path> {
1734 /// Creates a clone-on-write pointer from an owned
1735 /// instance of [`PathBuf`].
1737 /// This conversion does not clone or allocate.
1739 fn from(s: PathBuf) -> Cow<'a, Path> {
1744 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1745 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1746 /// Creates a clone-on-write pointer from a reference to
1749 /// This conversion does not clone or allocate.
1751 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1752 Cow::Borrowed(p.as_path())
1756 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1757 impl<'a> From<Cow<'a, Path>> for PathBuf {
1758 /// Converts a clone-on-write pointer to an owned path.
1760 /// Converting from a `Cow::Owned` does not clone or allocate.
1762 fn from(p: Cow<'a, Path>) -> Self {
1767 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1768 impl From<PathBuf> for Arc<Path> {
1769 /// Converts a [`PathBuf`] into an [`Arc`] by moving the [`PathBuf`] data into a new [`Arc`] buffer.
1771 fn from(s: PathBuf) -> Arc<Path> {
1772 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1773 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1777 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1778 impl From<&Path> for Arc<Path> {
1779 /// Converts a [`Path`] into an [`Arc`] by copying the [`Path`] data into a new [`Arc`] buffer.
1781 fn from(s: &Path) -> Arc<Path> {
1782 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1783 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1787 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1788 impl From<PathBuf> for Rc<Path> {
1789 /// Converts a [`PathBuf`] into an [`Rc`] by moving the [`PathBuf`] data into a new `Rc` buffer.
1791 fn from(s: PathBuf) -> Rc<Path> {
1792 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1793 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1797 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1798 impl From<&Path> for Rc<Path> {
1799 /// Converts a [`Path`] into an [`Rc`] by copying the [`Path`] data into a new `Rc` buffer.
1801 fn from(s: &Path) -> Rc<Path> {
1802 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1803 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 impl ToOwned for Path {
1809 type Owned = PathBuf;
1811 fn to_owned(&self) -> PathBuf {
1815 fn clone_into(&self, target: &mut PathBuf) {
1816 self.inner.clone_into(&mut target.inner);
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl cmp::PartialEq for PathBuf {
1823 fn eq(&self, other: &PathBuf) -> bool {
1824 self.components() == other.components()
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 impl Hash for PathBuf {
1830 fn hash<H: Hasher>(&self, h: &mut H) {
1831 self.as_path().hash(h)
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 impl cmp::Eq for PathBuf {}
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 impl cmp::PartialOrd for PathBuf {
1841 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1842 Some(compare_components(self.components(), other.components()))
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 impl cmp::Ord for PathBuf {
1849 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1850 compare_components(self.components(), other.components())
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl AsRef<OsStr> for PathBuf {
1857 fn as_ref(&self) -> &OsStr {
1862 /// A slice of a path (akin to [`str`]).
1864 /// This type supports a number of operations for inspecting a path, including
1865 /// breaking the path into its components (separated by `/` on Unix and by either
1866 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1867 /// is absolute, and so on.
1869 /// This is an *unsized* type, meaning that it must always be used behind a
1870 /// pointer like `&` or [`Box`]. For an owned version of this type,
1871 /// see [`PathBuf`].
1873 /// More details about the overall approach can be found in
1874 /// the [module documentation](self).
1879 /// use std::path::Path;
1880 /// use std::ffi::OsStr;
1882 /// // Note: this example does work on Windows
1883 /// let path = Path::new("./foo/bar.txt");
1885 /// let parent = path.parent();
1886 /// assert_eq!(parent, Some(Path::new("./foo")));
1888 /// let file_stem = path.file_stem();
1889 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1891 /// let extension = path.extension();
1892 /// assert_eq!(extension, Some(OsStr::new("txt")));
1894 #[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
1895 #[stable(feature = "rust1", since = "1.0.0")]
1897 // `Path::new` current implementation relies
1898 // on `Path` being layout-compatible with `OsStr`.
1899 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1900 // Anyway, `Path` representation and layout are considered implementation detail, are
1901 // not documented and must not be relied upon.
1906 /// An error returned from [`Path::strip_prefix`] if the prefix was not found.
1908 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1909 /// See its documentation for more.
1911 /// [`strip_prefix`]: Path::strip_prefix
1912 #[derive(Debug, Clone, PartialEq, Eq)]
1913 #[stable(since = "1.7.0", feature = "strip_prefix")]
1914 pub struct StripPrefixError(());
1917 // The following (private!) function allows construction of a path from a u8
1918 // slice, which is only safe when it is known to follow the OsStr encoding.
1919 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1920 unsafe { Path::new(u8_slice_as_os_str(s)) }
1922 // The following (private!) function reveals the byte encoding used for OsStr.
1923 fn as_u8_slice(&self) -> &[u8] {
1924 os_str_as_u8_slice(&self.inner)
1927 /// Directly wraps a string slice as a `Path` slice.
1929 /// This is a cost-free conversion.
1934 /// use std::path::Path;
1936 /// Path::new("foo.txt");
1939 /// You can create `Path`s from `String`s, or even other `Path`s:
1942 /// use std::path::Path;
1944 /// let string = String::from("foo.txt");
1945 /// let from_string = Path::new(&string);
1946 /// let from_path = Path::new(&from_string);
1947 /// assert_eq!(from_string, from_path);
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1951 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1954 /// Yields the underlying [`OsStr`] slice.
1959 /// use std::path::Path;
1961 /// let os_str = Path::new("foo.txt").as_os_str();
1962 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1964 #[stable(feature = "rust1", since = "1.0.0")]
1967 pub fn as_os_str(&self) -> &OsStr {
1971 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1973 /// This conversion may entail doing a check for UTF-8 validity.
1974 /// Note that validation is performed because non-UTF-8 strings are
1975 /// perfectly valid for some OS.
1982 /// use std::path::Path;
1984 /// let path = Path::new("foo.txt");
1985 /// assert_eq!(path.to_str(), Some("foo.txt"));
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 #[must_use = "this returns the result of the operation, \
1989 without modifying the original"]
1991 pub fn to_str(&self) -> Option<&str> {
1995 /// Converts a `Path` to a [`Cow<str>`].
1997 /// Any non-Unicode sequences are replaced with
1998 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
2000 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
2004 /// Calling `to_string_lossy` on a `Path` with valid unicode:
2007 /// use std::path::Path;
2009 /// let path = Path::new("foo.txt");
2010 /// assert_eq!(path.to_string_lossy(), "foo.txt");
2013 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
2014 /// have returned `"fo�.txt"`.
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 #[must_use = "this returns the result of the operation, \
2017 without modifying the original"]
2019 pub fn to_string_lossy(&self) -> Cow<'_, str> {
2020 self.inner.to_string_lossy()
2023 /// Converts a `Path` to an owned [`PathBuf`].
2028 /// use std::path::Path;
2030 /// let path_buf = Path::new("foo.txt").to_path_buf();
2031 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
2033 #[rustc_conversion_suggestion]
2034 #[must_use = "this returns the result of the operation, \
2035 without modifying the original"]
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 pub fn to_path_buf(&self) -> PathBuf {
2038 PathBuf::from(self.inner.to_os_string())
2041 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
2042 /// the current directory.
2044 /// * On Unix, a path is absolute if it starts with the root, so
2045 /// `is_absolute` and [`has_root`] are equivalent.
2047 /// * On Windows, a path is absolute if it has a prefix and starts with the
2048 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
2053 /// use std::path::Path;
2055 /// assert!(!Path::new("foo.txt").is_absolute());
2058 /// [`has_root`]: Path::has_root
2059 #[stable(feature = "rust1", since = "1.0.0")]
2061 #[allow(deprecated)]
2062 pub fn is_absolute(&self) -> bool {
2063 if cfg!(target_os = "redox") {
2064 // FIXME: Allow Redox prefixes
2065 self.has_root() || has_redox_scheme(self.as_u8_slice())
2067 self.has_root() && (cfg!(any(unix, target_os = "wasi")) || self.prefix().is_some())
2071 /// Returns `true` if the `Path` is relative, i.e., not absolute.
2073 /// See [`is_absolute`]'s documentation for more details.
2078 /// use std::path::Path;
2080 /// assert!(Path::new("foo.txt").is_relative());
2083 /// [`is_absolute`]: Path::is_absolute
2084 #[stable(feature = "rust1", since = "1.0.0")]
2087 pub fn is_relative(&self) -> bool {
2091 fn prefix(&self) -> Option<Prefix<'_>> {
2092 self.components().prefix
2095 /// Returns `true` if the `Path` has a root.
2097 /// * On Unix, a path has a root if it begins with `/`.
2099 /// * On Windows, a path has a root if it:
2100 /// * has no prefix and begins with a separator, e.g., `\windows`
2101 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
2102 /// * has any non-disk prefix, e.g., `\\server\share`
2107 /// use std::path::Path;
2109 /// assert!(Path::new("/etc/passwd").has_root());
2111 #[stable(feature = "rust1", since = "1.0.0")]
2114 pub fn has_root(&self) -> bool {
2115 self.components().has_root()
2118 /// Returns the `Path` without its final component, if there is one.
2120 /// Returns [`None`] if the path terminates in a root or prefix.
2125 /// use std::path::Path;
2127 /// let path = Path::new("/foo/bar");
2128 /// let parent = path.parent().unwrap();
2129 /// assert_eq!(parent, Path::new("/foo"));
2131 /// let grand_parent = parent.parent().unwrap();
2132 /// assert_eq!(grand_parent, Path::new("/"));
2133 /// assert_eq!(grand_parent.parent(), None);
2135 #[stable(feature = "rust1", since = "1.0.0")]
2137 pub fn parent(&self) -> Option<&Path> {
2138 let mut comps = self.components();
2139 let comp = comps.next_back();
2140 comp.and_then(|p| match p {
2141 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
2142 Some(comps.as_path())
2148 /// Produces an iterator over `Path` and its ancestors.
2150 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2151 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2152 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2153 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2159 /// use std::path::Path;
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(), None);
2167 /// let mut ancestors = Path::new("../foo/bar").ancestors();
2168 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
2169 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
2170 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
2171 /// assert_eq!(ancestors.next(), Some(Path::new("")));
2172 /// assert_eq!(ancestors.next(), None);
2175 /// [`parent`]: Path::parent
2176 #[stable(feature = "path_ancestors", since = "1.28.0")]
2178 pub fn ancestors(&self) -> Ancestors<'_> {
2179 Ancestors { next: Some(&self) }
2182 /// Returns the final component of the `Path`, if there is one.
2184 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2185 /// is the directory name.
2187 /// Returns [`None`] if the path terminates in `..`.
2192 /// use std::path::Path;
2193 /// use std::ffi::OsStr;
2195 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2196 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2197 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2198 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2199 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2200 /// assert_eq!(None, Path::new("/").file_name());
2202 #[stable(feature = "rust1", since = "1.0.0")]
2204 pub fn file_name(&self) -> Option<&OsStr> {
2205 self.components().next_back().and_then(|p| match p {
2206 Component::Normal(p) => Some(p),
2211 /// Returns a path that, when joined onto `base`, yields `self`.
2215 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2216 /// returns `false`), returns [`Err`].
2218 /// [`starts_with`]: Path::starts_with
2223 /// use std::path::{Path, PathBuf};
2225 /// let path = Path::new("/test/haha/foo.txt");
2227 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2228 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2229 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2230 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2231 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2233 /// assert!(path.strip_prefix("test").is_err());
2234 /// assert!(path.strip_prefix("/haha").is_err());
2236 /// let prefix = PathBuf::from("/test/");
2237 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2239 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2240 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2244 self._strip_prefix(base.as_ref())
2247 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2248 iter_after(self.components(), base.components())
2249 .map(|c| c.as_path())
2250 .ok_or(StripPrefixError(()))
2253 /// Determines whether `base` is a prefix of `self`.
2255 /// Only considers whole path components to match.
2260 /// use std::path::Path;
2262 /// let path = Path::new("/etc/passwd");
2264 /// assert!(path.starts_with("/etc"));
2265 /// assert!(path.starts_with("/etc/"));
2266 /// assert!(path.starts_with("/etc/passwd"));
2267 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2268 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2270 /// assert!(!path.starts_with("/e"));
2271 /// assert!(!path.starts_with("/etc/passwd.txt"));
2273 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2275 #[stable(feature = "rust1", since = "1.0.0")]
2277 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2278 self._starts_with(base.as_ref())
2281 fn _starts_with(&self, base: &Path) -> bool {
2282 iter_after(self.components(), base.components()).is_some()
2285 /// Determines whether `child` is a suffix of `self`.
2287 /// Only considers whole path components to match.
2292 /// use std::path::Path;
2294 /// let path = Path::new("/etc/resolv.conf");
2296 /// assert!(path.ends_with("resolv.conf"));
2297 /// assert!(path.ends_with("etc/resolv.conf"));
2298 /// assert!(path.ends_with("/etc/resolv.conf"));
2300 /// assert!(!path.ends_with("/resolv.conf"));
2301 /// assert!(!path.ends_with("conf")); // use .extension() instead
2303 #[stable(feature = "rust1", since = "1.0.0")]
2305 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2306 self._ends_with(child.as_ref())
2309 fn _ends_with(&self, child: &Path) -> bool {
2310 iter_after(self.components().rev(), child.components().rev()).is_some()
2313 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2315 /// [`self.file_name`]: Path::file_name
2319 /// * [`None`], if there is no file name;
2320 /// * The entire file name if there is no embedded `.`;
2321 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2322 /// * Otherwise, the portion of the file name before the final `.`
2327 /// use std::path::Path;
2329 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2330 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2334 /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
2335 /// before the *first* `.`
2337 /// [`Path::file_prefix`]: Path::file_prefix
2339 #[stable(feature = "rust1", since = "1.0.0")]
2341 pub fn file_stem(&self) -> Option<&OsStr> {
2342 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2345 /// Extracts the prefix of [`self.file_name`].
2349 /// * [`None`], if there is no file name;
2350 /// * The entire file name if there is no embedded `.`;
2351 /// * The portion of the file name before the first non-beginning `.`;
2352 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2353 /// * The portion of the file name before the second `.` if the file name begins with `.`
2355 /// [`self.file_name`]: Path::file_name
2360 /// # #![feature(path_file_prefix)]
2361 /// use std::path::Path;
2363 /// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
2364 /// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
2368 /// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
2369 /// before the *last* `.`
2371 /// [`Path::file_stem`]: Path::file_stem
2373 #[unstable(feature = "path_file_prefix", issue = "86319")]
2375 pub fn file_prefix(&self) -> Option<&OsStr> {
2376 self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before))
2379 /// Extracts the extension of [`self.file_name`], if possible.
2381 /// The extension is:
2383 /// * [`None`], if there is no file name;
2384 /// * [`None`], if there is no embedded `.`;
2385 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2386 /// * Otherwise, the portion of the file name after the final `.`
2388 /// [`self.file_name`]: Path::file_name
2393 /// use std::path::Path;
2395 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2396 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2398 #[stable(feature = "rust1", since = "1.0.0")]
2400 pub fn extension(&self) -> Option<&OsStr> {
2401 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
2404 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2406 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2411 /// use std::path::{Path, PathBuf};
2413 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2415 #[stable(feature = "rust1", since = "1.0.0")]
2417 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2418 self._join(path.as_ref())
2421 fn _join(&self, path: &Path) -> PathBuf {
2422 let mut buf = self.to_path_buf();
2427 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2429 /// See [`PathBuf::set_file_name`] for more details.
2434 /// use std::path::{Path, PathBuf};
2436 /// let path = Path::new("/tmp/foo.txt");
2437 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2439 /// let path = Path::new("/tmp");
2440 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2442 #[stable(feature = "rust1", since = "1.0.0")]
2444 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2445 self._with_file_name(file_name.as_ref())
2448 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2449 let mut buf = self.to_path_buf();
2450 buf.set_file_name(file_name);
2454 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2456 /// See [`PathBuf::set_extension`] for more details.
2461 /// use std::path::{Path, PathBuf};
2463 /// let path = Path::new("foo.rs");
2464 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2466 /// let path = Path::new("foo.tar.gz");
2467 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2468 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2469 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2473 self._with_extension(extension.as_ref())
2476 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2477 let mut buf = self.to_path_buf();
2478 buf.set_extension(extension);
2482 /// Produces an iterator over the [`Component`]s of the path.
2484 /// When parsing the path, there is a small amount of normalization:
2486 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2487 /// `a` and `b` as components.
2489 /// * Occurrences of `.` are normalized away, except if they are at the
2490 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2491 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2492 /// an additional [`CurDir`] component.
2494 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2496 /// Note that no other normalization takes place; in particular, `a/c`
2497 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2498 /// is a symbolic link (so its parent isn't `a`).
2503 /// use std::path::{Path, Component};
2504 /// use std::ffi::OsStr;
2506 /// let mut components = Path::new("/tmp/foo.txt").components();
2508 /// assert_eq!(components.next(), Some(Component::RootDir));
2509 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2510 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2511 /// assert_eq!(components.next(), None)
2514 /// [`CurDir`]: Component::CurDir
2515 #[stable(feature = "rust1", since = "1.0.0")]
2516 pub fn components(&self) -> Components<'_> {
2517 let prefix = parse_prefix(self.as_os_str());
2519 path: self.as_u8_slice(),
2521 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2522 || has_redox_scheme(self.as_u8_slice()),
2523 front: State::Prefix,
2528 /// Produces an iterator over the path's components viewed as [`OsStr`]
2531 /// For more information about the particulars of how the path is separated
2532 /// into components, see [`components`].
2534 /// [`components`]: Path::components
2539 /// use std::path::{self, Path};
2540 /// use std::ffi::OsStr;
2542 /// let mut it = Path::new("/tmp/foo.txt").iter();
2543 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2544 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2545 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2546 /// assert_eq!(it.next(), None)
2548 #[stable(feature = "rust1", since = "1.0.0")]
2550 pub fn iter(&self) -> Iter<'_> {
2551 Iter { inner: self.components() }
2554 /// Returns an object that implements [`Display`] for safely printing paths
2555 /// that may contain non-Unicode data. This may perform lossy conversion,
2556 /// depending on the platform. If you would like an implementation which
2557 /// escapes the path please use [`Debug`] instead.
2559 /// [`Display`]: fmt::Display
2564 /// use std::path::Path;
2566 /// let path = Path::new("/tmp/foo.rs");
2568 /// println!("{}", path.display());
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 #[must_use = "this does not display the path, \
2572 it returns an object that can be displayed"]
2574 pub fn display(&self) -> Display<'_> {
2575 Display { path: self }
2578 /// Queries the file system to get information about a file, directory, etc.
2580 /// This function will traverse symbolic links to query information about the
2581 /// destination file.
2583 /// This is an alias to [`fs::metadata`].
2588 /// use std::path::Path;
2590 /// let path = Path::new("/Minas/tirith");
2591 /// let metadata = path.metadata().expect("metadata call failed");
2592 /// println!("{:?}", metadata.file_type());
2594 #[stable(feature = "path_ext", since = "1.5.0")]
2596 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2600 /// Queries the metadata about a file without following symlinks.
2602 /// This is an alias to [`fs::symlink_metadata`].
2607 /// use std::path::Path;
2609 /// let path = Path::new("/Minas/tirith");
2610 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2611 /// println!("{:?}", metadata.file_type());
2613 #[stable(feature = "path_ext", since = "1.5.0")]
2615 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2616 fs::symlink_metadata(self)
2619 /// Returns the canonical, absolute form of the path with all intermediate
2620 /// components normalized and symbolic links resolved.
2622 /// This is an alias to [`fs::canonicalize`].
2627 /// use std::path::{Path, PathBuf};
2629 /// let path = Path::new("/foo/test/../test/bar.rs");
2630 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2632 #[stable(feature = "path_ext", since = "1.5.0")]
2634 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2635 fs::canonicalize(self)
2638 /// Reads a symbolic link, returning the file that the link points to.
2640 /// This is an alias to [`fs::read_link`].
2645 /// use std::path::Path;
2647 /// let path = Path::new("/laputa/sky_castle.rs");
2648 /// let path_link = path.read_link().expect("read_link call failed");
2650 #[stable(feature = "path_ext", since = "1.5.0")]
2652 pub fn read_link(&self) -> io::Result<PathBuf> {
2656 /// Returns an iterator over the entries within a directory.
2658 /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. New
2659 /// errors may be encountered after an iterator is initially constructed.
2661 /// This is an alias to [`fs::read_dir`].
2666 /// use std::path::Path;
2668 /// let path = Path::new("/laputa");
2669 /// for entry in path.read_dir().expect("read_dir call failed") {
2670 /// if let Ok(entry) = entry {
2671 /// println!("{:?}", entry.path());
2675 #[stable(feature = "path_ext", since = "1.5.0")]
2677 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2681 /// Returns `true` if the path points at an existing entity.
2683 /// This function will traverse symbolic links to query information about the
2684 /// destination file.
2686 /// If you cannot access the metadata of the file, e.g. because of a
2687 /// permission error or broken symbolic links, this will return `false`.
2692 /// use std::path::Path;
2693 /// assert!(!Path::new("does_not_exist.txt").exists());
2698 /// This is a convenience function that coerces errors to false. If you want to
2699 /// check errors, call [`fs::metadata`].
2700 #[stable(feature = "path_ext", since = "1.5.0")]
2703 pub fn exists(&self) -> bool {
2704 fs::metadata(self).is_ok()
2707 /// Returns `Ok(true)` if the path points at an existing entity.
2709 /// This function will traverse symbolic links to query information about the
2710 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2712 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2713 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2714 /// denied on some of the parent directories.)
2719 /// #![feature(path_try_exists)]
2721 /// use std::path::Path;
2722 /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2723 /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2725 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2727 #[unstable(feature = "path_try_exists", issue = "83186")]
2729 pub fn try_exists(&self) -> io::Result<bool> {
2730 fs::try_exists(self)
2733 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2735 /// This function will traverse symbolic links to query information about the
2736 /// destination file.
2738 /// If you cannot access the metadata of the file, e.g. because of a
2739 /// permission error or broken symbolic links, this will return `false`.
2744 /// use std::path::Path;
2745 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2746 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2751 /// This is a convenience function that coerces errors to false. If you want to
2752 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2753 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2755 /// When the goal is simply to read from (or write to) the source, the most
2756 /// reliable way to test the source can be read (or written to) is to open
2757 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2758 /// a Unix-like system for example. See [`fs::File::open`] or
2759 /// [`fs::OpenOptions::open`] for more information.
2760 #[stable(feature = "path_ext", since = "1.5.0")]
2762 pub fn is_file(&self) -> bool {
2763 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2766 /// Returns `true` if the path exists on disk and is pointing at a directory.
2768 /// This function will traverse symbolic links to query information about the
2769 /// destination file.
2771 /// If you cannot access the metadata of the file, e.g. because of a
2772 /// permission error or broken symbolic links, this will return `false`.
2777 /// use std::path::Path;
2778 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2779 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2784 /// This is a convenience function that coerces errors to false. If you want to
2785 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2786 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2787 #[stable(feature = "path_ext", since = "1.5.0")]
2789 pub fn is_dir(&self) -> bool {
2790 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2793 /// Returns `true` if the path exists on disk and is pointing at a symbolic link.
2795 /// This function will not traverse symbolic links.
2796 /// In case of a broken symbolic link this will also return true.
2798 /// If you cannot access the directory containing the file, e.g., because of a
2799 /// permission error, this will return false.
2803 #[cfg_attr(unix, doc = "```no_run")]
2804 #[cfg_attr(not(unix), doc = "```ignore")]
2805 /// use std::path::Path;
2806 /// use std::os::unix::fs::symlink;
2808 /// let link_path = Path::new("link");
2809 /// symlink("/origin_does_not_exists/", link_path).unwrap();
2810 /// assert_eq!(link_path.is_symlink(), true);
2811 /// assert_eq!(link_path.exists(), false);
2816 /// This is a convenience function that coerces errors to false. If you want to
2817 /// check errors, call [`fs::symlink_metadata`] and handle its [`Result`]. Then call
2818 /// [`fs::Metadata::is_symlink`] if it was [`Ok`].
2820 #[stable(feature = "is_symlink", since = "1.58.0")]
2821 pub fn is_symlink(&self) -> bool {
2822 fs::symlink_metadata(self).map(|m| m.is_symlink()).unwrap_or(false)
2825 /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
2827 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2828 #[must_use = "`self` will be dropped if the result is not used"]
2829 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2830 let rw = Box::into_raw(self) as *mut OsStr;
2831 let inner = unsafe { Box::from_raw(rw) };
2832 PathBuf { inner: OsString::from(inner) }
2836 #[stable(feature = "rust1", since = "1.0.0")]
2837 impl AsRef<OsStr> for Path {
2839 fn as_ref(&self) -> &OsStr {
2844 #[stable(feature = "rust1", since = "1.0.0")]
2845 impl fmt::Debug for Path {
2846 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2847 fmt::Debug::fmt(&self.inner, formatter)
2851 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2853 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2854 /// [`Display`] trait in a way that mitigates that. It is created by the
2855 /// [`display`](Path::display) method on [`Path`]. This may perform lossy
2856 /// conversion, depending on the platform. If you would like an implementation
2857 /// which escapes the path please use [`Debug`] instead.
2862 /// use std::path::Path;
2864 /// let path = Path::new("/tmp/foo.rs");
2866 /// println!("{}", path.display());
2869 /// [`Display`]: fmt::Display
2870 /// [`format!`]: crate::format
2871 #[stable(feature = "rust1", since = "1.0.0")]
2872 pub struct Display<'a> {
2876 #[stable(feature = "rust1", since = "1.0.0")]
2877 impl fmt::Debug for Display<'_> {
2878 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2879 fmt::Debug::fmt(&self.path, f)
2883 #[stable(feature = "rust1", since = "1.0.0")]
2884 impl fmt::Display for Display<'_> {
2885 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2886 self.path.inner.display(f)
2890 #[stable(feature = "rust1", since = "1.0.0")]
2891 impl cmp::PartialEq for Path {
2893 fn eq(&self, other: &Path) -> bool {
2894 self.components() == other.components()
2898 #[stable(feature = "rust1", since = "1.0.0")]
2899 impl Hash for Path {
2900 fn hash<H: Hasher>(&self, h: &mut H) {
2901 let bytes = self.as_u8_slice();
2902 let prefix_len = match parse_prefix(&self.inner) {
2909 let bytes = &bytes[prefix_len..];
2911 let mut component_start = 0;
2912 let mut bytes_hashed = 0;
2914 for i in 0..bytes.len() {
2915 if is_sep_byte(bytes[i]) {
2916 if i > component_start {
2917 let to_hash = &bytes[component_start..i];
2919 bytes_hashed += to_hash.len();
2922 // skip over separator and optionally a following CurDir item
2923 // since components() would normalize these away
2924 component_start = i + match bytes[i..] {
2925 [_, b'.', b'/', ..] | [_, b'.'] => 2,
2931 if component_start < bytes.len() {
2932 let to_hash = &bytes[component_start..];
2934 bytes_hashed += to_hash.len();
2937 h.write_usize(bytes_hashed);
2941 #[stable(feature = "rust1", since = "1.0.0")]
2942 impl cmp::Eq for Path {}
2944 #[stable(feature = "rust1", since = "1.0.0")]
2945 impl cmp::PartialOrd for Path {
2947 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2948 Some(compare_components(self.components(), other.components()))
2952 #[stable(feature = "rust1", since = "1.0.0")]
2953 impl cmp::Ord for Path {
2955 fn cmp(&self, other: &Path) -> cmp::Ordering {
2956 compare_components(self.components(), other.components())
2960 #[stable(feature = "rust1", since = "1.0.0")]
2961 impl AsRef<Path> for Path {
2963 fn as_ref(&self) -> &Path {
2968 #[stable(feature = "rust1", since = "1.0.0")]
2969 impl AsRef<Path> for OsStr {
2971 fn as_ref(&self) -> &Path {
2976 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2977 impl AsRef<Path> for Cow<'_, OsStr> {
2979 fn as_ref(&self) -> &Path {
2984 #[stable(feature = "rust1", since = "1.0.0")]
2985 impl AsRef<Path> for OsString {
2987 fn as_ref(&self) -> &Path {
2992 #[stable(feature = "rust1", since = "1.0.0")]
2993 impl AsRef<Path> for str {
2995 fn as_ref(&self) -> &Path {
3000 #[stable(feature = "rust1", since = "1.0.0")]
3001 impl AsRef<Path> for String {
3003 fn as_ref(&self) -> &Path {
3008 #[stable(feature = "rust1", since = "1.0.0")]
3009 impl AsRef<Path> for PathBuf {
3011 fn as_ref(&self) -> &Path {
3016 #[stable(feature = "path_into_iter", since = "1.6.0")]
3017 impl<'a> IntoIterator for &'a PathBuf {
3018 type Item = &'a OsStr;
3019 type IntoIter = Iter<'a>;
3021 fn into_iter(self) -> Iter<'a> {
3026 #[stable(feature = "path_into_iter", since = "1.6.0")]
3027 impl<'a> IntoIterator for &'a Path {
3028 type Item = &'a OsStr;
3029 type IntoIter = Iter<'a>;
3031 fn into_iter(self) -> Iter<'a> {
3036 macro_rules! impl_cmp {
3037 ($lhs:ty, $rhs: ty) => {
3038 #[stable(feature = "partialeq_path", since = "1.6.0")]
3039 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3041 fn eq(&self, other: &$rhs) -> bool {
3042 <Path as PartialEq>::eq(self, other)
3046 #[stable(feature = "partialeq_path", since = "1.6.0")]
3047 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3049 fn eq(&self, other: &$lhs) -> bool {
3050 <Path as PartialEq>::eq(self, other)
3054 #[stable(feature = "cmp_path", since = "1.8.0")]
3055 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3057 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3058 <Path as PartialOrd>::partial_cmp(self, other)
3062 #[stable(feature = "cmp_path", since = "1.8.0")]
3063 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3065 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3066 <Path as PartialOrd>::partial_cmp(self, other)
3072 impl_cmp!(PathBuf, Path);
3073 impl_cmp!(PathBuf, &'a Path);
3074 impl_cmp!(Cow<'a, Path>, Path);
3075 impl_cmp!(Cow<'a, Path>, &'b Path);
3076 impl_cmp!(Cow<'a, Path>, PathBuf);
3078 macro_rules! impl_cmp_os_str {
3079 ($lhs:ty, $rhs: ty) => {
3080 #[stable(feature = "cmp_path", since = "1.8.0")]
3081 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3083 fn eq(&self, other: &$rhs) -> bool {
3084 <Path as PartialEq>::eq(self, other.as_ref())
3088 #[stable(feature = "cmp_path", since = "1.8.0")]
3089 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3091 fn eq(&self, other: &$lhs) -> bool {
3092 <Path as PartialEq>::eq(self.as_ref(), other)
3096 #[stable(feature = "cmp_path", since = "1.8.0")]
3097 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3099 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3100 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
3104 #[stable(feature = "cmp_path", since = "1.8.0")]
3105 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3107 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3108 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
3114 impl_cmp_os_str!(PathBuf, OsStr);
3115 impl_cmp_os_str!(PathBuf, &'a OsStr);
3116 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
3117 impl_cmp_os_str!(PathBuf, OsString);
3118 impl_cmp_os_str!(Path, OsStr);
3119 impl_cmp_os_str!(Path, &'a OsStr);
3120 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
3121 impl_cmp_os_str!(Path, OsString);
3122 impl_cmp_os_str!(&'a Path, OsStr);
3123 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
3124 impl_cmp_os_str!(&'a Path, OsString);
3125 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
3126 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
3127 impl_cmp_os_str!(Cow<'a, Path>, OsString);
3129 #[stable(since = "1.7.0", feature = "strip_prefix")]
3130 impl fmt::Display for StripPrefixError {
3131 #[allow(deprecated, deprecated_in_future)]
3132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3133 self.description().fmt(f)
3137 #[stable(since = "1.7.0", feature = "strip_prefix")]
3138 impl Error for StripPrefixError {
3139 #[allow(deprecated)]
3140 fn description(&self) -> &str {