1 // ignore-tidy-filelength
3 //! Cross-platform path manipulation.
5 //! This module provides two types, [`PathBuf`] and [`Path`] (akin to [`String`]
6 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
7 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
8 //! on strings according to the local platform's path syntax.
10 //! Paths can be parsed into [`Component`]s by iterating over the structure
11 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
12 //! correspond to the substrings between path separators (`/` or `\`). You can
13 //! reconstruct an equivalent path from components with the [`push`] method on
14 //! [`PathBuf`]; note that the paths may differ syntactically by the
15 //! normalization described in the documentation for the [`components`] method.
19 //! Path manipulation includes both parsing components from slices and building
22 //! To parse a path, you can create a [`Path`] slice from a [`str`]
23 //! slice and start asking questions:
26 //! use std::path::Path;
27 //! use std::ffi::OsStr;
29 //! let path = Path::new("/tmp/foo/bar.txt");
31 //! let parent = path.parent();
32 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
34 //! let file_stem = path.file_stem();
35 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
37 //! let extension = path.extension();
38 //! assert_eq!(extension, Some(OsStr::new("txt")));
41 //! To build or modify paths, use [`PathBuf`]:
44 //! use std::path::PathBuf;
46 //! // This way works...
47 //! let mut path = PathBuf::from("c:\\");
49 //! path.push("windows");
50 //! path.push("system32");
52 //! path.set_extension("dll");
54 //! // ... but push is best used if you don't know everything up
55 //! // front. If you do, this way is better:
56 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
59 //! [`components`]: Path::components
60 //! [`push`]: PathBuf::push
62 #![stable(feature = "rust1", since = "1.0.0")]
64 use crate::borrow::{Borrow, Cow};
66 use crate::error::Error;
69 use crate::hash::{Hash, Hasher};
71 use crate::iter::{self, FusedIterator};
72 use crate::ops::{self, Deref};
74 use crate::str::FromStr;
77 use crate::ffi::{OsStr, OsString};
79 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
81 ////////////////////////////////////////////////////////////////////////////////
83 ////////////////////////////////////////////////////////////////////////////////
85 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
86 // taking advantage of the fact that OsStr always encodes ASCII characters
87 // as-is. Eventually, this transmutation should be replaced by direct uses of
88 // OsStr APIs for parsing, but it will take a while for those to become
91 ////////////////////////////////////////////////////////////////////////////////
93 ////////////////////////////////////////////////////////////////////////////////
95 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
97 /// Windows uses a variety of path prefix styles, including references to drive
98 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
99 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
100 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
101 /// no normalization is performed.
106 /// use std::path::{Component, Path, Prefix};
107 /// use std::path::Prefix::*;
108 /// use std::ffi::OsStr;
110 /// fn get_path_prefix(s: &str) -> Prefix {
111 /// let path = Path::new(s);
112 /// match path.components().next().unwrap() {
113 /// Component::Prefix(prefix_component) => prefix_component.kind(),
118 /// # if cfg!(windows) {
119 /// assert_eq!(Verbatim(OsStr::new("pictures")),
120 /// get_path_prefix(r"\\?\pictures\kittens"));
121 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
122 /// get_path_prefix(r"\\?\UNC\server\share"));
123 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
124 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
125 /// get_path_prefix(r"\\.\BrainInterface"));
126 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
127 /// get_path_prefix(r"\\server\share"));
128 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
131 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub enum Prefix<'a> {
134 /// Verbatim prefix, e.g., `\\?\cat_pics`.
136 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
138 #[stable(feature = "rust1", since = "1.0.0")]
139 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
141 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
142 /// e.g., `\\?\UNC\server\share`.
144 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
145 /// server's hostname and a share name.
146 #[stable(feature = "rust1", since = "1.0.0")]
148 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
149 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
152 /// Verbatim disk prefix, e.g., `\\?\C:`.
154 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
155 /// drive letter and `:`.
156 #[stable(feature = "rust1", since = "1.0.0")]
157 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
159 /// Device namespace prefix, e.g., `\\.\COM42`.
161 /// Device namespace prefixes consist of `\\.\` immediately followed by the
163 #[stable(feature = "rust1", since = "1.0.0")]
164 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
166 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
167 /// `\\server\share`.
169 /// UNC prefixes consist of the server's hostname and a share name.
170 #[stable(feature = "rust1", since = "1.0.0")]
172 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
173 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
176 /// Prefix `C:` for the given disk drive.
177 #[stable(feature = "rust1", since = "1.0.0")]
178 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
181 impl<'a> Prefix<'a> {
183 fn len(&self) -> usize {
185 fn os_str_len(s: &OsStr) -> usize {
186 os_str_as_u8_slice(s).len()
189 Verbatim(x) => 4 + os_str_len(x),
190 VerbatimUNC(x, y) => {
191 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
193 VerbatimDisk(_) => 6,
194 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
195 DeviceNS(x) => 4 + os_str_len(x),
200 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
205 /// use std::path::Prefix::*;
206 /// use std::ffi::OsStr;
208 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
209 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
210 /// assert!(VerbatimDisk(b'C').is_verbatim());
211 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
212 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
213 /// assert!(!Disk(b'C').is_verbatim());
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn is_verbatim(&self) -> bool {
219 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
223 fn is_drive(&self) -> bool {
224 matches!(*self, Prefix::Disk(_))
228 fn has_implicit_root(&self) -> bool {
233 ////////////////////////////////////////////////////////////////////////////////
234 // Exposed parsing helpers
235 ////////////////////////////////////////////////////////////////////////////////
237 /// Determines whether the character is one of the permitted path
238 /// separators for the current platform.
245 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
246 /// assert!(!path::is_separator('❤'));
248 #[stable(feature = "rust1", since = "1.0.0")]
249 pub fn is_separator(c: char) -> bool {
250 c.is_ascii() && is_sep_byte(c as u8)
253 /// The primary separator of path components for the current platform.
255 /// For example, `/` on Unix and `\` on Windows.
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
259 ////////////////////////////////////////////////////////////////////////////////
261 ////////////////////////////////////////////////////////////////////////////////
263 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
264 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
265 // `iter` after having exhausted `prefix`.
266 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
268 I: Iterator<Item = Component<'a>> + Clone,
269 J: Iterator<Item = Component<'b>>,
272 let mut iter_next = iter.clone();
273 match (iter_next.next(), prefix.next()) {
274 (Some(ref x), Some(ref y)) if x == y => (),
275 (Some(_), Some(_)) => return None,
276 (Some(_), None) => return Some(iter),
277 (None, None) => return Some(iter),
278 (None, Some(_)) => return None,
284 // See note at the top of this module to understand why these are used:
286 // These casts are safe as OsStr is internally a wrapper around [u8] on all
289 // Note that currently this relies on the special knowledge that libstd has;
290 // these types are single-element structs but are not marked repr(transparent)
291 // or repr(C) which would make these casts allowable outside std.
292 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
293 unsafe { &*(s as *const OsStr as *const [u8]) }
295 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
296 &*(s as *const [u8] as *const OsStr)
299 // Detect scheme on Redox
300 fn has_redox_scheme(s: &[u8]) -> bool {
301 cfg!(target_os = "redox") && s.contains(&b':')
304 ////////////////////////////////////////////////////////////////////////////////
305 // Cross-platform, iterator-independent parsing
306 ////////////////////////////////////////////////////////////////////////////////
308 /// Says whether the first byte after the prefix is a separator.
309 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
310 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
311 !path.is_empty() && is_sep_byte(path[0])
314 // basic workhorse for splitting stem and extension
315 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
317 if os_str_as_u8_slice(file) == b".." {
318 return (Some(file), None);
321 // The unsafety here stems from converting between &OsStr and &[u8]
322 // and back. This is safe to do because (1) we only look at ASCII
323 // contents of the encoding and (2) new &OsStr values are produced
324 // only from ASCII-bounded slices of existing &OsStr values.
326 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
327 let after = iter.next();
328 let before = iter.next();
329 if before == Some(b"") {
332 (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s)))
337 ////////////////////////////////////////////////////////////////////////////////
338 // The core iterators
339 ////////////////////////////////////////////////////////////////////////////////
341 /// Component parsing works by a double-ended state machine; the cursors at the
342 /// front and back of the path each keep track of what parts of the path have
343 /// been consumed so far.
345 /// Going front to back, a path is made up of a prefix, a starting
346 /// directory component, and a body (of normal components)
347 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
350 StartDir = 1, // / or . or nothing
351 Body = 2, // foo/bar/baz
355 /// A structure wrapping a Windows path prefix as well as its unparsed string
358 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
359 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
360 /// returned by [`as_os_str`].
362 /// Instances of this `struct` can be obtained by matching against the
363 /// [`Prefix` variant] on [`Component`].
365 /// Does not occur on Unix.
370 /// # if cfg!(windows) {
371 /// use std::path::{Component, Path, Prefix};
372 /// use std::ffi::OsStr;
374 /// let path = Path::new(r"c:\you\later\");
375 /// match path.components().next().unwrap() {
376 /// Component::Prefix(prefix_component) => {
377 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
378 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
380 /// _ => unreachable!(),
385 /// [`as_os_str`]: PrefixComponent::as_os_str
386 /// [`kind`]: PrefixComponent::kind
387 /// [`Prefix` variant]: Component::Prefix
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[derive(Copy, Clone, Eq, Debug)]
390 pub struct PrefixComponent<'a> {
391 /// The prefix as an unparsed `OsStr` slice.
394 /// The parsed prefix data.
398 impl<'a> PrefixComponent<'a> {
399 /// Returns the parsed prefix data.
401 /// See [`Prefix`]'s documentation for more information on the different
402 /// kinds of prefixes.
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn kind(&self) -> Prefix<'a> {
408 /// Returns the raw [`OsStr`] slice for this prefix.
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn as_os_str(&self) -> &'a OsStr {
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
417 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
418 cmp::PartialEq::eq(&self.parsed, &other.parsed)
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
424 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
425 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl cmp::Ord for PrefixComponent<'_> {
431 fn cmp(&self, other: &Self) -> cmp::Ordering {
432 cmp::Ord::cmp(&self.parsed, &other.parsed)
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl Hash for PrefixComponent<'_> {
438 fn hash<H: Hasher>(&self, h: &mut H) {
443 /// A single component of a path.
445 /// A `Component` roughly corresponds to a substring between path separators
448 /// This `enum` is created by iterating over [`Components`], which in turn is
449 /// created by the [`components`][`Path::components`] method on [`Path`].
454 /// use std::path::{Component, Path};
456 /// let path = Path::new("/tmp/foo/bar.txt");
457 /// let components = path.components().collect::<Vec<_>>();
458 /// assert_eq!(&components, &[
459 /// Component::RootDir,
460 /// Component::Normal("tmp".as_ref()),
461 /// Component::Normal("foo".as_ref()),
462 /// Component::Normal("bar.txt".as_ref()),
465 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub enum Component<'a> {
468 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
470 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
473 /// Does not occur on Unix.
474 #[stable(feature = "rust1", since = "1.0.0")]
475 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
477 /// The root directory component, appears after any prefix and before anything else.
479 /// It represents a separator that designates that a path starts from root.
480 #[stable(feature = "rust1", since = "1.0.0")]
483 /// A reference to the current directory, i.e., `.`.
484 #[stable(feature = "rust1", since = "1.0.0")]
487 /// A reference to the parent directory, i.e., `..`.
488 #[stable(feature = "rust1", since = "1.0.0")]
491 /// A normal component, e.g., `a` and `b` in `a/b`.
493 /// This variant is the most common one, it represents references to files
495 #[stable(feature = "rust1", since = "1.0.0")]
496 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
499 impl<'a> Component<'a> {
500 /// Extracts the underlying [`OsStr`] slice.
505 /// use std::path::Path;
507 /// let path = Path::new("./tmp/foo/bar.txt");
508 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
509 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn as_os_str(self) -> &'a OsStr {
514 Component::Prefix(p) => p.as_os_str(),
515 Component::RootDir => OsStr::new(MAIN_SEP_STR),
516 Component::CurDir => OsStr::new("."),
517 Component::ParentDir => OsStr::new(".."),
518 Component::Normal(path) => path,
523 #[stable(feature = "rust1", since = "1.0.0")]
524 impl AsRef<OsStr> for Component<'_> {
525 fn as_ref(&self) -> &OsStr {
530 #[stable(feature = "path_component_asref", since = "1.25.0")]
531 impl AsRef<Path> for Component<'_> {
532 fn as_ref(&self) -> &Path {
533 self.as_os_str().as_ref()
537 /// An iterator over the [`Component`]s of a [`Path`].
539 /// This `struct` is created by the [`components`] method on [`Path`].
540 /// See its documentation for more.
545 /// use std::path::Path;
547 /// let path = Path::new("/tmp/foo/bar.txt");
549 /// for component in path.components() {
550 /// println!("{:?}", component);
554 /// [`components`]: Path::components
556 #[stable(feature = "rust1", since = "1.0.0")]
557 pub struct Components<'a> {
558 // The path left to parse components from
561 // The prefix as it was originally parsed, if any
562 prefix: Option<Prefix<'a>>,
564 // true if path *physically* has a root separator; for most Windows
565 // prefixes, it may have a "logical" rootseparator for the purposes of
566 // normalization, e.g., \\server\share == \\server\share\.
567 has_physical_root: bool,
569 // The iterator is double-ended, and these two states keep track of what has
570 // been produced from either end
575 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
577 /// This `struct` is created by the [`iter`] method on [`Path`].
578 /// See its documentation for more.
580 /// [`iter`]: Path::iter
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub struct Iter<'a> {
584 inner: Components<'a>,
587 #[stable(feature = "path_components_debug", since = "1.13.0")]
588 impl fmt::Debug for Components<'_> {
589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590 struct DebugHelper<'a>(&'a Path);
592 impl fmt::Debug for DebugHelper<'_> {
593 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594 f.debug_list().entries(self.0.components()).finish()
598 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
602 impl<'a> Components<'a> {
603 // how long is the prefix, if any?
605 fn prefix_len(&self) -> usize {
606 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
610 fn prefix_verbatim(&self) -> bool {
611 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
614 /// how much of the prefix is left from the point of view of iteration?
616 fn prefix_remaining(&self) -> usize {
617 if self.front == State::Prefix { self.prefix_len() } else { 0 }
620 // Given the iteration so far, how much of the pre-State::Body path is left?
622 fn len_before_body(&self) -> usize {
623 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
624 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
625 self.prefix_remaining() + root + cur_dir
628 // is the iteration complete?
630 fn finished(&self) -> bool {
631 self.front == State::Done || self.back == State::Done || self.front > self.back
635 fn is_sep_byte(&self, b: u8) -> bool {
636 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
639 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
644 /// use std::path::Path;
646 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
647 /// components.next();
648 /// components.next();
650 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn as_path(&self) -> &'a Path {
654 let mut comps = self.clone();
655 if comps.front == State::Body {
658 if comps.back == State::Body {
661 unsafe { Path::from_u8_slice(comps.path) }
664 /// Is the *original* path rooted?
665 fn has_root(&self) -> bool {
666 if self.has_physical_root {
669 if let Some(p) = self.prefix {
670 if p.has_implicit_root() {
677 /// Should the normalized path include a leading . ?
678 fn include_cur_dir(&self) -> bool {
682 let mut iter = self.path[self.prefix_len()..].iter();
683 match (iter.next(), iter.next()) {
684 (Some(&b'.'), None) => true,
685 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
690 // parse a given byte sequence into the corresponding path component
691 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
693 b"." if self.prefix_verbatim() => Some(Component::CurDir),
694 b"." => None, // . components are normalized away, except at
695 // the beginning of a path, which is treated
696 // separately via `include_cur_dir`
697 b".." => Some(Component::ParentDir),
699 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
703 // parse a component from the left, saying how many bytes to consume to
704 // remove the component
705 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
706 debug_assert!(self.front == State::Body);
707 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
708 None => (0, self.path),
709 Some(i) => (1, &self.path[..i]),
711 (comp.len() + extra, self.parse_single_component(comp))
714 // parse a component from the right, saying how many bytes to consume to
715 // remove the component
716 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
717 debug_assert!(self.back == State::Body);
718 let start = self.len_before_body();
719 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
720 None => (0, &self.path[start..]),
721 Some(i) => (1, &self.path[start + i + 1..]),
723 (comp.len() + extra, self.parse_single_component(comp))
726 // trim away repeated separators (i.e., empty components) on the left
727 fn trim_left(&mut self) {
728 while !self.path.is_empty() {
729 let (size, comp) = self.parse_next_component();
733 self.path = &self.path[size..];
738 // trim away repeated separators (i.e., empty components) on the right
739 fn trim_right(&mut self) {
740 while self.path.len() > self.len_before_body() {
741 let (size, comp) = self.parse_next_component_back();
745 self.path = &self.path[..self.path.len() - size];
751 #[stable(feature = "rust1", since = "1.0.0")]
752 impl AsRef<Path> for Components<'_> {
753 fn as_ref(&self) -> &Path {
758 #[stable(feature = "rust1", since = "1.0.0")]
759 impl AsRef<OsStr> for Components<'_> {
760 fn as_ref(&self) -> &OsStr {
761 self.as_path().as_os_str()
765 #[stable(feature = "path_iter_debug", since = "1.13.0")]
766 impl fmt::Debug for Iter<'_> {
767 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
768 struct DebugHelper<'a>(&'a Path);
770 impl fmt::Debug for DebugHelper<'_> {
771 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772 f.debug_list().entries(self.0.iter()).finish()
776 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
781 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
786 /// use std::path::Path;
788 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
792 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub fn as_path(&self) -> &'a Path {
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl AsRef<Path> for Iter<'_> {
802 fn as_ref(&self) -> &Path {
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl AsRef<OsStr> for Iter<'_> {
809 fn as_ref(&self) -> &OsStr {
810 self.as_path().as_os_str()
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a> Iterator for Iter<'a> {
816 type Item = &'a OsStr;
818 fn next(&mut self) -> Option<&'a OsStr> {
819 self.inner.next().map(Component::as_os_str)
823 #[stable(feature = "rust1", since = "1.0.0")]
824 impl<'a> DoubleEndedIterator for Iter<'a> {
825 fn next_back(&mut self) -> Option<&'a OsStr> {
826 self.inner.next_back().map(Component::as_os_str)
830 #[stable(feature = "fused", since = "1.26.0")]
831 impl FusedIterator for Iter<'_> {}
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<'a> Iterator for Components<'a> {
835 type Item = Component<'a>;
837 fn next(&mut self) -> Option<Component<'a>> {
838 while !self.finished() {
840 State::Prefix if self.prefix_len() > 0 => {
841 self.front = State::StartDir;
842 debug_assert!(self.prefix_len() <= self.path.len());
843 let raw = &self.path[..self.prefix_len()];
844 self.path = &self.path[self.prefix_len()..];
845 return Some(Component::Prefix(PrefixComponent {
846 raw: unsafe { u8_slice_as_os_str(raw) },
847 parsed: self.prefix.unwrap(),
851 self.front = State::StartDir;
854 self.front = State::Body;
855 if self.has_physical_root {
856 debug_assert!(!self.path.is_empty());
857 self.path = &self.path[1..];
858 return Some(Component::RootDir);
859 } else if let Some(p) = self.prefix {
860 if p.has_implicit_root() && !p.is_verbatim() {
861 return Some(Component::RootDir);
863 } else if self.include_cur_dir() {
864 debug_assert!(!self.path.is_empty());
865 self.path = &self.path[1..];
866 return Some(Component::CurDir);
869 State::Body if !self.path.is_empty() => {
870 let (size, comp) = self.parse_next_component();
871 self.path = &self.path[size..];
877 self.front = State::Done;
879 State::Done => unreachable!(),
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<'a> DoubleEndedIterator for Components<'a> {
888 fn next_back(&mut self) -> Option<Component<'a>> {
889 while !self.finished() {
891 State::Body if self.path.len() > self.len_before_body() => {
892 let (size, comp) = self.parse_next_component_back();
893 self.path = &self.path[..self.path.len() - size];
899 self.back = State::StartDir;
902 self.back = State::Prefix;
903 if self.has_physical_root {
904 self.path = &self.path[..self.path.len() - 1];
905 return Some(Component::RootDir);
906 } else if let Some(p) = self.prefix {
907 if p.has_implicit_root() && !p.is_verbatim() {
908 return Some(Component::RootDir);
910 } else if self.include_cur_dir() {
911 self.path = &self.path[..self.path.len() - 1];
912 return Some(Component::CurDir);
915 State::Prefix if self.prefix_len() > 0 => {
916 self.back = State::Done;
917 return Some(Component::Prefix(PrefixComponent {
918 raw: unsafe { u8_slice_as_os_str(self.path) },
919 parsed: self.prefix.unwrap(),
923 self.back = State::Done;
926 State::Done => unreachable!(),
933 #[stable(feature = "fused", since = "1.26.0")]
934 impl FusedIterator for Components<'_> {}
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<'a> cmp::PartialEq for Components<'a> {
938 fn eq(&self, other: &Components<'a>) -> bool {
939 Iterator::eq(self.clone(), other.clone())
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl cmp::Eq for Components<'_> {}
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<'a> cmp::PartialOrd for Components<'a> {
948 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
949 Iterator::partial_cmp(self.clone(), other.clone())
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl cmp::Ord for Components<'_> {
955 fn cmp(&self, other: &Self) -> cmp::Ordering {
956 Iterator::cmp(self.clone(), other.clone())
960 /// An iterator over [`Path`] and its ancestors.
962 /// This `struct` is created by the [`ancestors`] method on [`Path`].
963 /// See its documentation for more.
968 /// use std::path::Path;
970 /// let path = Path::new("/foo/bar");
972 /// for ancestor in path.ancestors() {
973 /// println!("{}", ancestor.display());
977 /// [`ancestors`]: Path::ancestors
978 #[derive(Copy, Clone, Debug)]
979 #[stable(feature = "path_ancestors", since = "1.28.0")]
980 pub struct Ancestors<'a> {
981 next: Option<&'a Path>,
984 #[stable(feature = "path_ancestors", since = "1.28.0")]
985 impl<'a> Iterator for Ancestors<'a> {
986 type Item = &'a Path;
988 fn next(&mut self) -> Option<Self::Item> {
989 let next = self.next;
990 self.next = next.and_then(Path::parent);
995 #[stable(feature = "path_ancestors", since = "1.28.0")]
996 impl FusedIterator for Ancestors<'_> {}
998 ////////////////////////////////////////////////////////////////////////////////
999 // Basic types and traits
1000 ////////////////////////////////////////////////////////////////////////////////
1002 /// An owned, mutable path (akin to [`String`]).
1004 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1005 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1006 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1008 /// [`push`]: PathBuf::push
1009 /// [`set_extension`]: PathBuf::set_extension
1011 /// More details about the overall approach can be found in
1012 /// the [module documentation](index.html).
1016 /// You can use [`push`] to build up a `PathBuf` from
1020 /// use std::path::PathBuf;
1022 /// let mut path = PathBuf::new();
1024 /// path.push(r"C:\");
1025 /// path.push("windows");
1026 /// path.push("system32");
1028 /// path.set_extension("dll");
1031 /// However, [`push`] is best used for dynamic situations. This is a better way
1032 /// to do this when you know all of the components ahead of time:
1035 /// use std::path::PathBuf;
1037 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1040 /// We can still do better than this! Since these are all strings, we can use
1044 /// use std::path::PathBuf;
1046 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1049 /// Which method works best depends on what kind of situation you're in.
1051 #[stable(feature = "rust1", since = "1.0.0")]
1053 // `PathBuf::as_mut_vec` current implementation relies
1054 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1055 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1056 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1057 // not documented and must not be relied upon.
1058 pub struct PathBuf {
1063 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1064 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1067 /// Allocates an empty `PathBuf`.
1072 /// use std::path::PathBuf;
1074 /// let path = PathBuf::new();
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub fn new() -> PathBuf {
1078 PathBuf { inner: OsString::new() }
1081 /// Creates a new `PathBuf` with a given capacity used to create the
1082 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1087 /// use std::path::PathBuf;
1089 /// let mut path = PathBuf::with_capacity(10);
1090 /// let capacity = path.capacity();
1092 /// // This push is done without reallocating
1093 /// path.push(r"C:\");
1095 /// assert_eq!(capacity, path.capacity());
1098 /// [`with_capacity`]: OsString::with_capacity
1099 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1100 pub fn with_capacity(capacity: usize) -> PathBuf {
1101 PathBuf { inner: OsString::with_capacity(capacity) }
1104 /// Coerces to a [`Path`] slice.
1109 /// use std::path::{Path, PathBuf};
1111 /// let p = PathBuf::from("/test");
1112 /// assert_eq!(Path::new("/test"), p.as_path());
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn as_path(&self) -> &Path {
1119 /// Extends `self` with `path`.
1121 /// If `path` is absolute, it replaces the current path.
1125 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1126 /// replaces everything except for the prefix (if any) of `self`.
1127 /// * if `path` has a prefix but no root, it replaces `self`.
1131 /// Pushing a relative path extends the existing path:
1134 /// use std::path::PathBuf;
1136 /// let mut path = PathBuf::from("/tmp");
1137 /// path.push("file.bk");
1138 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1141 /// Pushing an absolute path replaces the existing path:
1144 /// use std::path::PathBuf;
1146 /// let mut path = PathBuf::from("/tmp");
1147 /// path.push("/etc");
1148 /// assert_eq!(path, PathBuf::from("/etc"));
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1152 self._push(path.as_ref())
1155 fn _push(&mut self, path: &Path) {
1156 // in general, a separator is needed if the rightmost byte is not a separator
1157 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1159 // in the special case of `C:` on Windows, do *not* add a separator
1161 let comps = self.components();
1162 if comps.prefix_len() > 0
1163 && comps.prefix_len() == comps.path.len()
1164 && comps.prefix.unwrap().is_drive()
1170 // absolute `path` replaces `self`
1171 if path.is_absolute() || path.prefix().is_some() {
1172 self.as_mut_vec().truncate(0);
1174 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1175 } else if path.has_root() {
1176 let prefix_len = self.components().prefix_remaining();
1177 self.as_mut_vec().truncate(prefix_len);
1179 // `path` is a pure relative path
1180 } else if need_sep {
1181 self.inner.push(MAIN_SEP_STR);
1184 self.inner.push(path);
1187 /// Truncates `self` to [`self.parent`].
1189 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1190 /// Otherwise, returns `true`.
1192 /// [`self.parent`]: Path::parent
1197 /// use std::path::{Path, PathBuf};
1199 /// let mut p = PathBuf::from("/spirited/away.rs");
1202 /// assert_eq!(Path::new("/spirited"), p);
1204 /// assert_eq!(Path::new("/"), p);
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 pub fn pop(&mut self) -> bool {
1208 match self.parent().map(|p| p.as_u8_slice().len()) {
1210 self.as_mut_vec().truncate(len);
1217 /// Updates [`self.file_name`] to `file_name`.
1219 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1222 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1223 /// `file_name`. The new path will be a sibling of the original path.
1224 /// (That is, it will have the same parent.)
1226 /// [`self.file_name`]: Path::file_name
1227 /// [`pop`]: PathBuf::pop
1232 /// use std::path::PathBuf;
1234 /// let mut buf = PathBuf::from("/");
1235 /// assert!(buf.file_name() == None);
1236 /// buf.set_file_name("bar");
1237 /// assert!(buf == PathBuf::from("/bar"));
1238 /// assert!(buf.file_name().is_some());
1239 /// buf.set_file_name("baz.txt");
1240 /// assert!(buf == PathBuf::from("/baz.txt"));
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1244 self._set_file_name(file_name.as_ref())
1247 fn _set_file_name(&mut self, file_name: &OsStr) {
1248 if self.file_name().is_some() {
1249 let popped = self.pop();
1250 debug_assert!(popped);
1252 self.push(file_name);
1255 /// Updates [`self.extension`] to `extension`.
1257 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1258 /// returns `true` and updates the extension otherwise.
1260 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1263 /// [`self.file_name`]: Path::file_name
1264 /// [`self.extension`]: Path::extension
1269 /// use std::path::{Path, PathBuf};
1271 /// let mut p = PathBuf::from("/feel/the");
1273 /// p.set_extension("force");
1274 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1276 /// p.set_extension("dark_side");
1277 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1281 self._set_extension(extension.as_ref())
1284 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1285 let file_stem = match self.file_stem() {
1286 None => return false,
1287 Some(f) => os_str_as_u8_slice(f),
1290 // truncate until right after the file stem
1291 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1292 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1293 let v = self.as_mut_vec();
1294 v.truncate(end_file_stem.wrapping_sub(start));
1296 // add the new extension, if any
1297 let new = os_str_as_u8_slice(extension);
1298 if !new.is_empty() {
1299 v.reserve_exact(new.len() + 1);
1301 v.extend_from_slice(new);
1307 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1312 /// use std::path::PathBuf;
1314 /// let p = PathBuf::from("/the/head");
1315 /// let os_str = p.into_os_string();
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn into_os_string(self) -> OsString {
1322 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1323 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1324 pub fn into_boxed_path(self) -> Box<Path> {
1325 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1326 unsafe { Box::from_raw(rw) }
1329 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1331 /// [`capacity`]: OsString::capacity
1332 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1333 pub fn capacity(&self) -> usize {
1334 self.inner.capacity()
1337 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1339 /// [`clear`]: OsString::clear
1340 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1341 pub fn clear(&mut self) {
1345 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1347 /// [`reserve`]: OsString::reserve
1348 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1349 pub fn reserve(&mut self, additional: usize) {
1350 self.inner.reserve(additional)
1353 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1355 /// [`reserve_exact`]: OsString::reserve_exact
1356 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1357 pub fn reserve_exact(&mut self, additional: usize) {
1358 self.inner.reserve_exact(additional)
1361 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1363 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1364 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1365 pub fn shrink_to_fit(&mut self) {
1366 self.inner.shrink_to_fit()
1369 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1371 /// [`shrink_to`]: OsString::shrink_to
1372 #[unstable(feature = "shrink_to", issue = "56431")]
1373 pub fn shrink_to(&mut self, min_capacity: usize) {
1374 self.inner.shrink_to(min_capacity)
1378 #[stable(feature = "box_from_path", since = "1.17.0")]
1379 impl From<&Path> for Box<Path> {
1380 fn from(path: &Path) -> Box<Path> {
1381 let boxed: Box<OsStr> = path.inner.into();
1382 let rw = Box::into_raw(boxed) as *mut Path;
1383 unsafe { Box::from_raw(rw) }
1387 #[stable(feature = "box_from_cow", since = "1.45.0")]
1388 impl From<Cow<'_, Path>> for Box<Path> {
1390 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1392 Cow::Borrowed(path) => Box::from(path),
1393 Cow::Owned(path) => Box::from(path),
1398 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1399 impl From<Box<Path>> for PathBuf {
1400 /// Converts a `Box<Path>` into a `PathBuf`
1402 /// This conversion does not allocate or copy memory.
1403 fn from(boxed: Box<Path>) -> PathBuf {
1404 boxed.into_path_buf()
1408 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1409 impl From<PathBuf> for Box<Path> {
1410 /// Converts a `PathBuf` into a `Box<Path>`
1412 /// This conversion currently should not allocate memory,
1413 /// but this behavior is not guaranteed on all platforms or in all future versions.
1414 fn from(p: PathBuf) -> Box<Path> {
1419 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1420 impl Clone for Box<Path> {
1422 fn clone(&self) -> Self {
1423 self.to_path_buf().into_boxed_path()
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1429 fn from(s: &T) -> PathBuf {
1430 PathBuf::from(s.as_ref().to_os_string())
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl From<OsString> for PathBuf {
1436 /// Converts a `OsString` into a `PathBuf`
1438 /// This conversion does not allocate or copy memory.
1440 fn from(s: OsString) -> PathBuf {
1441 PathBuf { inner: s }
1445 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1446 impl From<PathBuf> for OsString {
1447 /// Converts a `PathBuf` into a `OsString`
1449 /// This conversion does not allocate or copy memory.
1450 fn from(path_buf: PathBuf) -> OsString {
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl From<String> for PathBuf {
1457 /// Converts a `String` into a `PathBuf`
1459 /// This conversion does not allocate or copy memory.
1460 fn from(s: String) -> PathBuf {
1461 PathBuf::from(OsString::from(s))
1465 #[stable(feature = "path_from_str", since = "1.32.0")]
1466 impl FromStr for PathBuf {
1467 type Err = core::convert::Infallible;
1469 fn from_str(s: &str) -> Result<Self, Self::Err> {
1470 Ok(PathBuf::from(s))
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1476 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1477 let mut buf = PathBuf::new();
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1485 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1486 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1490 fn extend_one(&mut self, p: P) {
1491 self.push(p.as_ref());
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl fmt::Debug for PathBuf {
1497 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1498 fmt::Debug::fmt(&**self, formatter)
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl ops::Deref for PathBuf {
1506 fn deref(&self) -> &Path {
1507 Path::new(&self.inner)
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl Borrow<Path> for PathBuf {
1513 fn borrow(&self) -> &Path {
1518 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1519 impl Default for PathBuf {
1520 fn default() -> Self {
1525 #[stable(feature = "cow_from_path", since = "1.6.0")]
1526 impl<'a> From<&'a Path> for Cow<'a, Path> {
1528 fn from(s: &'a Path) -> Cow<'a, Path> {
1533 #[stable(feature = "cow_from_path", since = "1.6.0")]
1534 impl<'a> From<PathBuf> for Cow<'a, Path> {
1536 fn from(s: PathBuf) -> Cow<'a, Path> {
1541 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1542 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1544 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1545 Cow::Borrowed(p.as_path())
1549 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1550 impl<'a> From<Cow<'a, Path>> for PathBuf {
1552 fn from(p: Cow<'a, Path>) -> Self {
1557 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1558 impl From<PathBuf> for Arc<Path> {
1559 /// Converts a `PathBuf` into an `Arc` by moving the `PathBuf` data into a new `Arc` buffer.
1561 fn from(s: PathBuf) -> Arc<Path> {
1562 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1563 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1567 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1568 impl From<&Path> for Arc<Path> {
1569 /// Converts a `Path` into an `Arc` by copying the `Path` data into a new `Arc` buffer.
1571 fn from(s: &Path) -> Arc<Path> {
1572 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1573 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1577 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1578 impl From<PathBuf> for Rc<Path> {
1579 /// Converts a `PathBuf` into an `Rc` by moving the `PathBuf` data into a new `Rc` buffer.
1581 fn from(s: PathBuf) -> Rc<Path> {
1582 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1583 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1587 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1588 impl From<&Path> for Rc<Path> {
1589 /// Converts a `Path` into an `Rc` by copying the `Path` data into a new `Rc` buffer.
1591 fn from(s: &Path) -> Rc<Path> {
1592 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1593 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl ToOwned for Path {
1599 type Owned = PathBuf;
1600 fn to_owned(&self) -> PathBuf {
1603 fn clone_into(&self, target: &mut PathBuf) {
1604 self.inner.clone_into(&mut target.inner);
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl cmp::PartialEq for PathBuf {
1610 fn eq(&self, other: &PathBuf) -> bool {
1611 self.components() == other.components()
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl Hash for PathBuf {
1617 fn hash<H: Hasher>(&self, h: &mut H) {
1618 self.as_path().hash(h)
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 impl cmp::Eq for PathBuf {}
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl cmp::PartialOrd for PathBuf {
1627 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1628 self.components().partial_cmp(other.components())
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 impl cmp::Ord for PathBuf {
1634 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1635 self.components().cmp(other.components())
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl AsRef<OsStr> for PathBuf {
1641 fn as_ref(&self) -> &OsStr {
1646 /// A slice of a path (akin to [`str`]).
1648 /// This type supports a number of operations for inspecting a path, including
1649 /// breaking the path into its components (separated by `/` on Unix and by either
1650 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1651 /// is absolute, and so on.
1653 /// This is an *unsized* type, meaning that it must always be used behind a
1654 /// pointer like `&` or [`Box`]. For an owned version of this type,
1655 /// see [`PathBuf`].
1657 /// More details about the overall approach can be found in
1658 /// the [module documentation](index.html).
1663 /// use std::path::Path;
1664 /// use std::ffi::OsStr;
1666 /// // Note: this example does work on Windows
1667 /// let path = Path::new("./foo/bar.txt");
1669 /// let parent = path.parent();
1670 /// assert_eq!(parent, Some(Path::new("./foo")));
1672 /// let file_stem = path.file_stem();
1673 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1675 /// let extension = path.extension();
1676 /// assert_eq!(extension, Some(OsStr::new("txt")));
1678 #[stable(feature = "rust1", since = "1.0.0")]
1680 // `Path::new` current implementation relies
1681 // on `Path` being layout-compatible with `OsStr`.
1682 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1683 // Anyway, `Path` representation and layout are considered implementation detail, are
1684 // not documented and must not be relied upon.
1689 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1692 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1693 /// See its documentation for more.
1695 /// [`strip_prefix`]: Path::strip_prefix
1696 #[derive(Debug, Clone, PartialEq, Eq)]
1697 #[stable(since = "1.7.0", feature = "strip_prefix")]
1698 pub struct StripPrefixError(());
1701 // The following (private!) function allows construction of a path from a u8
1702 // slice, which is only safe when it is known to follow the OsStr encoding.
1703 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1704 Path::new(u8_slice_as_os_str(s))
1706 // The following (private!) function reveals the byte encoding used for OsStr.
1707 fn as_u8_slice(&self) -> &[u8] {
1708 os_str_as_u8_slice(&self.inner)
1711 /// Directly wraps a string slice as a `Path` slice.
1713 /// This is a cost-free conversion.
1718 /// use std::path::Path;
1720 /// Path::new("foo.txt");
1723 /// You can create `Path`s from `String`s, or even other `Path`s:
1726 /// use std::path::Path;
1728 /// let string = String::from("foo.txt");
1729 /// let from_string = Path::new(&string);
1730 /// let from_path = Path::new(&from_string);
1731 /// assert_eq!(from_string, from_path);
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1735 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1738 /// Yields the underlying [`OsStr`] slice.
1743 /// use std::path::Path;
1745 /// let os_str = Path::new("foo.txt").as_os_str();
1746 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1748 #[stable(feature = "rust1", since = "1.0.0")]
1749 pub fn as_os_str(&self) -> &OsStr {
1753 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1755 /// This conversion may entail doing a check for UTF-8 validity.
1756 /// Note that validation is performed because non-UTF-8 strings are
1757 /// perfectly valid for some OS.
1764 /// use std::path::Path;
1766 /// let path = Path::new("foo.txt");
1767 /// assert_eq!(path.to_str(), Some("foo.txt"));
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 pub fn to_str(&self) -> Option<&str> {
1774 /// Converts a `Path` to a [`Cow<str>`].
1776 /// Any non-Unicode sequences are replaced with
1777 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1779 /// [`Cow<str>`]: Cow
1780 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1784 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1787 /// use std::path::Path;
1789 /// let path = Path::new("foo.txt");
1790 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1793 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1794 /// have returned `"fo�.txt"`.
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1797 self.inner.to_string_lossy()
1800 /// Converts a `Path` to an owned [`PathBuf`].
1805 /// use std::path::Path;
1807 /// let path_buf = Path::new("foo.txt").to_path_buf();
1808 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1810 #[rustc_conversion_suggestion]
1811 #[stable(feature = "rust1", since = "1.0.0")]
1812 pub fn to_path_buf(&self) -> PathBuf {
1813 PathBuf::from(self.inner.to_os_string())
1816 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1817 /// the current directory.
1819 /// * On Unix, a path is absolute if it starts with the root, so
1820 /// `is_absolute` and [`has_root`] are equivalent.
1822 /// * On Windows, a path is absolute if it has a prefix and starts with the
1823 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1828 /// use std::path::Path;
1830 /// assert!(!Path::new("foo.txt").is_absolute());
1833 /// [`has_root`]: Path::has_root
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 #[allow(deprecated)]
1836 pub fn is_absolute(&self) -> bool {
1837 if cfg!(target_os = "redox") {
1838 // FIXME: Allow Redox prefixes
1839 self.has_root() || has_redox_scheme(self.as_u8_slice())
1841 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1845 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1847 /// See [`is_absolute`]'s documentation for more details.
1852 /// use std::path::Path;
1854 /// assert!(Path::new("foo.txt").is_relative());
1857 /// [`is_absolute`]: Path::is_absolute
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 pub fn is_relative(&self) -> bool {
1863 fn prefix(&self) -> Option<Prefix<'_>> {
1864 self.components().prefix
1867 /// Returns `true` if the `Path` has a root.
1869 /// * On Unix, a path has a root if it begins with `/`.
1871 /// * On Windows, a path has a root if it:
1872 /// * has no prefix and begins with a separator, e.g., `\windows`
1873 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1874 /// * has any non-disk prefix, e.g., `\\server\share`
1879 /// use std::path::Path;
1881 /// assert!(Path::new("/etc/passwd").has_root());
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 pub fn has_root(&self) -> bool {
1885 self.components().has_root()
1888 /// Returns the `Path` without its final component, if there is one.
1890 /// Returns [`None`] if the path terminates in a root or prefix.
1895 /// use std::path::Path;
1897 /// let path = Path::new("/foo/bar");
1898 /// let parent = path.parent().unwrap();
1899 /// assert_eq!(parent, Path::new("/foo"));
1901 /// let grand_parent = parent.parent().unwrap();
1902 /// assert_eq!(grand_parent, Path::new("/"));
1903 /// assert_eq!(grand_parent.parent(), None);
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 pub fn parent(&self) -> Option<&Path> {
1907 let mut comps = self.components();
1908 let comp = comps.next_back();
1909 comp.and_then(|p| match p {
1910 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
1911 Some(comps.as_path())
1917 /// Produces an iterator over `Path` and its ancestors.
1919 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1920 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1921 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1922 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1928 /// use std::path::Path;
1930 /// let mut ancestors = Path::new("/foo/bar").ancestors();
1931 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1932 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1933 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1934 /// assert_eq!(ancestors.next(), None);
1936 /// let mut ancestors = Path::new("../foo/bar").ancestors();
1937 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
1938 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
1939 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
1940 /// assert_eq!(ancestors.next(), Some(Path::new("")));
1941 /// assert_eq!(ancestors.next(), None);
1944 /// [`parent`]: Path::parent
1945 #[stable(feature = "path_ancestors", since = "1.28.0")]
1946 pub fn ancestors(&self) -> Ancestors<'_> {
1947 Ancestors { next: Some(&self) }
1950 /// Returns the final component of the `Path`, if there is one.
1952 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1953 /// is the directory name.
1955 /// Returns [`None`] if the path terminates in `..`.
1960 /// use std::path::Path;
1961 /// use std::ffi::OsStr;
1963 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1964 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1965 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1966 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1967 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1968 /// assert_eq!(None, Path::new("/").file_name());
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 pub fn file_name(&self) -> Option<&OsStr> {
1972 self.components().next_back().and_then(|p| match p {
1973 Component::Normal(p) => Some(p),
1978 /// Returns a path that, when joined onto `base`, yields `self`.
1982 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
1983 /// returns `false`), returns [`Err`].
1985 /// [`starts_with`]: Path::starts_with
1990 /// use std::path::{Path, PathBuf};
1992 /// let path = Path::new("/test/haha/foo.txt");
1994 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
1995 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1996 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
1997 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
1998 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2000 /// assert!(path.strip_prefix("test").is_err());
2001 /// assert!(path.strip_prefix("/haha").is_err());
2003 /// let prefix = PathBuf::from("/test/");
2004 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2006 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2007 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2011 self._strip_prefix(base.as_ref())
2014 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2015 iter_after(self.components(), base.components())
2016 .map(|c| c.as_path())
2017 .ok_or(StripPrefixError(()))
2020 /// Determines whether `base` is a prefix of `self`.
2022 /// Only considers whole path components to match.
2027 /// use std::path::Path;
2029 /// let path = Path::new("/etc/passwd");
2031 /// assert!(path.starts_with("/etc"));
2032 /// assert!(path.starts_with("/etc/"));
2033 /// assert!(path.starts_with("/etc/passwd"));
2034 /// assert!(path.starts_with("/etc/passwd/"));
2036 /// assert!(!path.starts_with("/e"));
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2040 self._starts_with(base.as_ref())
2043 fn _starts_with(&self, base: &Path) -> bool {
2044 iter_after(self.components(), base.components()).is_some()
2047 /// Determines whether `child` is a suffix of `self`.
2049 /// Only considers whole path components to match.
2054 /// use std::path::Path;
2056 /// let path = Path::new("/etc/passwd");
2058 /// assert!(path.ends_with("passwd"));
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2062 self._ends_with(child.as_ref())
2065 fn _ends_with(&self, child: &Path) -> bool {
2066 iter_after(self.components().rev(), child.components().rev()).is_some()
2069 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2071 /// [`self.file_name`]: Path::file_name
2075 /// * [`None`], if there is no file name;
2076 /// * The entire file name if there is no embedded `.`;
2077 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2078 /// * Otherwise, the portion of the file name before the final `.`
2083 /// use std::path::Path;
2085 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2086 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2088 #[stable(feature = "rust1", since = "1.0.0")]
2089 pub fn file_stem(&self) -> Option<&OsStr> {
2090 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2093 /// Extracts the extension of [`self.file_name`], if possible.
2095 /// The extension is:
2097 /// * [`None`], if there is no file name;
2098 /// * [`None`], if there is no embedded `.`;
2099 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2100 /// * Otherwise, the portion of the file name after the final `.`
2102 /// [`self.file_name`]: Path::file_name
2107 /// use std::path::Path;
2109 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2110 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2112 #[stable(feature = "rust1", since = "1.0.0")]
2113 pub fn extension(&self) -> Option<&OsStr> {
2114 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2117 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2119 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2124 /// use std::path::{Path, PathBuf};
2126 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2128 #[stable(feature = "rust1", since = "1.0.0")]
2130 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2131 self._join(path.as_ref())
2134 fn _join(&self, path: &Path) -> PathBuf {
2135 let mut buf = self.to_path_buf();
2140 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2142 /// See [`PathBuf::set_file_name`] for more details.
2147 /// use std::path::{Path, PathBuf};
2149 /// let path = Path::new("/tmp/foo.txt");
2150 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2152 /// let path = Path::new("/tmp");
2153 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2157 self._with_file_name(file_name.as_ref())
2160 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2161 let mut buf = self.to_path_buf();
2162 buf.set_file_name(file_name);
2166 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2168 /// See [`PathBuf::set_extension`] for more details.
2173 /// use std::path::{Path, PathBuf};
2175 /// let path = Path::new("foo.rs");
2176 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2178 /// let path = Path::new("foo.tar.gz");
2179 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2180 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2181 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2185 self._with_extension(extension.as_ref())
2188 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2189 let mut buf = self.to_path_buf();
2190 buf.set_extension(extension);
2194 /// Produces an iterator over the [`Component`]s of the path.
2196 /// When parsing the path, there is a small amount of normalization:
2198 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2199 /// `a` and `b` as components.
2201 /// * Occurrences of `.` are normalized away, except if they are at the
2202 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2203 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2204 /// an additional [`CurDir`] component.
2206 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2208 /// Note that no other normalization takes place; in particular, `a/c`
2209 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2210 /// is a symbolic link (so its parent isn't `a`).
2215 /// use std::path::{Path, Component};
2216 /// use std::ffi::OsStr;
2218 /// let mut components = Path::new("/tmp/foo.txt").components();
2220 /// assert_eq!(components.next(), Some(Component::RootDir));
2221 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2222 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2223 /// assert_eq!(components.next(), None)
2226 /// [`CurDir`]: Component::CurDir
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 pub fn components(&self) -> Components<'_> {
2229 let prefix = parse_prefix(self.as_os_str());
2231 path: self.as_u8_slice(),
2233 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2234 || has_redox_scheme(self.as_u8_slice()),
2235 front: State::Prefix,
2240 /// Produces an iterator over the path's components viewed as [`OsStr`]
2243 /// For more information about the particulars of how the path is separated
2244 /// into components, see [`components`].
2246 /// [`components`]: Path::components
2251 /// use std::path::{self, Path};
2252 /// use std::ffi::OsStr;
2254 /// let mut it = Path::new("/tmp/foo.txt").iter();
2255 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2256 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2257 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2258 /// assert_eq!(it.next(), None)
2260 #[stable(feature = "rust1", since = "1.0.0")]
2261 pub fn iter(&self) -> Iter<'_> {
2262 Iter { inner: self.components() }
2265 /// Returns an object that implements [`Display`] for safely printing paths
2266 /// that may contain non-Unicode data.
2268 /// [`Display`]: fmt::Display
2273 /// use std::path::Path;
2275 /// let path = Path::new("/tmp/foo.rs");
2277 /// println!("{}", path.display());
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 pub fn display(&self) -> Display<'_> {
2281 Display { path: self }
2284 /// Queries the file system to get information about a file, directory, etc.
2286 /// This function will traverse symbolic links to query information about the
2287 /// destination file.
2289 /// This is an alias to [`fs::metadata`].
2294 /// use std::path::Path;
2296 /// let path = Path::new("/Minas/tirith");
2297 /// let metadata = path.metadata().expect("metadata call failed");
2298 /// println!("{:?}", metadata.file_type());
2300 #[stable(feature = "path_ext", since = "1.5.0")]
2301 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2305 /// Queries the metadata about a file without following symlinks.
2307 /// This is an alias to [`fs::symlink_metadata`].
2312 /// use std::path::Path;
2314 /// let path = Path::new("/Minas/tirith");
2315 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2316 /// println!("{:?}", metadata.file_type());
2318 #[stable(feature = "path_ext", since = "1.5.0")]
2319 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2320 fs::symlink_metadata(self)
2323 /// Returns the canonical, absolute form of the path with all intermediate
2324 /// components normalized and symbolic links resolved.
2326 /// This is an alias to [`fs::canonicalize`].
2331 /// use std::path::{Path, PathBuf};
2333 /// let path = Path::new("/foo/test/../test/bar.rs");
2334 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2336 #[stable(feature = "path_ext", since = "1.5.0")]
2337 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2338 fs::canonicalize(self)
2341 /// Reads a symbolic link, returning the file that the link points to.
2343 /// This is an alias to [`fs::read_link`].
2348 /// use std::path::Path;
2350 /// let path = Path::new("/laputa/sky_castle.rs");
2351 /// let path_link = path.read_link().expect("read_link call failed");
2353 #[stable(feature = "path_ext", since = "1.5.0")]
2354 pub fn read_link(&self) -> io::Result<PathBuf> {
2358 /// Returns an iterator over the entries within a directory.
2360 /// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New
2361 /// errors may be encountered after an iterator is initially constructed.
2363 /// This is an alias to [`fs::read_dir`].
2368 /// use std::path::Path;
2370 /// let path = Path::new("/laputa");
2371 /// for entry in path.read_dir().expect("read_dir call failed") {
2372 /// if let Ok(entry) = entry {
2373 /// println!("{:?}", entry.path());
2377 #[stable(feature = "path_ext", since = "1.5.0")]
2378 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2382 /// Returns `true` if the path points at an existing entity.
2384 /// This function will traverse symbolic links to query information about the
2385 /// destination file. In case of broken symbolic links this will return `false`.
2387 /// If you cannot access the directory containing the file, e.g., because of a
2388 /// permission error, this will return `false`.
2393 /// use std::path::Path;
2394 /// assert!(!Path::new("does_not_exist.txt").exists());
2399 /// This is a convenience function that coerces errors to false. If you want to
2400 /// check errors, call [`fs::metadata`].
2401 #[stable(feature = "path_ext", since = "1.5.0")]
2402 pub fn exists(&self) -> bool {
2403 fs::metadata(self).is_ok()
2406 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2408 /// This function will traverse symbolic links to query information about the
2409 /// destination file. In case of broken symbolic links this will return `false`.
2411 /// If you cannot access the directory containing the file, e.g., because of a
2412 /// permission error, this will return `false`.
2417 /// use std::path::Path;
2418 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2419 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2424 /// This is a convenience function that coerces errors to false. If you want to
2425 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2426 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2428 /// When the goal is simply to read from (or write to) the source, the most
2429 /// reliable way to test the source can be read (or written to) is to open
2430 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2431 /// a Unix-like system for example. See [`fs::File::open`] or
2432 /// [`fs::OpenOptions::open`] for more information.
2433 #[stable(feature = "path_ext", since = "1.5.0")]
2434 pub fn is_file(&self) -> bool {
2435 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2438 /// Returns `true` if the path exists on disk and is pointing at a directory.
2440 /// This function will traverse symbolic links to query information about the
2441 /// destination file. In case of broken symbolic links this will return `false`.
2443 /// If you cannot access the directory containing the file, e.g., because of a
2444 /// permission error, this will return `false`.
2449 /// use std::path::Path;
2450 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2451 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2456 /// This is a convenience function that coerces errors to false. If you want to
2457 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2458 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2459 #[stable(feature = "path_ext", since = "1.5.0")]
2460 pub fn is_dir(&self) -> bool {
2461 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2464 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2466 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2467 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2468 let rw = Box::into_raw(self) as *mut OsStr;
2469 let inner = unsafe { Box::from_raw(rw) };
2470 PathBuf { inner: OsString::from(inner) }
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl AsRef<OsStr> for Path {
2476 fn as_ref(&self) -> &OsStr {
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 impl fmt::Debug for Path {
2483 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2484 fmt::Debug::fmt(&self.inner, formatter)
2488 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2490 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2491 /// [`Display`] trait in a way that mitigates that. It is created by the
2492 /// [`display`][`Path::display`] method on [`Path`].
2497 /// use std::path::Path;
2499 /// let path = Path::new("/tmp/foo.rs");
2501 /// println!("{}", path.display());
2504 /// [`Display`]: fmt::Display
2505 /// [`format!`]: crate::format
2506 #[stable(feature = "rust1", since = "1.0.0")]
2507 pub struct Display<'a> {
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 impl fmt::Debug for Display<'_> {
2513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2514 fmt::Debug::fmt(&self.path, f)
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 impl fmt::Display for Display<'_> {
2520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2521 self.path.inner.display(f)
2525 #[stable(feature = "rust1", since = "1.0.0")]
2526 impl cmp::PartialEq for Path {
2527 fn eq(&self, other: &Path) -> bool {
2528 self.components().eq(other.components())
2532 #[stable(feature = "rust1", since = "1.0.0")]
2533 impl Hash for Path {
2534 fn hash<H: Hasher>(&self, h: &mut H) {
2535 for component in self.components() {
2541 #[stable(feature = "rust1", since = "1.0.0")]
2542 impl cmp::Eq for Path {}
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl cmp::PartialOrd for Path {
2546 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2547 self.components().partial_cmp(other.components())
2551 #[stable(feature = "rust1", since = "1.0.0")]
2552 impl cmp::Ord for Path {
2553 fn cmp(&self, other: &Path) -> cmp::Ordering {
2554 self.components().cmp(other.components())
2558 #[stable(feature = "rust1", since = "1.0.0")]
2559 impl AsRef<Path> for Path {
2560 fn as_ref(&self) -> &Path {
2565 #[stable(feature = "rust1", since = "1.0.0")]
2566 impl AsRef<Path> for OsStr {
2567 fn as_ref(&self) -> &Path {
2572 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2573 impl AsRef<Path> for Cow<'_, OsStr> {
2574 fn as_ref(&self) -> &Path {
2579 #[stable(feature = "rust1", since = "1.0.0")]
2580 impl AsRef<Path> for OsString {
2581 fn as_ref(&self) -> &Path {
2586 #[stable(feature = "rust1", since = "1.0.0")]
2587 impl AsRef<Path> for str {
2589 fn as_ref(&self) -> &Path {
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 impl AsRef<Path> for String {
2596 fn as_ref(&self) -> &Path {
2601 #[stable(feature = "rust1", since = "1.0.0")]
2602 impl AsRef<Path> for PathBuf {
2604 fn as_ref(&self) -> &Path {
2609 #[stable(feature = "path_into_iter", since = "1.6.0")]
2610 impl<'a> IntoIterator for &'a PathBuf {
2611 type Item = &'a OsStr;
2612 type IntoIter = Iter<'a>;
2613 fn into_iter(self) -> Iter<'a> {
2618 #[stable(feature = "path_into_iter", since = "1.6.0")]
2619 impl<'a> IntoIterator for &'a Path {
2620 type Item = &'a OsStr;
2621 type IntoIter = Iter<'a>;
2622 fn into_iter(self) -> Iter<'a> {
2627 macro_rules! impl_cmp {
2628 ($lhs:ty, $rhs: ty) => {
2629 #[stable(feature = "partialeq_path", since = "1.6.0")]
2630 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2632 fn eq(&self, other: &$rhs) -> bool {
2633 <Path as PartialEq>::eq(self, other)
2637 #[stable(feature = "partialeq_path", since = "1.6.0")]
2638 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2640 fn eq(&self, other: &$lhs) -> bool {
2641 <Path as PartialEq>::eq(self, other)
2645 #[stable(feature = "cmp_path", since = "1.8.0")]
2646 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2648 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2649 <Path as PartialOrd>::partial_cmp(self, other)
2653 #[stable(feature = "cmp_path", since = "1.8.0")]
2654 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2656 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2657 <Path as PartialOrd>::partial_cmp(self, other)
2663 impl_cmp!(PathBuf, Path);
2664 impl_cmp!(PathBuf, &'a Path);
2665 impl_cmp!(Cow<'a, Path>, Path);
2666 impl_cmp!(Cow<'a, Path>, &'b Path);
2667 impl_cmp!(Cow<'a, Path>, PathBuf);
2669 macro_rules! impl_cmp_os_str {
2670 ($lhs:ty, $rhs: ty) => {
2671 #[stable(feature = "cmp_path", since = "1.8.0")]
2672 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2674 fn eq(&self, other: &$rhs) -> bool {
2675 <Path as PartialEq>::eq(self, other.as_ref())
2679 #[stable(feature = "cmp_path", since = "1.8.0")]
2680 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2682 fn eq(&self, other: &$lhs) -> bool {
2683 <Path as PartialEq>::eq(self.as_ref(), other)
2687 #[stable(feature = "cmp_path", since = "1.8.0")]
2688 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2690 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2691 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2695 #[stable(feature = "cmp_path", since = "1.8.0")]
2696 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2698 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2699 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2705 impl_cmp_os_str!(PathBuf, OsStr);
2706 impl_cmp_os_str!(PathBuf, &'a OsStr);
2707 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2708 impl_cmp_os_str!(PathBuf, OsString);
2709 impl_cmp_os_str!(Path, OsStr);
2710 impl_cmp_os_str!(Path, &'a OsStr);
2711 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2712 impl_cmp_os_str!(Path, OsString);
2713 impl_cmp_os_str!(&'a Path, OsStr);
2714 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2715 impl_cmp_os_str!(&'a Path, OsString);
2716 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2717 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2718 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2720 #[stable(since = "1.7.0", feature = "strip_prefix")]
2721 impl fmt::Display for StripPrefixError {
2722 #[allow(deprecated, deprecated_in_future)]
2723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2724 self.description().fmt(f)
2728 #[stable(since = "1.7.0", feature = "strip_prefix")]
2729 impl Error for StripPrefixError {
2730 #[allow(deprecated)]
2731 fn description(&self) -> &str {
2741 use crate::sync::Arc;
2744 ($path:expr, iter: $iter:expr) => (
2746 let path = Path::new($path);
2748 // Forward iteration
2749 let comps = path.iter()
2750 .map(|p| p.to_string_lossy().into_owned())
2751 .collect::<Vec<String>>();
2752 let exp: &[&str] = &$iter;
2753 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2754 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2757 // Reverse iteration
2758 let comps = Path::new($path).iter().rev()
2759 .map(|p| p.to_string_lossy().into_owned())
2760 .collect::<Vec<String>>();
2761 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2762 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2767 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2769 let path = Path::new($path);
2771 let act_root = path.has_root();
2772 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2773 $has_root, act_root);
2775 let act_abs = path.is_absolute();
2776 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2777 $is_absolute, act_abs);
2781 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2783 let path = Path::new($path);
2785 let parent = path.parent().map(|p| p.to_str().unwrap());
2786 let exp_parent: Option<&str> = $parent;
2787 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2788 exp_parent, parent);
2790 let file = path.file_name().map(|p| p.to_str().unwrap());
2791 let exp_file: Option<&str> = $file;
2792 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2797 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2799 let path = Path::new($path);
2801 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2802 let exp_stem: Option<&str> = $file_stem;
2803 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2806 let ext = path.extension().map(|p| p.to_str().unwrap());
2807 let exp_ext: Option<&str> = $extension;
2808 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2813 ($path:expr, iter: $iter:expr,
2814 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2815 parent: $parent:expr, file_name: $file:expr,
2816 file_stem: $file_stem:expr, extension: $extension:expr) => (
2818 t!($path, iter: $iter);
2819 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2820 t!($path, parent: $parent, file_name: $file);
2821 t!($path, file_stem: $file_stem, extension: $extension);
2828 use crate::borrow::Cow;
2830 let static_path = Path::new("/home/foo");
2831 let static_cow_path: Cow<'static, Path> = static_path.into();
2832 let pathbuf = PathBuf::from("/home/foo");
2835 let path: &Path = &pathbuf;
2836 let borrowed_cow_path: Cow<'_, Path> = path.into();
2838 assert_eq!(static_cow_path, borrowed_cow_path);
2841 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2843 assert_eq!(static_cow_path, owned_cow_path);
2848 pub fn test_decompositions_unix() {
2864 file_name: Some("foo"),
2865 file_stem: Some("foo"),
2884 file_name: Some("foo"),
2885 file_stem: Some("foo"),
2894 file_name: Some("foo"),
2895 file_stem: Some("foo"),
2904 file_name: Some("foo"),
2905 file_stem: Some("foo"),
2910 iter: ["foo", "bar"],
2913 parent: Some("foo"),
2914 file_name: Some("bar"),
2915 file_stem: Some("bar"),
2920 iter: ["/", "foo", "bar"],
2923 parent: Some("/foo"),
2924 file_name: Some("bar"),
2925 file_stem: Some("bar"),
2934 file_name: Some("foo"),
2935 file_stem: Some("foo"),
2940 iter: ["/", "foo", "bar"],
2943 parent: Some("///foo"),
2944 file_name: Some("bar"),
2945 file_stem: Some("bar"),
2984 file_name: Some("foo"),
2985 file_stem: Some("foo"),
2990 iter: ["foo", ".."],
2993 parent: Some("foo"),
3004 file_name: Some("foo"),
3005 file_stem: Some("foo"),
3010 iter: ["foo", "bar"],
3013 parent: Some("foo"),
3014 file_name: Some("bar"),
3015 file_stem: Some("bar"),
3020 iter: ["foo", ".."],
3023 parent: Some("foo"),
3030 iter: ["foo", "..", "bar"],
3033 parent: Some("foo/.."),
3034 file_name: Some("bar"),
3035 file_stem: Some("bar"),
3044 file_name: Some("a"),
3045 file_stem: Some("a"),
3074 file_name: Some("b"),
3075 file_stem: Some("b"),
3084 file_name: Some("b"),
3085 file_stem: Some("b"),
3094 file_name: Some("b"),
3095 file_stem: Some("b"),
3100 iter: ["a", "b", "c"],
3103 parent: Some("a/b"),
3104 file_name: Some("c"),
3105 file_stem: Some("c"),
3114 file_name: Some(".foo"),
3115 file_stem: Some(".foo"),
3122 pub fn test_decompositions_windows() {
3138 file_name: Some("foo"),
3139 file_stem: Some("foo"),
3194 iter: ["\\", "foo"],
3198 file_name: Some("foo"),
3199 file_stem: Some("foo"),
3208 file_name: Some("foo"),
3209 file_stem: Some("foo"),
3214 iter: ["\\", "foo"],
3218 file_name: Some("foo"),
3219 file_stem: Some("foo"),
3224 iter: ["foo", "bar"],
3227 parent: Some("foo"),
3228 file_name: Some("bar"),
3229 file_stem: Some("bar"),
3234 iter: ["\\", "foo", "bar"],
3237 parent: Some("/foo"),
3238 file_name: Some("bar"),
3239 file_stem: Some("bar"),
3244 iter: ["\\", "foo"],
3248 file_name: Some("foo"),
3249 file_stem: Some("foo"),
3254 iter: ["\\", "foo", "bar"],
3257 parent: Some("///foo"),
3258 file_name: Some("bar"),
3259 file_stem: Some("bar"),
3298 file_name: Some("foo"),
3299 file_stem: Some("foo"),
3304 iter: ["foo", ".."],
3307 parent: Some("foo"),
3318 file_name: Some("foo"),
3319 file_stem: Some("foo"),
3324 iter: ["foo", "bar"],
3327 parent: Some("foo"),
3328 file_name: Some("bar"),
3329 file_stem: Some("bar"),
3334 iter: ["foo", ".."],
3337 parent: Some("foo"),
3344 iter: ["foo", "..", "bar"],
3347 parent: Some("foo/.."),
3348 file_name: Some("bar"),
3349 file_stem: Some("bar"),
3358 file_name: Some("a"),
3359 file_stem: Some("a"),
3388 file_name: Some("b"),
3389 file_stem: Some("b"),
3398 file_name: Some("b"),
3399 file_stem: Some("b"),
3408 file_name: Some("b"),
3409 file_stem: Some("b"),
3414 iter: ["a", "b", "c"],
3417 parent: Some("a/b"),
3418 file_name: Some("c"),
3419 file_stem: Some("c"),
3423 iter: ["a", "b", "c"],
3426 parent: Some("a\\b"),
3427 file_name: Some("c"),
3428 file_stem: Some("c"),
3437 file_name: Some("a"),
3438 file_stem: Some("a"),
3443 iter: ["c:", "\\", "foo.txt"],
3446 parent: Some("c:\\"),
3447 file_name: Some("foo.txt"),
3448 file_stem: Some("foo"),
3449 extension: Some("txt")
3452 t!("\\\\server\\share\\foo.txt",
3453 iter: ["\\\\server\\share", "\\", "foo.txt"],
3456 parent: Some("\\\\server\\share\\"),
3457 file_name: Some("foo.txt"),
3458 file_stem: Some("foo"),
3459 extension: Some("txt")
3462 t!("\\\\server\\share",
3463 iter: ["\\\\server\\share", "\\"],
3473 iter: ["\\", "server"],
3477 file_name: Some("server"),
3478 file_stem: Some("server"),
3482 t!("\\\\?\\bar\\foo.txt",
3483 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3486 parent: Some("\\\\?\\bar\\"),
3487 file_name: Some("foo.txt"),
3488 file_stem: Some("foo"),
3489 extension: Some("txt")
3493 iter: ["\\\\?\\bar"],
3512 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3513 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3516 parent: Some("\\\\?\\UNC\\server\\share\\"),
3517 file_name: Some("foo.txt"),
3518 file_stem: Some("foo"),
3519 extension: Some("txt")
3522 t!("\\\\?\\UNC\\server",
3523 iter: ["\\\\?\\UNC\\server"],
3533 iter: ["\\\\?\\UNC\\"],
3542 t!("\\\\?\\C:\\foo.txt",
3543 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3546 parent: Some("\\\\?\\C:\\"),
3547 file_name: Some("foo.txt"),
3548 file_stem: Some("foo"),
3549 extension: Some("txt")
3553 iter: ["\\\\?\\C:", "\\"],
3563 iter: ["\\\\?\\C:"],
3572 t!("\\\\?\\foo/bar",
3573 iter: ["\\\\?\\foo/bar"],
3583 iter: ["\\\\?\\C:/foo"],
3592 t!("\\\\.\\foo\\bar",
3593 iter: ["\\\\.\\foo", "\\", "bar"],
3596 parent: Some("\\\\.\\foo\\"),
3597 file_name: Some("bar"),
3598 file_stem: Some("bar"),
3603 iter: ["\\\\.\\foo", "\\"],
3612 t!("\\\\.\\foo/bar",
3613 iter: ["\\\\.\\foo/bar", "\\"],
3622 t!("\\\\.\\foo\\bar/baz",
3623 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3626 parent: Some("\\\\.\\foo\\bar"),
3627 file_name: Some("baz"),
3628 file_stem: Some("baz"),
3633 iter: ["\\\\.\\", "\\"],
3643 iter: ["\\\\?\\a", "\\", "b"],
3646 parent: Some("\\\\?\\a\\"),
3647 file_name: Some("b"),
3648 file_stem: Some("b"),
3654 pub fn test_stem_ext() {
3656 file_stem: Some("foo"),
3661 file_stem: Some("foo"),
3666 file_stem: Some(".foo"),
3671 file_stem: Some("foo"),
3672 extension: Some("txt")
3676 file_stem: Some("foo.bar"),
3677 extension: Some("txt")
3681 file_stem: Some("foo.bar"),
3685 t!(".", file_stem: None, extension: None);
3687 t!("..", file_stem: None, extension: None);
3689 t!("", file_stem: None, extension: None);
3693 pub fn test_push() {
3695 ($path:expr, $push:expr, $expected:expr) => ( {
3696 let mut actual = PathBuf::from($path);
3698 assert!(actual.to_str() == Some($expected),
3699 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3700 $push, $path, $expected, actual.to_str().unwrap());
3704 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3705 tp!("", "foo", "foo");
3706 tp!("foo", "bar", "foo/bar");
3707 tp!("foo/", "bar", "foo/bar");
3708 tp!("foo//", "bar", "foo//bar");
3709 tp!("foo/.", "bar", "foo/./bar");
3710 tp!("foo./.", "bar", "foo././bar");
3711 tp!("foo", "", "foo/");
3712 tp!("foo", ".", "foo/.");
3713 tp!("foo", "..", "foo/..");
3714 tp!("foo", "/", "/");
3715 tp!("/foo/bar", "/", "/");
3716 tp!("/foo/bar", "/baz", "/baz");
3717 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3719 tp!("", "foo", "foo");
3720 tp!("foo", "bar", r"foo\bar");
3721 tp!("foo/", "bar", r"foo/bar");
3722 tp!(r"foo\", "bar", r"foo\bar");
3723 tp!("foo//", "bar", r"foo//bar");
3724 tp!(r"foo\\", "bar", r"foo\\bar");
3725 tp!("foo/.", "bar", r"foo/.\bar");
3726 tp!("foo./.", "bar", r"foo./.\bar");
3727 tp!(r"foo\.", "bar", r"foo\.\bar");
3728 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3729 tp!("foo", "", "foo\\");
3730 tp!("foo", ".", r"foo\.");
3731 tp!("foo", "..", r"foo\..");
3732 tp!("foo", "/", "/");
3733 tp!("foo", r"\", r"\");
3734 tp!("/foo/bar", "/", "/");
3735 tp!(r"\foo\bar", r"\", r"\");
3736 tp!("/foo/bar", "/baz", "/baz");
3737 tp!("/foo/bar", r"\baz", r"\baz");
3738 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3739 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3741 tp!("c:\\", "windows", "c:\\windows");
3742 tp!("c:", "windows", "c:windows");
3744 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3745 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3746 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3747 tp!("a\\b", "\\c\\d", "\\c\\d");
3748 tp!("a\\b", ".", "a\\b\\.");
3749 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3750 tp!("a\\b", "C:a.txt", "C:a.txt");
3751 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3752 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3753 tp!("C:\\a\\b\\c", "C:d", "C:d");
3754 tp!("C:a\\b\\c", "C:d", "C:d");
3755 tp!("C:", r"a\b\c", r"C:a\b\c");
3756 tp!("C:", r"..\a", r"C:..\a");
3757 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
3758 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3759 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3760 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3761 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3762 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3763 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
3764 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3765 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3767 // Note: modified from old path API
3768 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3770 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
3771 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3772 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3773 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3774 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3776 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3783 ($path:expr, $expected:expr, $output:expr) => ( {
3784 let mut actual = PathBuf::from($path);
3785 let output = actual.pop();
3786 assert!(actual.to_str() == Some($expected) && output == $output,
3787 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3788 $path, $expected, $output,
3789 actual.to_str().unwrap(), output);
3794 tp!("/", "/", false);
3795 tp!("foo", "", true);
3797 tp!("/foo", "/", true);
3798 tp!("/foo/bar", "/foo", true);
3799 tp!("foo/bar", "foo", true);
3800 tp!("foo/.", "", true);
3801 tp!("foo//bar", "foo", true);
3804 tp!("a\\b\\c", "a\\b", true);
3805 tp!("\\a", "\\", true);
3806 tp!("\\", "\\", false);
3808 tp!("C:\\a\\b", "C:\\a", true);
3809 tp!("C:\\a", "C:\\", true);
3810 tp!("C:\\", "C:\\", false);
3811 tp!("C:a\\b", "C:a", true);
3812 tp!("C:a", "C:", true);
3813 tp!("C:", "C:", false);
3814 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3815 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3816 tp!("\\\\server\\share", "\\\\server\\share", false);
3817 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3818 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3819 tp!("\\\\?\\a", "\\\\?\\a", false);
3820 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3821 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3822 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3823 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
3824 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
3825 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
3826 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3827 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3828 tp!("\\\\.\\a", "\\\\.\\a", false);
3830 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3835 pub fn test_set_file_name() {
3837 ($path:expr, $file:expr, $expected:expr) => ( {
3838 let mut p = PathBuf::from($path);
3839 p.set_file_name($file);
3840 assert!(p.to_str() == Some($expected),
3841 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3842 $path, $file, $expected,
3843 p.to_str().unwrap());
3847 tfn!("foo", "foo", "foo");
3848 tfn!("foo", "bar", "bar");
3849 tfn!("foo", "", "");
3850 tfn!("", "foo", "foo");
3851 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3852 tfn!(".", "foo", "./foo");
3853 tfn!("foo/", "bar", "bar");
3854 tfn!("foo/.", "bar", "bar");
3855 tfn!("..", "foo", "../foo");
3856 tfn!("foo/..", "bar", "foo/../bar");
3857 tfn!("/", "foo", "/foo");
3859 tfn!(".", "foo", r".\foo");
3860 tfn!(r"foo\", "bar", r"bar");
3861 tfn!(r"foo\.", "bar", r"bar");
3862 tfn!("..", "foo", r"..\foo");
3863 tfn!(r"foo\..", "bar", r"foo\..\bar");
3864 tfn!(r"\", "foo", r"\foo");
3869 pub fn test_set_extension() {
3871 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3872 let mut p = PathBuf::from($path);
3873 let output = p.set_extension($ext);
3874 assert!(p.to_str() == Some($expected) && output == $output,
3875 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3876 $path, $ext, $expected, $output,
3877 p.to_str().unwrap(), output);
3881 tfe!("foo", "txt", "foo.txt", true);
3882 tfe!("foo.bar", "txt", "foo.txt", true);
3883 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3884 tfe!(".test", "txt", ".test.txt", true);
3885 tfe!("foo.txt", "", "foo", true);
3886 tfe!("foo", "", "foo", true);
3887 tfe!("", "foo", "", false);
3888 tfe!(".", "foo", ".", false);
3889 tfe!("foo/", "bar", "foo.bar", true);
3890 tfe!("foo/.", "bar", "foo.bar", true);
3891 tfe!("..", "foo", "..", false);
3892 tfe!("foo/..", "bar", "foo/..", false);
3893 tfe!("/", "foo", "/", false);
3897 fn test_eq_receivers() {
3898 use crate::borrow::Cow;
3900 let borrowed: &Path = Path::new("foo/bar");
3901 let mut owned: PathBuf = PathBuf::new();
3904 let borrowed_cow: Cow<'_, Path> = borrowed.into();
3905 let owned_cow: Cow<'_, Path> = owned.clone().into();
3908 ($($current:expr),+) => {
3910 assert_eq!($current, borrowed);
3911 assert_eq!($current, owned);
3912 assert_eq!($current, borrowed_cow);
3913 assert_eq!($current, owned_cow);
3918 t!(borrowed, owned, borrowed_cow, owned_cow);
3922 pub fn test_compare() {
3923 use crate::collections::hash_map::DefaultHasher;
3924 use crate::hash::{Hash, Hasher};
3926 fn hash<T: Hash>(t: T) -> u64 {
3927 let mut s = DefaultHasher::new();
3933 ($path1:expr, $path2:expr, eq: $eq:expr,
3934 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3935 relative_from: $relative_from:expr) => ({
3936 let path1 = Path::new($path1);
3937 let path2 = Path::new($path2);
3939 let eq = path1 == path2;
3940 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3941 $path1, $path2, $eq, eq);
3942 assert!($eq == (hash(path1) == hash(path2)),
3943 "{:?} == {:?}, expected {:?}, got {} and {}",
3944 $path1, $path2, $eq, hash(path1), hash(path2));
3946 let starts_with = path1.starts_with(path2);
3947 assert!(starts_with == $starts_with,
3948 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3949 $starts_with, starts_with);
3951 let ends_with = path1.ends_with(path2);
3952 assert!(ends_with == $ends_with,
3953 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3954 $ends_with, ends_with);
3956 let relative_from = path1.strip_prefix(path2)
3957 .map(|p| p.to_str().unwrap())
3959 let exp: Option<&str> = $relative_from;
3960 assert!(relative_from == exp,
3961 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3962 $path1, $path2, exp, relative_from);
3970 relative_from: Some("")
3977 relative_from: Some("foo")
3991 relative_from: Some("")
3998 relative_from: Some("")
4001 tc!("foo/bar", "foo",
4005 relative_from: Some("bar")
4008 tc!("foo/bar/baz", "foo/bar",
4012 relative_from: Some("baz")
4015 tc!("foo/bar", "foo/bar/baz",
4022 tc!("./foo/bar/", ".",
4026 relative_from: Some("foo/bar")
4030 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4031 r"c:\src\rust\cargo-test\test",
4035 relative_from: Some("Cargo.toml")
4038 tc!(r"c:\foo", r"C:\foo",
4042 relative_from: Some("")
4048 fn test_components_debug() {
4049 let path = Path::new("/tmp");
4051 let mut components = path.components();
4053 let expected = "Components([RootDir, Normal(\"tmp\")])";
4054 let actual = format!("{:?}", components);
4055 assert_eq!(expected, actual);
4057 let _ = components.next().unwrap();
4058 let expected = "Components([Normal(\"tmp\")])";
4059 let actual = format!("{:?}", components);
4060 assert_eq!(expected, actual);
4062 let _ = components.next().unwrap();
4063 let expected = "Components([])";
4064 let actual = format!("{:?}", components);
4065 assert_eq!(expected, actual);
4070 fn test_iter_debug() {
4071 let path = Path::new("/tmp");
4073 let mut iter = path.iter();
4075 let expected = "Iter([\"/\", \"tmp\"])";
4076 let actual = format!("{:?}", iter);
4077 assert_eq!(expected, actual);
4079 let _ = iter.next().unwrap();
4080 let expected = "Iter([\"tmp\"])";
4081 let actual = format!("{:?}", iter);
4082 assert_eq!(expected, actual);
4084 let _ = iter.next().unwrap();
4085 let expected = "Iter([])";
4086 let actual = format!("{:?}", iter);
4087 assert_eq!(expected, actual);
4092 let orig: &str = "some/sort/of/path";
4093 let path = Path::new(orig);
4094 let boxed: Box<Path> = Box::from(path);
4095 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4096 assert_eq!(path, &*boxed);
4097 assert_eq!(&*boxed, &*path_buf);
4098 assert_eq!(&*path_buf, path);
4102 fn test_clone_into() {
4103 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4104 let path = Path::new("short");
4105 path.clone_into(&mut path_buf);
4106 assert_eq!(path, path_buf);
4107 assert!(path_buf.into_os_string().capacity() >= 15);
4111 fn display_format_flags() {
4112 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4113 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4118 let orig = "hello/world";
4119 let path = Path::new(orig);
4120 let rc: Rc<Path> = Rc::from(path);
4121 let arc: Arc<Path> = Arc::from(path);
4123 assert_eq!(&*rc, path);
4124 assert_eq!(&*arc, path);
4126 let rc2: Rc<Path> = Rc::from(path.to_owned());
4127 let arc2: Arc<Path> = Arc::from(path.to_owned());
4129 assert_eq!(&*rc2, path);
4130 assert_eq!(&*arc2, path);