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 //! [`Component`]: ../../std/path/enum.Component.html
60 //! [`components`]: ../../std/path/struct.Path.html#method.components
61 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
62 //! [`Path`]: ../../std/path/struct.Path.html
63 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
64 //! [`String`]: ../../std/string/struct.String.html
66 //! [`str`]: ../../std/primitive.str.html
67 //! [`OsString`]: ../../std/ffi/struct.OsString.html
68 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
70 #![stable(feature = "rust1", since = "1.0.0")]
72 use crate::borrow::{Borrow, Cow};
74 use crate::error::Error;
77 use crate::hash::{Hash, Hasher};
79 use crate::iter::{self, FusedIterator};
80 use crate::ops::{self, Deref};
82 use crate::str::FromStr;
85 use crate::ffi::{OsStr, OsString};
87 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
89 ////////////////////////////////////////////////////////////////////////////////
91 ////////////////////////////////////////////////////////////////////////////////
93 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
94 // taking advantage of the fact that OsStr always encodes ASCII characters
95 // as-is. Eventually, this transmutation should be replaced by direct uses of
96 // OsStr APIs for parsing, but it will take a while for those to become
99 ////////////////////////////////////////////////////////////////////////////////
101 ////////////////////////////////////////////////////////////////////////////////
103 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
105 /// Windows uses a variety of path prefix styles, including references to drive
106 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
107 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
108 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
109 /// no normalization is performed.
114 /// use std::path::{Component, Path, Prefix};
115 /// use std::path::Prefix::*;
116 /// use std::ffi::OsStr;
118 /// fn get_path_prefix(s: &str) -> Prefix {
119 /// let path = Path::new(s);
120 /// match path.components().next().unwrap() {
121 /// Component::Prefix(prefix_component) => prefix_component.kind(),
126 /// # if cfg!(windows) {
127 /// assert_eq!(Verbatim(OsStr::new("pictures")),
128 /// get_path_prefix(r"\\?\pictures\kittens"));
129 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
130 /// get_path_prefix(r"\\?\UNC\server\share"));
131 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
132 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
133 /// get_path_prefix(r"\\.\BrainInterface"));
134 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
135 /// get_path_prefix(r"\\server\share"));
136 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
139 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub enum Prefix<'a> {
142 /// Verbatim prefix, e.g., `\\?\cat_pics`.
144 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
146 #[stable(feature = "rust1", since = "1.0.0")]
147 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
149 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
150 /// e.g., `\\?\UNC\server\share`.
152 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
153 /// server's hostname and a share name.
154 #[stable(feature = "rust1", since = "1.0.0")]
156 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
157 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
160 /// Verbatim disk prefix, e.g., `\\?\C:\`.
162 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
163 /// drive letter and `:\`.
164 #[stable(feature = "rust1", since = "1.0.0")]
165 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
167 /// Device namespace prefix, e.g., `\\.\COM42`.
169 /// Device namespace prefixes consist of `\\.\` immediately followed by the
171 #[stable(feature = "rust1", since = "1.0.0")]
172 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
174 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
175 /// `\\server\share`.
177 /// UNC prefixes consist of the server's hostname and a share name.
178 #[stable(feature = "rust1", since = "1.0.0")]
180 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
181 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
184 /// Prefix `C:` for the given disk drive.
185 #[stable(feature = "rust1", since = "1.0.0")]
186 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
189 impl<'a> Prefix<'a> {
191 fn len(&self) -> usize {
193 fn os_str_len(s: &OsStr) -> usize {
194 os_str_as_u8_slice(s).len()
197 Verbatim(x) => 4 + os_str_len(x),
198 VerbatimUNC(x, y) => {
199 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
201 VerbatimDisk(_) => 6,
202 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
203 DeviceNS(x) => 4 + os_str_len(x),
208 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
213 /// use std::path::Prefix::*;
214 /// use std::ffi::OsStr;
216 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
217 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
218 /// assert!(VerbatimDisk(b'C').is_verbatim());
219 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
220 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
221 /// assert!(!Disk(b'C').is_verbatim());
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn is_verbatim(&self) -> bool {
228 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
234 fn is_drive(&self) -> bool {
236 Prefix::Disk(_) => true,
242 fn has_implicit_root(&self) -> bool {
247 ////////////////////////////////////////////////////////////////////////////////
248 // Exposed parsing helpers
249 ////////////////////////////////////////////////////////////////////////////////
251 /// Determines whether the character is one of the permitted path
252 /// separators for the current platform.
259 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
260 /// assert!(!path::is_separator('❤'));
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn is_separator(c: char) -> bool {
264 c.is_ascii() && is_sep_byte(c as u8)
267 /// The primary separator of path components for the current platform.
269 /// For example, `/` on Unix and `\` on Windows.
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
273 ////////////////////////////////////////////////////////////////////////////////
275 ////////////////////////////////////////////////////////////////////////////////
277 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
278 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
279 // `iter` after having exhausted `prefix`.
280 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
282 I: Iterator<Item = Component<'a>> + Clone,
283 J: Iterator<Item = Component<'b>>,
286 let mut iter_next = iter.clone();
287 match (iter_next.next(), prefix.next()) {
288 (Some(ref x), Some(ref y)) if x == y => (),
289 (Some(_), Some(_)) => return None,
290 (Some(_), None) => return Some(iter),
291 (None, None) => return Some(iter),
292 (None, Some(_)) => return None,
298 // See note at the top of this module to understand why these are used:
300 // These casts are safe as OsStr is internally a wrapper around [u8] on all
303 // Note that currently this relies on the special knowledge that libstd has;
304 // these types are single-element structs but are not marked repr(transparent)
305 // or repr(C) which would make these casts allowable outside std.
306 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
307 unsafe { &*(s as *const OsStr as *const [u8]) }
309 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
310 &*(s as *const [u8] as *const OsStr)
313 // Detect scheme on Redox
314 fn has_redox_scheme(s: &[u8]) -> bool {
315 cfg!(target_os = "redox") && s.contains(&b':')
318 ////////////////////////////////////////////////////////////////////////////////
319 // Cross-platform, iterator-independent parsing
320 ////////////////////////////////////////////////////////////////////////////////
322 /// Says whether the first byte after the prefix is a separator.
323 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
324 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
325 !path.is_empty() && is_sep_byte(path[0])
328 // basic workhorse for splitting stem and extension
329 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
331 if os_str_as_u8_slice(file) == b".." {
332 return (Some(file), None);
335 // The unsafety here stems from converting between &OsStr and &[u8]
336 // and back. This is safe to do because (1) we only look at ASCII
337 // contents of the encoding and (2) new &OsStr values are produced
338 // only from ASCII-bounded slices of existing &OsStr values.
340 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
341 let after = iter.next();
342 let before = iter.next();
343 if before == Some(b"") {
346 (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s)))
351 ////////////////////////////////////////////////////////////////////////////////
352 // The core iterators
353 ////////////////////////////////////////////////////////////////////////////////
355 /// Component parsing works by a double-ended state machine; the cursors at the
356 /// front and back of the path each keep track of what parts of the path have
357 /// been consumed so far.
359 /// Going front to back, a path is made up of a prefix, a starting
360 /// directory component, and a body (of normal components)
361 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
364 StartDir = 1, // / or . or nothing
365 Body = 2, // foo/bar/baz
369 /// A structure wrapping a Windows path prefix as well as its unparsed string
372 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
373 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
374 /// returned by [`as_os_str`].
376 /// Instances of this `struct` can be obtained by matching against the
377 /// [`Prefix` variant] on [`Component`].
379 /// Does not occur on Unix.
384 /// # if cfg!(windows) {
385 /// use std::path::{Component, Path, Prefix};
386 /// use std::ffi::OsStr;
388 /// let path = Path::new(r"c:\you\later\");
389 /// match path.components().next().unwrap() {
390 /// Component::Prefix(prefix_component) => {
391 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
392 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
394 /// _ => unreachable!(),
399 /// [`as_os_str`]: #method.as_os_str
400 /// [`Component`]: enum.Component.html
401 /// [`kind`]: #method.kind
402 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
403 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
404 /// [`Prefix`]: enum.Prefix.html
405 #[stable(feature = "rust1", since = "1.0.0")]
406 #[derive(Copy, Clone, Eq, Debug)]
407 pub struct PrefixComponent<'a> {
408 /// The prefix as an unparsed `OsStr` slice.
411 /// The parsed prefix data.
415 impl<'a> PrefixComponent<'a> {
416 /// Returns the parsed prefix data.
418 /// See [`Prefix`]'s documentation for more information on the different
419 /// kinds of prefixes.
421 /// [`Prefix`]: enum.Prefix.html
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn kind(&self) -> Prefix<'a> {
427 /// Returns the raw [`OsStr`] slice for this prefix.
429 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn as_os_str(&self) -> &'a OsStr {
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
438 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
439 cmp::PartialEq::eq(&self.parsed, &other.parsed)
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
445 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
446 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl cmp::Ord for PrefixComponent<'_> {
452 fn cmp(&self, other: &Self) -> cmp::Ordering {
453 cmp::Ord::cmp(&self.parsed, &other.parsed)
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl Hash for PrefixComponent<'_> {
459 fn hash<H: Hasher>(&self, h: &mut H) {
464 /// A single component of a path.
466 /// A `Component` roughly corresponds to a substring between path separators
469 /// This `enum` is created by iterating over [`Components`], which in turn is
470 /// created by the [`components`][`Path::components`] method on [`Path`].
475 /// use std::path::{Component, Path};
477 /// let path = Path::new("/tmp/foo/bar.txt");
478 /// let components = path.components().collect::<Vec<_>>();
479 /// assert_eq!(&components, &[
480 /// Component::RootDir,
481 /// Component::Normal("tmp".as_ref()),
482 /// Component::Normal("foo".as_ref()),
483 /// Component::Normal("bar.txt".as_ref()),
487 /// [`Components`]: struct.Components.html
488 /// [`Path`]: struct.Path.html
489 /// [`Path::components`]: struct.Path.html#method.components
490 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub enum Component<'a> {
493 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
495 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
498 /// Does not occur on Unix.
500 /// [`Prefix`]: enum.Prefix.html
501 #[stable(feature = "rust1", since = "1.0.0")]
502 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
504 /// The root directory component, appears after any prefix and before anything else.
506 /// It represents a separator that designates that a path starts from root.
507 #[stable(feature = "rust1", since = "1.0.0")]
510 /// A reference to the current directory, i.e., `.`.
511 #[stable(feature = "rust1", since = "1.0.0")]
514 /// A reference to the parent directory, i.e., `..`.
515 #[stable(feature = "rust1", since = "1.0.0")]
518 /// A normal component, e.g., `a` and `b` in `a/b`.
520 /// This variant is the most common one, it represents references to files
522 #[stable(feature = "rust1", since = "1.0.0")]
523 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
526 impl<'a> Component<'a> {
527 /// Extracts the underlying [`OsStr`] slice.
532 /// use std::path::Path;
534 /// let path = Path::new("./tmp/foo/bar.txt");
535 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
536 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
539 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn as_os_str(self) -> &'a OsStr {
543 Component::Prefix(p) => p.as_os_str(),
544 Component::RootDir => OsStr::new(MAIN_SEP_STR),
545 Component::CurDir => OsStr::new("."),
546 Component::ParentDir => OsStr::new(".."),
547 Component::Normal(path) => path,
552 #[stable(feature = "rust1", since = "1.0.0")]
553 impl AsRef<OsStr> for Component<'_> {
554 fn as_ref(&self) -> &OsStr {
559 #[stable(feature = "path_component_asref", since = "1.25.0")]
560 impl AsRef<Path> for Component<'_> {
561 fn as_ref(&self) -> &Path {
562 self.as_os_str().as_ref()
566 /// An iterator over the [`Component`]s of a [`Path`].
568 /// This `struct` is created by the [`components`] method on [`Path`].
569 /// See its documentation for more.
574 /// use std::path::Path;
576 /// let path = Path::new("/tmp/foo/bar.txt");
578 /// for component in path.components() {
579 /// println!("{:?}", component);
583 /// [`Component`]: enum.Component.html
584 /// [`components`]: struct.Path.html#method.components
585 /// [`Path`]: struct.Path.html
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub struct Components<'a> {
589 // The path left to parse components from
592 // The prefix as it was originally parsed, if any
593 prefix: Option<Prefix<'a>>,
595 // true if path *physically* has a root separator; for most Windows
596 // prefixes, it may have a "logical" rootseparator for the purposes of
597 // normalization, e.g., \\server\share == \\server\share\.
598 has_physical_root: bool,
600 // The iterator is double-ended, and these two states keep track of what has
601 // been produced from either end
606 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
608 /// This `struct` is created by the [`iter`] method on [`Path`].
609 /// See its documentation for more.
611 /// [`Component`]: enum.Component.html
612 /// [`iter`]: struct.Path.html#method.iter
613 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
614 /// [`Path`]: struct.Path.html
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub struct Iter<'a> {
618 inner: Components<'a>,
621 #[stable(feature = "path_components_debug", since = "1.13.0")]
622 impl fmt::Debug for Components<'_> {
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 struct DebugHelper<'a>(&'a Path);
626 impl fmt::Debug for DebugHelper<'_> {
627 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 f.debug_list().entries(self.0.components()).finish()
632 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
636 impl<'a> Components<'a> {
637 // how long is the prefix, if any?
639 fn prefix_len(&self) -> usize {
640 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
644 fn prefix_verbatim(&self) -> bool {
645 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
648 /// how much of the prefix is left from the point of view of iteration?
650 fn prefix_remaining(&self) -> usize {
651 if self.front == State::Prefix { self.prefix_len() } else { 0 }
654 // Given the iteration so far, how much of the pre-State::Body path is left?
656 fn len_before_body(&self) -> usize {
657 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
658 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
659 self.prefix_remaining() + root + cur_dir
662 // is the iteration complete?
664 fn finished(&self) -> bool {
665 self.front == State::Done || self.back == State::Done || self.front > self.back
669 fn is_sep_byte(&self, b: u8) -> bool {
670 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
673 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
678 /// use std::path::Path;
680 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
681 /// components.next();
682 /// components.next();
684 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn as_path(&self) -> &'a Path {
688 let mut comps = self.clone();
689 if comps.front == State::Body {
692 if comps.back == State::Body {
695 unsafe { Path::from_u8_slice(comps.path) }
698 /// Is the *original* path rooted?
699 fn has_root(&self) -> bool {
700 if self.has_physical_root {
703 if let Some(p) = self.prefix {
704 if p.has_implicit_root() {
711 /// Should the normalized path include a leading . ?
712 fn include_cur_dir(&self) -> bool {
716 let mut iter = self.path[self.prefix_len()..].iter();
717 match (iter.next(), iter.next()) {
718 (Some(&b'.'), None) => true,
719 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
724 // parse a given byte sequence into the corresponding path component
725 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
727 b"." if self.prefix_verbatim() => Some(Component::CurDir),
728 b"." => None, // . components are normalized away, except at
729 // the beginning of a path, which is treated
730 // separately via `include_cur_dir`
731 b".." => Some(Component::ParentDir),
733 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
737 // parse a component from the left, saying how many bytes to consume to
738 // remove the component
739 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
740 debug_assert!(self.front == State::Body);
741 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
742 None => (0, self.path),
743 Some(i) => (1, &self.path[..i]),
745 (comp.len() + extra, self.parse_single_component(comp))
748 // parse a component from the right, saying how many bytes to consume to
749 // remove the component
750 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
751 debug_assert!(self.back == State::Body);
752 let start = self.len_before_body();
753 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
754 None => (0, &self.path[start..]),
755 Some(i) => (1, &self.path[start + i + 1..]),
757 (comp.len() + extra, self.parse_single_component(comp))
760 // trim away repeated separators (i.e., empty components) on the left
761 fn trim_left(&mut self) {
762 while !self.path.is_empty() {
763 let (size, comp) = self.parse_next_component();
767 self.path = &self.path[size..];
772 // trim away repeated separators (i.e., empty components) on the right
773 fn trim_right(&mut self) {
774 while self.path.len() > self.len_before_body() {
775 let (size, comp) = self.parse_next_component_back();
779 self.path = &self.path[..self.path.len() - size];
785 #[stable(feature = "rust1", since = "1.0.0")]
786 impl AsRef<Path> for Components<'_> {
787 fn as_ref(&self) -> &Path {
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl AsRef<OsStr> for Components<'_> {
794 fn as_ref(&self) -> &OsStr {
795 self.as_path().as_os_str()
799 #[stable(feature = "path_iter_debug", since = "1.13.0")]
800 impl fmt::Debug for Iter<'_> {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 struct DebugHelper<'a>(&'a Path);
804 impl fmt::Debug for DebugHelper<'_> {
805 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806 f.debug_list().entries(self.0.iter()).finish()
810 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
815 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
820 /// use std::path::Path;
822 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
826 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub fn as_path(&self) -> &'a Path {
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl AsRef<Path> for Iter<'_> {
836 fn as_ref(&self) -> &Path {
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl AsRef<OsStr> for Iter<'_> {
843 fn as_ref(&self) -> &OsStr {
844 self.as_path().as_os_str()
848 #[stable(feature = "rust1", since = "1.0.0")]
849 impl<'a> Iterator for Iter<'a> {
850 type Item = &'a OsStr;
852 fn next(&mut self) -> Option<&'a OsStr> {
853 self.inner.next().map(Component::as_os_str)
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<'a> DoubleEndedIterator for Iter<'a> {
859 fn next_back(&mut self) -> Option<&'a OsStr> {
860 self.inner.next_back().map(Component::as_os_str)
864 #[stable(feature = "fused", since = "1.26.0")]
865 impl FusedIterator for Iter<'_> {}
867 #[stable(feature = "rust1", since = "1.0.0")]
868 impl<'a> Iterator for Components<'a> {
869 type Item = Component<'a>;
871 fn next(&mut self) -> Option<Component<'a>> {
872 while !self.finished() {
874 State::Prefix if self.prefix_len() > 0 => {
875 self.front = State::StartDir;
876 debug_assert!(self.prefix_len() <= self.path.len());
877 let raw = &self.path[..self.prefix_len()];
878 self.path = &self.path[self.prefix_len()..];
879 return Some(Component::Prefix(PrefixComponent {
880 raw: unsafe { u8_slice_as_os_str(raw) },
881 parsed: self.prefix.unwrap(),
885 self.front = State::StartDir;
888 self.front = State::Body;
889 if self.has_physical_root {
890 debug_assert!(!self.path.is_empty());
891 self.path = &self.path[1..];
892 return Some(Component::RootDir);
893 } else if let Some(p) = self.prefix {
894 if p.has_implicit_root() && !p.is_verbatim() {
895 return Some(Component::RootDir);
897 } else if self.include_cur_dir() {
898 debug_assert!(!self.path.is_empty());
899 self.path = &self.path[1..];
900 return Some(Component::CurDir);
903 State::Body if !self.path.is_empty() => {
904 let (size, comp) = self.parse_next_component();
905 self.path = &self.path[size..];
911 self.front = State::Done;
913 State::Done => unreachable!(),
920 #[stable(feature = "rust1", since = "1.0.0")]
921 impl<'a> DoubleEndedIterator for Components<'a> {
922 fn next_back(&mut self) -> Option<Component<'a>> {
923 while !self.finished() {
925 State::Body if self.path.len() > self.len_before_body() => {
926 let (size, comp) = self.parse_next_component_back();
927 self.path = &self.path[..self.path.len() - size];
933 self.back = State::StartDir;
936 self.back = State::Prefix;
937 if self.has_physical_root {
938 self.path = &self.path[..self.path.len() - 1];
939 return Some(Component::RootDir);
940 } else if let Some(p) = self.prefix {
941 if p.has_implicit_root() && !p.is_verbatim() {
942 return Some(Component::RootDir);
944 } else if self.include_cur_dir() {
945 self.path = &self.path[..self.path.len() - 1];
946 return Some(Component::CurDir);
949 State::Prefix if self.prefix_len() > 0 => {
950 self.back = State::Done;
951 return Some(Component::Prefix(PrefixComponent {
952 raw: unsafe { u8_slice_as_os_str(self.path) },
953 parsed: self.prefix.unwrap(),
957 self.back = State::Done;
960 State::Done => unreachable!(),
967 #[stable(feature = "fused", since = "1.26.0")]
968 impl FusedIterator for Components<'_> {}
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<'a> cmp::PartialEq for Components<'a> {
972 fn eq(&self, other: &Components<'a>) -> bool {
973 Iterator::eq(self.clone(), other.clone())
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl cmp::Eq for Components<'_> {}
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<'a> cmp::PartialOrd for Components<'a> {
982 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
983 Iterator::partial_cmp(self.clone(), other.clone())
987 #[stable(feature = "rust1", since = "1.0.0")]
988 impl cmp::Ord for Components<'_> {
989 fn cmp(&self, other: &Self) -> cmp::Ordering {
990 Iterator::cmp(self.clone(), other.clone())
994 /// An iterator over [`Path`] and its ancestors.
996 /// This `struct` is created by the [`ancestors`] method on [`Path`].
997 /// See its documentation for more.
1002 /// use std::path::Path;
1004 /// let path = Path::new("/foo/bar");
1006 /// for ancestor in path.ancestors() {
1007 /// println!("{}", ancestor.display());
1011 /// [`ancestors`]: struct.Path.html#method.ancestors
1012 /// [`Path`]: struct.Path.html
1013 #[derive(Copy, Clone, Debug)]
1014 #[stable(feature = "path_ancestors", since = "1.28.0")]
1015 pub struct Ancestors<'a> {
1016 next: Option<&'a Path>,
1019 #[stable(feature = "path_ancestors", since = "1.28.0")]
1020 impl<'a> Iterator for Ancestors<'a> {
1021 type Item = &'a Path;
1023 fn next(&mut self) -> Option<Self::Item> {
1024 let next = self.next;
1025 self.next = next.and_then(Path::parent);
1030 #[stable(feature = "path_ancestors", since = "1.28.0")]
1031 impl FusedIterator for Ancestors<'_> {}
1033 ////////////////////////////////////////////////////////////////////////////////
1034 // Basic types and traits
1035 ////////////////////////////////////////////////////////////////////////////////
1037 /// An owned, mutable path (akin to [`String`]).
1039 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1040 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1041 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1043 /// [`String`]: ../string/struct.String.html
1044 /// [`Path`]: struct.Path.html
1045 /// [`push`]: struct.PathBuf.html#method.push
1046 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1047 /// [`Deref`]: ../ops/trait.Deref.html
1049 /// More details about the overall approach can be found in
1050 /// the [module documentation](index.html).
1054 /// You can use [`push`] to build up a `PathBuf` from
1058 /// use std::path::PathBuf;
1060 /// let mut path = PathBuf::new();
1062 /// path.push(r"C:\");
1063 /// path.push("windows");
1064 /// path.push("system32");
1066 /// path.set_extension("dll");
1069 /// However, [`push`] is best used for dynamic situations. This is a better way
1070 /// to do this when you know all of the components ahead of time:
1073 /// use std::path::PathBuf;
1075 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1078 /// We can still do better than this! Since these are all strings, we can use
1082 /// use std::path::PathBuf;
1084 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1087 /// Which method works best depends on what kind of situation you're in.
1089 #[stable(feature = "rust1", since = "1.0.0")]
1091 // `PathBuf::as_mut_vec` current implementation relies
1092 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1093 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1094 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1095 // not documented and must not be relied upon.
1096 pub struct PathBuf {
1101 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1102 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1105 /// Allocates an empty `PathBuf`.
1110 /// use std::path::PathBuf;
1112 /// let path = PathBuf::new();
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn new() -> PathBuf {
1116 PathBuf { inner: OsString::new() }
1119 /// Creates a new `PathBuf` with a given capacity used to create the
1120 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1125 /// #![feature(path_buf_capacity)]
1126 /// use std::path::PathBuf;
1128 /// let mut path = PathBuf::with_capacity(10);
1129 /// let capacity = path.capacity();
1131 /// // This push is done without reallocating
1132 /// path.push(r"C:\");
1134 /// assert_eq!(capacity, path.capacity());
1137 /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1138 /// [`OsString`]: ../ffi/struct.OsString.html
1139 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1140 pub fn with_capacity(capacity: usize) -> PathBuf {
1141 PathBuf { inner: OsString::with_capacity(capacity) }
1144 /// Coerces to a [`Path`] slice.
1146 /// [`Path`]: struct.Path.html
1151 /// use std::path::{Path, PathBuf};
1153 /// let p = PathBuf::from("/test");
1154 /// assert_eq!(Path::new("/test"), p.as_path());
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 pub fn as_path(&self) -> &Path {
1161 /// Extends `self` with `path`.
1163 /// If `path` is absolute, it replaces the current path.
1167 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1168 /// replaces everything except for the prefix (if any) of `self`.
1169 /// * if `path` has a prefix but no root, it replaces `self`.
1173 /// Pushing a relative path extends the existing path:
1176 /// use std::path::PathBuf;
1178 /// let mut path = PathBuf::from("/tmp");
1179 /// path.push("file.bk");
1180 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1183 /// Pushing an absolute path replaces the existing path:
1186 /// use std::path::PathBuf;
1188 /// let mut path = PathBuf::from("/tmp");
1189 /// path.push("/etc");
1190 /// assert_eq!(path, PathBuf::from("/etc"));
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1194 self._push(path.as_ref())
1197 fn _push(&mut self, path: &Path) {
1198 // in general, a separator is needed if the rightmost byte is not a separator
1199 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1201 // in the special case of `C:` on Windows, do *not* add a separator
1203 let comps = self.components();
1204 if comps.prefix_len() > 0
1205 && comps.prefix_len() == comps.path.len()
1206 && comps.prefix.unwrap().is_drive()
1212 // absolute `path` replaces `self`
1213 if path.is_absolute() || path.prefix().is_some() {
1214 self.as_mut_vec().truncate(0);
1216 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1217 } else if path.has_root() {
1218 let prefix_len = self.components().prefix_remaining();
1219 self.as_mut_vec().truncate(prefix_len);
1221 // `path` is a pure relative path
1222 } else if need_sep {
1223 self.inner.push(MAIN_SEP_STR);
1226 self.inner.push(path);
1229 /// Truncates `self` to [`self.parent`].
1231 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1232 /// Otherwise, returns `true`.
1234 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1235 /// [`self.parent`]: struct.PathBuf.html#method.parent
1240 /// use std::path::{Path, PathBuf};
1242 /// let mut p = PathBuf::from("/test/test.rs");
1245 /// assert_eq!(Path::new("/test"), p);
1247 /// assert_eq!(Path::new("/"), p);
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn pop(&mut self) -> bool {
1251 match self.parent().map(|p| p.as_u8_slice().len()) {
1253 self.as_mut_vec().truncate(len);
1260 /// Updates [`self.file_name`] to `file_name`.
1262 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1265 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1266 /// `file_name`. The new path will be a sibling of the original path.
1267 /// (That is, it will have the same parent.)
1269 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1270 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1271 /// [`pop`]: struct.PathBuf.html#method.pop
1276 /// use std::path::PathBuf;
1278 /// let mut buf = PathBuf::from("/");
1279 /// assert!(buf.file_name() == None);
1280 /// buf.set_file_name("bar");
1281 /// assert!(buf == PathBuf::from("/bar"));
1282 /// assert!(buf.file_name().is_some());
1283 /// buf.set_file_name("baz.txt");
1284 /// assert!(buf == PathBuf::from("/baz.txt"));
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1288 self._set_file_name(file_name.as_ref())
1291 fn _set_file_name(&mut self, file_name: &OsStr) {
1292 if self.file_name().is_some() {
1293 let popped = self.pop();
1294 debug_assert!(popped);
1296 self.push(file_name);
1299 /// Updates [`self.extension`] to `extension`.
1301 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1302 /// returns `true` and updates the extension otherwise.
1304 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1307 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1308 /// [`self.extension`]: struct.PathBuf.html#method.extension
1309 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1314 /// use std::path::{Path, PathBuf};
1316 /// let mut p = PathBuf::from("/feel/the");
1318 /// p.set_extension("force");
1319 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1321 /// p.set_extension("dark_side");
1322 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1326 self._set_extension(extension.as_ref())
1329 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1330 let file_stem = match self.file_stem() {
1331 None => return false,
1332 Some(f) => os_str_as_u8_slice(f),
1335 // truncate until right after the file stem
1336 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1337 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1338 let v = self.as_mut_vec();
1339 v.truncate(end_file_stem.wrapping_sub(start));
1341 // add the new extension, if any
1342 let new = os_str_as_u8_slice(extension);
1343 if !new.is_empty() {
1344 v.reserve_exact(new.len() + 1);
1346 v.extend_from_slice(new);
1352 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1354 /// [`OsString`]: ../ffi/struct.OsString.html
1359 /// use std::path::PathBuf;
1361 /// let p = PathBuf::from("/the/head");
1362 /// let os_str = p.into_os_string();
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub fn into_os_string(self) -> OsString {
1369 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1371 /// [`Box`]: ../../std/boxed/struct.Box.html
1372 /// [`Path`]: struct.Path.html
1373 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1374 pub fn into_boxed_path(self) -> Box<Path> {
1375 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1376 unsafe { Box::from_raw(rw) }
1379 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1381 /// [`capacity`]: ../ffi/struct.OsString.html#method.capacity
1382 /// [`OsString`]: ../ffi/struct.OsString.html
1383 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1384 pub fn capacity(&self) -> usize {
1385 self.inner.capacity()
1388 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1390 /// [`clear`]: ../ffi/struct.OsString.html#method.clear
1391 /// [`OsString`]: ../ffi/struct.OsString.html
1392 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1393 pub fn clear(&mut self) {
1397 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1399 /// [`reserve`]: ../ffi/struct.OsString.html#method.reserve
1400 /// [`OsString`]: ../ffi/struct.OsString.html
1401 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1402 pub fn reserve(&mut self, additional: usize) {
1403 self.inner.reserve(additional)
1406 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1408 /// [`reserve_exact`]: ../ffi/struct.OsString.html#method.reserve_exact
1409 /// [`OsString`]: ../ffi/struct.OsString.html
1410 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1411 pub fn reserve_exact(&mut self, additional: usize) {
1412 self.inner.reserve_exact(additional)
1415 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1417 /// [`shrink_to_fit`]: ../ffi/struct.OsString.html#method.shrink_to_fit
1418 /// [`OsString`]: ../ffi/struct.OsString.html
1419 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1420 pub fn shrink_to_fit(&mut self) {
1421 self.inner.shrink_to_fit()
1424 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1426 /// [`shrink_to`]: ../ffi/struct.OsString.html#method.shrink_to
1427 /// [`OsString`]: ../ffi/struct.OsString.html
1428 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1429 pub fn shrink_to(&mut self, min_capacity: usize) {
1430 self.inner.shrink_to(min_capacity)
1434 #[stable(feature = "box_from_path", since = "1.17.0")]
1435 impl From<&Path> for Box<Path> {
1436 fn from(path: &Path) -> Box<Path> {
1437 let boxed: Box<OsStr> = path.inner.into();
1438 let rw = Box::into_raw(boxed) as *mut Path;
1439 unsafe { Box::from_raw(rw) }
1443 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1444 impl From<Box<Path>> for PathBuf {
1445 /// Converts a `Box<Path>` into a `PathBuf`
1447 /// This conversion does not allocate or copy memory.
1448 fn from(boxed: Box<Path>) -> PathBuf {
1449 boxed.into_path_buf()
1453 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1454 impl From<PathBuf> for Box<Path> {
1455 /// Converts a `PathBuf` into a `Box<Path>`
1457 /// This conversion currently should not allocate memory,
1458 /// but this behavior is not guaranteed on all platforms or in all future versions.
1459 fn from(p: PathBuf) -> Box<Path> {
1464 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1465 impl Clone for Box<Path> {
1467 fn clone(&self) -> Self {
1468 self.to_path_buf().into_boxed_path()
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1474 fn from(s: &T) -> PathBuf {
1475 PathBuf::from(s.as_ref().to_os_string())
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl From<OsString> for PathBuf {
1481 /// Converts a `OsString` into a `PathBuf`
1483 /// This conversion does not allocate or copy memory.
1484 fn from(s: OsString) -> PathBuf {
1485 PathBuf { inner: s }
1489 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1490 impl From<PathBuf> for OsString {
1491 /// Converts a `PathBuf` into a `OsString`
1493 /// This conversion does not allocate or copy memory.
1494 fn from(path_buf: PathBuf) -> OsString {
1499 #[stable(feature = "rust1", since = "1.0.0")]
1500 impl From<String> for PathBuf {
1501 /// Converts a `String` into a `PathBuf`
1503 /// This conversion does not allocate or copy memory.
1504 fn from(s: String) -> PathBuf {
1505 PathBuf::from(OsString::from(s))
1509 #[stable(feature = "path_from_str", since = "1.32.0")]
1510 impl FromStr for PathBuf {
1511 type Err = core::convert::Infallible;
1513 fn from_str(s: &str) -> Result<Self, Self::Err> {
1514 Ok(PathBuf::from(s))
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1520 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1521 let mut buf = PathBuf::new();
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1529 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1530 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1534 #[stable(feature = "rust1", since = "1.0.0")]
1535 impl fmt::Debug for PathBuf {
1536 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1537 fmt::Debug::fmt(&**self, formatter)
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 impl ops::Deref for PathBuf {
1545 fn deref(&self) -> &Path {
1546 Path::new(&self.inner)
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl Borrow<Path> for PathBuf {
1552 fn borrow(&self) -> &Path {
1557 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1558 impl Default for PathBuf {
1559 fn default() -> Self {
1564 #[stable(feature = "cow_from_path", since = "1.6.0")]
1565 impl<'a> From<&'a Path> for Cow<'a, Path> {
1567 fn from(s: &'a Path) -> Cow<'a, Path> {
1572 #[stable(feature = "cow_from_path", since = "1.6.0")]
1573 impl<'a> From<PathBuf> for Cow<'a, Path> {
1575 fn from(s: PathBuf) -> Cow<'a, Path> {
1580 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1581 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1583 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1584 Cow::Borrowed(p.as_path())
1588 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1589 impl<'a> From<Cow<'a, Path>> for PathBuf {
1591 fn from(p: Cow<'a, Path>) -> Self {
1596 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1597 impl From<PathBuf> for Arc<Path> {
1598 /// Converts a `PathBuf` into an `Arc` by moving the `PathBuf` data into a new `Arc` buffer.
1600 fn from(s: PathBuf) -> Arc<Path> {
1601 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1602 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1606 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1607 impl From<&Path> for Arc<Path> {
1608 /// Converts a `Path` into an `Arc` by copying the `Path` data into a new `Arc` buffer.
1610 fn from(s: &Path) -> Arc<Path> {
1611 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1612 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1616 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1617 impl From<PathBuf> for Rc<Path> {
1618 /// Converts a `PathBuf` into an `Rc` by moving the `PathBuf` data into a new `Rc` buffer.
1620 fn from(s: PathBuf) -> Rc<Path> {
1621 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1622 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1626 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1627 impl From<&Path> for Rc<Path> {
1628 /// Converts a `Path` into an `Rc` by copying the `Path` data into a new `Rc` buffer.
1630 fn from(s: &Path) -> Rc<Path> {
1631 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1632 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl ToOwned for Path {
1638 type Owned = PathBuf;
1639 fn to_owned(&self) -> PathBuf {
1642 fn clone_into(&self, target: &mut PathBuf) {
1643 self.inner.clone_into(&mut target.inner);
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl cmp::PartialEq for PathBuf {
1649 fn eq(&self, other: &PathBuf) -> bool {
1650 self.components() == other.components()
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl Hash for PathBuf {
1656 fn hash<H: Hasher>(&self, h: &mut H) {
1657 self.as_path().hash(h)
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl cmp::Eq for PathBuf {}
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl cmp::PartialOrd for PathBuf {
1666 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1667 self.components().partial_cmp(other.components())
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl cmp::Ord for PathBuf {
1673 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1674 self.components().cmp(other.components())
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 impl AsRef<OsStr> for PathBuf {
1680 fn as_ref(&self) -> &OsStr {
1685 /// A slice of a path (akin to [`str`]).
1687 /// This type supports a number of operations for inspecting a path, including
1688 /// breaking the path into its components (separated by `/` on Unix and by either
1689 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1690 /// is absolute, and so on.
1692 /// This is an *unsized* type, meaning that it must always be used behind a
1693 /// pointer like `&` or [`Box`]. For an owned version of this type,
1694 /// see [`PathBuf`].
1696 /// [`str`]: ../primitive.str.html
1697 /// [`Box`]: ../boxed/struct.Box.html
1698 /// [`PathBuf`]: struct.PathBuf.html
1700 /// More details about the overall approach can be found in
1701 /// the [module documentation](index.html).
1706 /// use std::path::Path;
1707 /// use std::ffi::OsStr;
1709 /// // Note: this example does work on Windows
1710 /// let path = Path::new("./foo/bar.txt");
1712 /// let parent = path.parent();
1713 /// assert_eq!(parent, Some(Path::new("./foo")));
1715 /// let file_stem = path.file_stem();
1716 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1718 /// let extension = path.extension();
1719 /// assert_eq!(extension, Some(OsStr::new("txt")));
1721 #[stable(feature = "rust1", since = "1.0.0")]
1723 // `Path::new` current implementation relies
1724 // on `Path` being layout-compatible with `OsStr`.
1725 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1726 // Anyway, `Path` representation and layout are considered implementation detail, are
1727 // not documented and must not be relied upon.
1732 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1735 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1736 /// See its documentation for more.
1738 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1739 /// [`Path`]: struct.Path.html
1740 #[derive(Debug, Clone, PartialEq, Eq)]
1741 #[stable(since = "1.7.0", feature = "strip_prefix")]
1742 pub struct StripPrefixError(());
1745 // The following (private!) function allows construction of a path from a u8
1746 // slice, which is only safe when it is known to follow the OsStr encoding.
1747 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1748 Path::new(u8_slice_as_os_str(s))
1750 // The following (private!) function reveals the byte encoding used for OsStr.
1751 fn as_u8_slice(&self) -> &[u8] {
1752 os_str_as_u8_slice(&self.inner)
1755 /// Directly wraps a string slice as a `Path` slice.
1757 /// This is a cost-free conversion.
1762 /// use std::path::Path;
1764 /// Path::new("foo.txt");
1767 /// You can create `Path`s from `String`s, or even other `Path`s:
1770 /// use std::path::Path;
1772 /// let string = String::from("foo.txt");
1773 /// let from_string = Path::new(&string);
1774 /// let from_path = Path::new(&from_string);
1775 /// assert_eq!(from_string, from_path);
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1779 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1782 /// Yields the underlying [`OsStr`] slice.
1784 /// [`OsStr`]: ../ffi/struct.OsStr.html
1789 /// use std::path::Path;
1791 /// let os_str = Path::new("foo.txt").as_os_str();
1792 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub fn as_os_str(&self) -> &OsStr {
1799 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1801 /// This conversion may entail doing a check for UTF-8 validity.
1802 /// Note that validation is performed because non-UTF-8 strings are
1803 /// perfectly valid for some OS.
1805 /// [`&str`]: ../primitive.str.html
1810 /// use std::path::Path;
1812 /// let path = Path::new("foo.txt");
1813 /// assert_eq!(path.to_str(), Some("foo.txt"));
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 pub fn to_str(&self) -> Option<&str> {
1820 /// Converts a `Path` to a [`Cow<str>`].
1822 /// Any non-Unicode sequences are replaced with
1823 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1825 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1826 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1830 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1833 /// use std::path::Path;
1835 /// let path = Path::new("foo.txt");
1836 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1839 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1840 /// have returned `"fo�.txt"`.
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1843 self.inner.to_string_lossy()
1846 /// Converts a `Path` to an owned [`PathBuf`].
1848 /// [`PathBuf`]: struct.PathBuf.html
1853 /// use std::path::Path;
1855 /// let path_buf = Path::new("foo.txt").to_path_buf();
1856 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1858 #[rustc_conversion_suggestion]
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 pub fn to_path_buf(&self) -> PathBuf {
1861 PathBuf::from(self.inner.to_os_string())
1864 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1865 /// the current directory.
1867 /// * On Unix, a path is absolute if it starts with the root, so
1868 /// `is_absolute` and [`has_root`] are equivalent.
1870 /// * On Windows, a path is absolute if it has a prefix and starts with the
1871 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1876 /// use std::path::Path;
1878 /// assert!(!Path::new("foo.txt").is_absolute());
1881 /// [`has_root`]: #method.has_root
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 #[allow(deprecated)]
1884 pub fn is_absolute(&self) -> bool {
1885 if cfg!(target_os = "redox") {
1886 // FIXME: Allow Redox prefixes
1887 self.has_root() || has_redox_scheme(self.as_u8_slice())
1889 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1893 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1895 /// See [`is_absolute`]'s documentation for more details.
1900 /// use std::path::Path;
1902 /// assert!(Path::new("foo.txt").is_relative());
1905 /// [`is_absolute`]: #method.is_absolute
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 pub fn is_relative(&self) -> bool {
1911 fn prefix(&self) -> Option<Prefix<'_>> {
1912 self.components().prefix
1915 /// Returns `true` if the `Path` has a root.
1917 /// * On Unix, a path has a root if it begins with `/`.
1919 /// * On Windows, a path has a root if it:
1920 /// * has no prefix and begins with a separator, e.g., `\windows`
1921 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1922 /// * has any non-disk prefix, e.g., `\\server\share`
1927 /// use std::path::Path;
1929 /// assert!(Path::new("/etc/passwd").has_root());
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 pub fn has_root(&self) -> bool {
1933 self.components().has_root()
1936 /// Returns the `Path` without its final component, if there is one.
1938 /// Returns [`None`] if the path terminates in a root or prefix.
1940 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1945 /// use std::path::Path;
1947 /// let path = Path::new("/foo/bar");
1948 /// let parent = path.parent().unwrap();
1949 /// assert_eq!(parent, Path::new("/foo"));
1951 /// let grand_parent = parent.parent().unwrap();
1952 /// assert_eq!(grand_parent, Path::new("/"));
1953 /// assert_eq!(grand_parent.parent(), None);
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 pub fn parent(&self) -> Option<&Path> {
1957 let mut comps = self.components();
1958 let comp = comps.next_back();
1959 comp.and_then(|p| match p {
1960 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
1961 Some(comps.as_path())
1967 /// Produces an iterator over `Path` and its ancestors.
1969 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1970 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1971 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1972 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1978 /// use std::path::Path;
1980 /// let mut ancestors = Path::new("/foo/bar").ancestors();
1981 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1982 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1983 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1984 /// assert_eq!(ancestors.next(), None);
1987 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1988 /// [`parent`]: struct.Path.html#method.parent
1989 #[stable(feature = "path_ancestors", since = "1.28.0")]
1990 pub fn ancestors(&self) -> Ancestors<'_> {
1991 Ancestors { next: Some(&self) }
1994 /// Returns the final component of the `Path`, if there is one.
1996 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1997 /// is the directory name.
1999 /// Returns [`None`] if the path terminates in `..`.
2001 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2006 /// use std::path::Path;
2007 /// use std::ffi::OsStr;
2009 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2010 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2011 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2012 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2013 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2014 /// assert_eq!(None, Path::new("/").file_name());
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 pub fn file_name(&self) -> Option<&OsStr> {
2018 self.components().next_back().and_then(|p| match p {
2019 Component::Normal(p) => Some(p.as_ref()),
2024 /// Returns a path that, when joined onto `base`, yields `self`.
2028 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2029 /// returns `false`), returns [`Err`].
2031 /// [`starts_with`]: #method.starts_with
2032 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2037 /// use std::path::{Path, PathBuf};
2039 /// let path = Path::new("/test/haha/foo.txt");
2041 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2042 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2043 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2044 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2045 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2046 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2047 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2049 /// let prefix = PathBuf::from("/test/");
2050 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2052 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2053 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2057 self._strip_prefix(base.as_ref())
2060 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2061 iter_after(self.components(), base.components())
2062 .map(|c| c.as_path())
2063 .ok_or(StripPrefixError(()))
2066 /// Determines whether `base` is a prefix of `self`.
2068 /// Only considers whole path components to match.
2073 /// use std::path::Path;
2075 /// let path = Path::new("/etc/passwd");
2077 /// assert!(path.starts_with("/etc"));
2078 /// assert!(path.starts_with("/etc/"));
2079 /// assert!(path.starts_with("/etc/passwd"));
2080 /// assert!(path.starts_with("/etc/passwd/"));
2082 /// assert!(!path.starts_with("/e"));
2084 #[stable(feature = "rust1", since = "1.0.0")]
2085 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2086 self._starts_with(base.as_ref())
2089 fn _starts_with(&self, base: &Path) -> bool {
2090 iter_after(self.components(), base.components()).is_some()
2093 /// Determines whether `child` is a suffix of `self`.
2095 /// Only considers whole path components to match.
2100 /// use std::path::Path;
2102 /// let path = Path::new("/etc/passwd");
2104 /// assert!(path.ends_with("passwd"));
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2108 self._ends_with(child.as_ref())
2111 fn _ends_with(&self, child: &Path) -> bool {
2112 iter_after(self.components().rev(), child.components().rev()).is_some()
2115 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2117 /// [`self.file_name`]: struct.Path.html#method.file_name
2121 /// * [`None`], if there is no file name;
2122 /// * The entire file name if there is no embedded `.`;
2123 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2124 /// * Otherwise, the portion of the file name before the final `.`
2126 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2131 /// use std::path::Path;
2133 /// let path = Path::new("foo.rs");
2135 /// assert_eq!("foo", path.file_stem().unwrap());
2137 #[stable(feature = "rust1", since = "1.0.0")]
2138 pub fn file_stem(&self) -> Option<&OsStr> {
2139 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2142 /// Extracts the extension of [`self.file_name`], if possible.
2144 /// The extension is:
2146 /// * [`None`], if there is no file name;
2147 /// * [`None`], if there is no embedded `.`;
2148 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2149 /// * Otherwise, the portion of the file name after the final `.`
2151 /// [`self.file_name`]: struct.Path.html#method.file_name
2152 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2157 /// use std::path::Path;
2159 /// let path = Path::new("foo.rs");
2161 /// assert_eq!("rs", path.extension().unwrap());
2163 #[stable(feature = "rust1", since = "1.0.0")]
2164 pub fn extension(&self) -> Option<&OsStr> {
2165 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2168 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2170 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2172 /// [`PathBuf`]: struct.PathBuf.html
2173 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2178 /// use std::path::{Path, PathBuf};
2180 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2182 #[stable(feature = "rust1", since = "1.0.0")]
2184 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2185 self._join(path.as_ref())
2188 fn _join(&self, path: &Path) -> PathBuf {
2189 let mut buf = self.to_path_buf();
2194 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2196 /// See [`PathBuf::set_file_name`] for more details.
2198 /// [`PathBuf`]: struct.PathBuf.html
2199 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2204 /// use std::path::{Path, PathBuf};
2206 /// let path = Path::new("/tmp/foo.txt");
2207 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2209 /// let path = Path::new("/tmp");
2210 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2212 #[stable(feature = "rust1", since = "1.0.0")]
2213 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2214 self._with_file_name(file_name.as_ref())
2217 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2218 let mut buf = self.to_path_buf();
2219 buf.set_file_name(file_name);
2223 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2225 /// See [`PathBuf::set_extension`] for more details.
2227 /// [`PathBuf`]: struct.PathBuf.html
2228 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2233 /// use std::path::{Path, PathBuf};
2235 /// let path = Path::new("foo.rs");
2236 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2238 #[stable(feature = "rust1", since = "1.0.0")]
2239 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2240 self._with_extension(extension.as_ref())
2243 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2244 let mut buf = self.to_path_buf();
2245 buf.set_extension(extension);
2249 /// Produces an iterator over the [`Component`]s of the path.
2251 /// When parsing the path, there is a small amount of normalization:
2253 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2254 /// `a` and `b` as components.
2256 /// * Occurrences of `.` are normalized away, except if they are at the
2257 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2258 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2259 /// an additional [`CurDir`] component.
2261 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2263 /// Note that no other normalization takes place; in particular, `a/c`
2264 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2265 /// is a symbolic link (so its parent isn't `a`).
2270 /// use std::path::{Path, Component};
2271 /// use std::ffi::OsStr;
2273 /// let mut components = Path::new("/tmp/foo.txt").components();
2275 /// assert_eq!(components.next(), Some(Component::RootDir));
2276 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2277 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2278 /// assert_eq!(components.next(), None)
2281 /// [`Component`]: enum.Component.html
2282 /// [`CurDir`]: enum.Component.html#variant.CurDir
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 pub fn components(&self) -> Components<'_> {
2285 let prefix = parse_prefix(self.as_os_str());
2287 path: self.as_u8_slice(),
2289 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2290 || has_redox_scheme(self.as_u8_slice()),
2291 front: State::Prefix,
2296 /// Produces an iterator over the path's components viewed as [`OsStr`]
2299 /// For more information about the particulars of how the path is separated
2300 /// into components, see [`components`].
2302 /// [`components`]: #method.components
2303 /// [`OsStr`]: ../ffi/struct.OsStr.html
2308 /// use std::path::{self, Path};
2309 /// use std::ffi::OsStr;
2311 /// let mut it = Path::new("/tmp/foo.txt").iter();
2312 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2313 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2314 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2315 /// assert_eq!(it.next(), None)
2317 #[stable(feature = "rust1", since = "1.0.0")]
2318 pub fn iter(&self) -> Iter<'_> {
2319 Iter { inner: self.components() }
2322 /// Returns an object that implements [`Display`] for safely printing paths
2323 /// that may contain non-Unicode data.
2325 /// [`Display`]: ../fmt/trait.Display.html
2330 /// use std::path::Path;
2332 /// let path = Path::new("/tmp/foo.rs");
2334 /// println!("{}", path.display());
2336 #[stable(feature = "rust1", since = "1.0.0")]
2337 pub fn display(&self) -> Display<'_> {
2338 Display { path: self }
2341 /// Queries the file system to get information about a file, directory, etc.
2343 /// This function will traverse symbolic links to query information about the
2344 /// destination file.
2346 /// This is an alias to [`fs::metadata`].
2348 /// [`fs::metadata`]: ../fs/fn.metadata.html
2353 /// use std::path::Path;
2355 /// let path = Path::new("/Minas/tirith");
2356 /// let metadata = path.metadata().expect("metadata call failed");
2357 /// println!("{:?}", metadata.file_type());
2359 #[stable(feature = "path_ext", since = "1.5.0")]
2360 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2364 /// Queries the metadata about a file without following symlinks.
2366 /// This is an alias to [`fs::symlink_metadata`].
2368 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2373 /// use std::path::Path;
2375 /// let path = Path::new("/Minas/tirith");
2376 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2377 /// println!("{:?}", metadata.file_type());
2379 #[stable(feature = "path_ext", since = "1.5.0")]
2380 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2381 fs::symlink_metadata(self)
2384 /// Returns the canonical, absolute form of the path with all intermediate
2385 /// components normalized and symbolic links resolved.
2387 /// This is an alias to [`fs::canonicalize`].
2389 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2394 /// use std::path::{Path, PathBuf};
2396 /// let path = Path::new("/foo/test/../test/bar.rs");
2397 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2399 #[stable(feature = "path_ext", since = "1.5.0")]
2400 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2401 fs::canonicalize(self)
2404 /// Reads a symbolic link, returning the file that the link points to.
2406 /// This is an alias to [`fs::read_link`].
2408 /// [`fs::read_link`]: ../fs/fn.read_link.html
2413 /// use std::path::Path;
2415 /// let path = Path::new("/laputa/sky_castle.rs");
2416 /// let path_link = path.read_link().expect("read_link call failed");
2418 #[stable(feature = "path_ext", since = "1.5.0")]
2419 pub fn read_link(&self) -> io::Result<PathBuf> {
2423 /// Returns an iterator over the entries within a directory.
2425 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2426 /// errors may be encountered after an iterator is initially constructed.
2428 /// This is an alias to [`fs::read_dir`].
2430 /// [`io::Result`]: ../io/type.Result.html
2431 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2432 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2437 /// use std::path::Path;
2439 /// let path = Path::new("/laputa");
2440 /// for entry in path.read_dir().expect("read_dir call failed") {
2441 /// if let Ok(entry) = entry {
2442 /// println!("{:?}", entry.path());
2446 #[stable(feature = "path_ext", since = "1.5.0")]
2447 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2451 /// Returns `true` if the path points at an existing entity.
2453 /// This function will traverse symbolic links to query information about the
2454 /// destination file. In case of broken symbolic links this will return `false`.
2456 /// If you cannot access the directory containing the file, e.g., because of a
2457 /// permission error, this will return `false`.
2462 /// use std::path::Path;
2463 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2468 /// This is a convenience function that coerces errors to false. If you want to
2469 /// check errors, call [fs::metadata].
2471 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2472 #[stable(feature = "path_ext", since = "1.5.0")]
2473 pub fn exists(&self) -> bool {
2474 fs::metadata(self).is_ok()
2477 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2479 /// This function will traverse symbolic links to query information about the
2480 /// destination file. In case of broken symbolic links this will return `false`.
2482 /// If you cannot access the directory containing the file, e.g., because of a
2483 /// permission error, this will return `false`.
2488 /// use std::path::Path;
2489 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2490 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2495 /// This is a convenience function that coerces errors to false. If you want to
2496 /// check errors, call [fs::metadata] and handle its Result. Then call
2497 /// [fs::Metadata::is_file] if it was Ok.
2499 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2500 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2501 #[stable(feature = "path_ext", since = "1.5.0")]
2502 pub fn is_file(&self) -> bool {
2503 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2506 /// Returns `true` if the path exists on disk and is pointing at a directory.
2508 /// This function will traverse symbolic links to query information about the
2509 /// destination file. In case of broken symbolic links this will return `false`.
2511 /// If you cannot access the directory containing the file, e.g., because of a
2512 /// permission error, this will return `false`.
2517 /// use std::path::Path;
2518 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2519 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2524 /// This is a convenience function that coerces errors to false. If you want to
2525 /// check errors, call [fs::metadata] and handle its Result. Then call
2526 /// [fs::Metadata::is_dir] if it was Ok.
2528 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2529 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2530 #[stable(feature = "path_ext", since = "1.5.0")]
2531 pub fn is_dir(&self) -> bool {
2532 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2535 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2538 /// [`Box`]: ../../std/boxed/struct.Box.html
2539 /// [`PathBuf`]: struct.PathBuf.html
2540 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2541 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2542 let rw = Box::into_raw(self) as *mut OsStr;
2543 let inner = unsafe { Box::from_raw(rw) };
2544 PathBuf { inner: OsString::from(inner) }
2548 #[stable(feature = "rust1", since = "1.0.0")]
2549 impl AsRef<OsStr> for Path {
2550 fn as_ref(&self) -> &OsStr {
2555 #[stable(feature = "rust1", since = "1.0.0")]
2556 impl fmt::Debug for Path {
2557 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2558 fmt::Debug::fmt(&self.inner, formatter)
2562 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2564 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2565 /// [`Display`] trait in a way that mitigates that. It is created by the
2566 /// [`display`][`Path::display`] method on [`Path`].
2571 /// use std::path::Path;
2573 /// let path = Path::new("/tmp/foo.rs");
2575 /// println!("{}", path.display());
2578 /// [`Display`]: ../../std/fmt/trait.Display.html
2579 /// [`format!`]: ../../std/macro.format.html
2580 /// [`Path`]: struct.Path.html
2581 /// [`Path::display`]: struct.Path.html#method.display
2582 #[stable(feature = "rust1", since = "1.0.0")]
2583 pub struct Display<'a> {
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 impl fmt::Debug for Display<'_> {
2589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2590 fmt::Debug::fmt(&self.path, f)
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 impl fmt::Display for Display<'_> {
2596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2597 self.path.inner.display(f)
2601 #[stable(feature = "rust1", since = "1.0.0")]
2602 impl cmp::PartialEq for Path {
2603 fn eq(&self, other: &Path) -> bool {
2604 self.components().eq(other.components())
2608 #[stable(feature = "rust1", since = "1.0.0")]
2609 impl Hash for Path {
2610 fn hash<H: Hasher>(&self, h: &mut H) {
2611 for component in self.components() {
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl cmp::Eq for Path {}
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 impl cmp::PartialOrd for Path {
2622 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2623 self.components().partial_cmp(other.components())
2627 #[stable(feature = "rust1", since = "1.0.0")]
2628 impl cmp::Ord for Path {
2629 fn cmp(&self, other: &Path) -> cmp::Ordering {
2630 self.components().cmp(other.components())
2634 #[stable(feature = "rust1", since = "1.0.0")]
2635 impl AsRef<Path> for Path {
2636 fn as_ref(&self) -> &Path {
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 impl AsRef<Path> for OsStr {
2643 fn as_ref(&self) -> &Path {
2648 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2649 impl AsRef<Path> for Cow<'_, OsStr> {
2650 fn as_ref(&self) -> &Path {
2655 #[stable(feature = "rust1", since = "1.0.0")]
2656 impl AsRef<Path> for OsString {
2657 fn as_ref(&self) -> &Path {
2662 #[stable(feature = "rust1", since = "1.0.0")]
2663 impl AsRef<Path> for str {
2664 fn as_ref(&self) -> &Path {
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 impl AsRef<Path> for String {
2671 fn as_ref(&self) -> &Path {
2676 #[stable(feature = "rust1", since = "1.0.0")]
2677 impl AsRef<Path> for PathBuf {
2678 fn as_ref(&self) -> &Path {
2683 #[stable(feature = "path_into_iter", since = "1.6.0")]
2684 impl<'a> IntoIterator for &'a PathBuf {
2685 type Item = &'a OsStr;
2686 type IntoIter = Iter<'a>;
2687 fn into_iter(self) -> Iter<'a> {
2692 #[stable(feature = "path_into_iter", since = "1.6.0")]
2693 impl<'a> IntoIterator for &'a Path {
2694 type Item = &'a OsStr;
2695 type IntoIter = Iter<'a>;
2696 fn into_iter(self) -> Iter<'a> {
2701 macro_rules! impl_cmp {
2702 ($lhs:ty, $rhs: ty) => {
2703 #[stable(feature = "partialeq_path", since = "1.6.0")]
2704 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2706 fn eq(&self, other: &$rhs) -> bool {
2707 <Path as PartialEq>::eq(self, other)
2711 #[stable(feature = "partialeq_path", since = "1.6.0")]
2712 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2714 fn eq(&self, other: &$lhs) -> bool {
2715 <Path as PartialEq>::eq(self, other)
2719 #[stable(feature = "cmp_path", since = "1.8.0")]
2720 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2722 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2723 <Path as PartialOrd>::partial_cmp(self, other)
2727 #[stable(feature = "cmp_path", since = "1.8.0")]
2728 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2730 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2731 <Path as PartialOrd>::partial_cmp(self, other)
2737 impl_cmp!(PathBuf, Path);
2738 impl_cmp!(PathBuf, &'a Path);
2739 impl_cmp!(Cow<'a, Path>, Path);
2740 impl_cmp!(Cow<'a, Path>, &'b Path);
2741 impl_cmp!(Cow<'a, Path>, PathBuf);
2743 macro_rules! impl_cmp_os_str {
2744 ($lhs:ty, $rhs: ty) => {
2745 #[stable(feature = "cmp_path", since = "1.8.0")]
2746 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2748 fn eq(&self, other: &$rhs) -> bool {
2749 <Path as PartialEq>::eq(self, other.as_ref())
2753 #[stable(feature = "cmp_path", since = "1.8.0")]
2754 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2756 fn eq(&self, other: &$lhs) -> bool {
2757 <Path as PartialEq>::eq(self.as_ref(), other)
2761 #[stable(feature = "cmp_path", since = "1.8.0")]
2762 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2764 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2765 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2769 #[stable(feature = "cmp_path", since = "1.8.0")]
2770 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2772 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2773 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2779 impl_cmp_os_str!(PathBuf, OsStr);
2780 impl_cmp_os_str!(PathBuf, &'a OsStr);
2781 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2782 impl_cmp_os_str!(PathBuf, OsString);
2783 impl_cmp_os_str!(Path, OsStr);
2784 impl_cmp_os_str!(Path, &'a OsStr);
2785 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2786 impl_cmp_os_str!(Path, OsString);
2787 impl_cmp_os_str!(&'a Path, OsStr);
2788 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2789 impl_cmp_os_str!(&'a Path, OsString);
2790 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2791 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2792 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2794 #[stable(since = "1.7.0", feature = "strip_prefix")]
2795 impl fmt::Display for StripPrefixError {
2796 #[allow(deprecated, deprecated_in_future)]
2797 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2798 self.description().fmt(f)
2802 #[stable(since = "1.7.0", feature = "strip_prefix")]
2803 impl Error for StripPrefixError {
2804 #[allow(deprecated)]
2805 fn description(&self) -> &str {
2815 use crate::sync::Arc;
2818 ($path:expr, iter: $iter:expr) => (
2820 let path = Path::new($path);
2822 // Forward iteration
2823 let comps = path.iter()
2824 .map(|p| p.to_string_lossy().into_owned())
2825 .collect::<Vec<String>>();
2826 let exp: &[&str] = &$iter;
2827 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2828 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2831 // Reverse iteration
2832 let comps = Path::new($path).iter().rev()
2833 .map(|p| p.to_string_lossy().into_owned())
2834 .collect::<Vec<String>>();
2835 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2836 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2841 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2843 let path = Path::new($path);
2845 let act_root = path.has_root();
2846 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2847 $has_root, act_root);
2849 let act_abs = path.is_absolute();
2850 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2851 $is_absolute, act_abs);
2855 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2857 let path = Path::new($path);
2859 let parent = path.parent().map(|p| p.to_str().unwrap());
2860 let exp_parent: Option<&str> = $parent;
2861 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2862 exp_parent, parent);
2864 let file = path.file_name().map(|p| p.to_str().unwrap());
2865 let exp_file: Option<&str> = $file;
2866 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2871 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2873 let path = Path::new($path);
2875 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2876 let exp_stem: Option<&str> = $file_stem;
2877 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2880 let ext = path.extension().map(|p| p.to_str().unwrap());
2881 let exp_ext: Option<&str> = $extension;
2882 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2887 ($path:expr, iter: $iter:expr,
2888 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2889 parent: $parent:expr, file_name: $file:expr,
2890 file_stem: $file_stem:expr, extension: $extension:expr) => (
2892 t!($path, iter: $iter);
2893 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2894 t!($path, parent: $parent, file_name: $file);
2895 t!($path, file_stem: $file_stem, extension: $extension);
2902 use crate::borrow::Cow;
2904 let static_path = Path::new("/home/foo");
2905 let static_cow_path: Cow<'static, Path> = static_path.into();
2906 let pathbuf = PathBuf::from("/home/foo");
2909 let path: &Path = &pathbuf;
2910 let borrowed_cow_path: Cow<'_, Path> = path.into();
2912 assert_eq!(static_cow_path, borrowed_cow_path);
2915 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2917 assert_eq!(static_cow_path, owned_cow_path);
2922 pub fn test_decompositions_unix() {
2938 file_name: Some("foo"),
2939 file_stem: Some("foo"),
2958 file_name: Some("foo"),
2959 file_stem: Some("foo"),
2968 file_name: Some("foo"),
2969 file_stem: Some("foo"),
2978 file_name: Some("foo"),
2979 file_stem: Some("foo"),
2984 iter: ["foo", "bar"],
2987 parent: Some("foo"),
2988 file_name: Some("bar"),
2989 file_stem: Some("bar"),
2994 iter: ["/", "foo", "bar"],
2997 parent: Some("/foo"),
2998 file_name: Some("bar"),
2999 file_stem: Some("bar"),
3008 file_name: Some("foo"),
3009 file_stem: Some("foo"),
3014 iter: ["/", "foo", "bar"],
3017 parent: Some("///foo"),
3018 file_name: Some("bar"),
3019 file_stem: Some("bar"),
3058 file_name: Some("foo"),
3059 file_stem: Some("foo"),
3064 iter: ["foo", ".."],
3067 parent: Some("foo"),
3078 file_name: Some("foo"),
3079 file_stem: Some("foo"),
3084 iter: ["foo", "bar"],
3087 parent: Some("foo"),
3088 file_name: Some("bar"),
3089 file_stem: Some("bar"),
3094 iter: ["foo", ".."],
3097 parent: Some("foo"),
3104 iter: ["foo", "..", "bar"],
3107 parent: Some("foo/.."),
3108 file_name: Some("bar"),
3109 file_stem: Some("bar"),
3118 file_name: Some("a"),
3119 file_stem: Some("a"),
3148 file_name: Some("b"),
3149 file_stem: Some("b"),
3158 file_name: Some("b"),
3159 file_stem: Some("b"),
3168 file_name: Some("b"),
3169 file_stem: Some("b"),
3174 iter: ["a", "b", "c"],
3177 parent: Some("a/b"),
3178 file_name: Some("c"),
3179 file_stem: Some("c"),
3188 file_name: Some(".foo"),
3189 file_stem: Some(".foo"),
3196 pub fn test_decompositions_windows() {
3212 file_name: Some("foo"),
3213 file_stem: Some("foo"),
3268 iter: ["\\", "foo"],
3272 file_name: Some("foo"),
3273 file_stem: Some("foo"),
3282 file_name: Some("foo"),
3283 file_stem: Some("foo"),
3288 iter: ["\\", "foo"],
3292 file_name: Some("foo"),
3293 file_stem: Some("foo"),
3298 iter: ["foo", "bar"],
3301 parent: Some("foo"),
3302 file_name: Some("bar"),
3303 file_stem: Some("bar"),
3308 iter: ["\\", "foo", "bar"],
3311 parent: Some("/foo"),
3312 file_name: Some("bar"),
3313 file_stem: Some("bar"),
3318 iter: ["\\", "foo"],
3322 file_name: Some("foo"),
3323 file_stem: Some("foo"),
3328 iter: ["\\", "foo", "bar"],
3331 parent: Some("///foo"),
3332 file_name: Some("bar"),
3333 file_stem: Some("bar"),
3372 file_name: Some("foo"),
3373 file_stem: Some("foo"),
3378 iter: ["foo", ".."],
3381 parent: Some("foo"),
3392 file_name: Some("foo"),
3393 file_stem: Some("foo"),
3398 iter: ["foo", "bar"],
3401 parent: Some("foo"),
3402 file_name: Some("bar"),
3403 file_stem: Some("bar"),
3408 iter: ["foo", ".."],
3411 parent: Some("foo"),
3418 iter: ["foo", "..", "bar"],
3421 parent: Some("foo/.."),
3422 file_name: Some("bar"),
3423 file_stem: Some("bar"),
3432 file_name: Some("a"),
3433 file_stem: Some("a"),
3462 file_name: Some("b"),
3463 file_stem: Some("b"),
3472 file_name: Some("b"),
3473 file_stem: Some("b"),
3482 file_name: Some("b"),
3483 file_stem: Some("b"),
3488 iter: ["a", "b", "c"],
3491 parent: Some("a/b"),
3492 file_name: Some("c"),
3493 file_stem: Some("c"),
3497 iter: ["a", "b", "c"],
3500 parent: Some("a\\b"),
3501 file_name: Some("c"),
3502 file_stem: Some("c"),
3511 file_name: Some("a"),
3512 file_stem: Some("a"),
3517 iter: ["c:", "\\", "foo.txt"],
3520 parent: Some("c:\\"),
3521 file_name: Some("foo.txt"),
3522 file_stem: Some("foo"),
3523 extension: Some("txt")
3526 t!("\\\\server\\share\\foo.txt",
3527 iter: ["\\\\server\\share", "\\", "foo.txt"],
3530 parent: Some("\\\\server\\share\\"),
3531 file_name: Some("foo.txt"),
3532 file_stem: Some("foo"),
3533 extension: Some("txt")
3536 t!("\\\\server\\share",
3537 iter: ["\\\\server\\share", "\\"],
3547 iter: ["\\", "server"],
3551 file_name: Some("server"),
3552 file_stem: Some("server"),
3556 t!("\\\\?\\bar\\foo.txt",
3557 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3560 parent: Some("\\\\?\\bar\\"),
3561 file_name: Some("foo.txt"),
3562 file_stem: Some("foo"),
3563 extension: Some("txt")
3567 iter: ["\\\\?\\bar"],
3586 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3587 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3590 parent: Some("\\\\?\\UNC\\server\\share\\"),
3591 file_name: Some("foo.txt"),
3592 file_stem: Some("foo"),
3593 extension: Some("txt")
3596 t!("\\\\?\\UNC\\server",
3597 iter: ["\\\\?\\UNC\\server"],
3607 iter: ["\\\\?\\UNC\\"],
3616 t!("\\\\?\\C:\\foo.txt",
3617 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3620 parent: Some("\\\\?\\C:\\"),
3621 file_name: Some("foo.txt"),
3622 file_stem: Some("foo"),
3623 extension: Some("txt")
3627 iter: ["\\\\?\\C:", "\\"],
3637 iter: ["\\\\?\\C:"],
3646 t!("\\\\?\\foo/bar",
3647 iter: ["\\\\?\\foo/bar"],
3657 iter: ["\\\\?\\C:/foo"],
3666 t!("\\\\.\\foo\\bar",
3667 iter: ["\\\\.\\foo", "\\", "bar"],
3670 parent: Some("\\\\.\\foo\\"),
3671 file_name: Some("bar"),
3672 file_stem: Some("bar"),
3677 iter: ["\\\\.\\foo", "\\"],
3686 t!("\\\\.\\foo/bar",
3687 iter: ["\\\\.\\foo/bar", "\\"],
3696 t!("\\\\.\\foo\\bar/baz",
3697 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3700 parent: Some("\\\\.\\foo\\bar"),
3701 file_name: Some("baz"),
3702 file_stem: Some("baz"),
3707 iter: ["\\\\.\\", "\\"],
3717 iter: ["\\\\?\\a", "\\", "b"],
3720 parent: Some("\\\\?\\a\\"),
3721 file_name: Some("b"),
3722 file_stem: Some("b"),
3728 pub fn test_stem_ext() {
3730 file_stem: Some("foo"),
3735 file_stem: Some("foo"),
3740 file_stem: Some(".foo"),
3745 file_stem: Some("foo"),
3746 extension: Some("txt")
3750 file_stem: Some("foo.bar"),
3751 extension: Some("txt")
3755 file_stem: Some("foo.bar"),
3759 t!(".", file_stem: None, extension: None);
3761 t!("..", file_stem: None, extension: None);
3763 t!("", file_stem: None, extension: None);
3767 pub fn test_push() {
3769 ($path:expr, $push:expr, $expected:expr) => ( {
3770 let mut actual = PathBuf::from($path);
3772 assert!(actual.to_str() == Some($expected),
3773 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3774 $push, $path, $expected, actual.to_str().unwrap());
3778 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3779 tp!("", "foo", "foo");
3780 tp!("foo", "bar", "foo/bar");
3781 tp!("foo/", "bar", "foo/bar");
3782 tp!("foo//", "bar", "foo//bar");
3783 tp!("foo/.", "bar", "foo/./bar");
3784 tp!("foo./.", "bar", "foo././bar");
3785 tp!("foo", "", "foo/");
3786 tp!("foo", ".", "foo/.");
3787 tp!("foo", "..", "foo/..");
3788 tp!("foo", "/", "/");
3789 tp!("/foo/bar", "/", "/");
3790 tp!("/foo/bar", "/baz", "/baz");
3791 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3793 tp!("", "foo", "foo");
3794 tp!("foo", "bar", r"foo\bar");
3795 tp!("foo/", "bar", r"foo/bar");
3796 tp!(r"foo\", "bar", r"foo\bar");
3797 tp!("foo//", "bar", r"foo//bar");
3798 tp!(r"foo\\", "bar", r"foo\\bar");
3799 tp!("foo/.", "bar", r"foo/.\bar");
3800 tp!("foo./.", "bar", r"foo./.\bar");
3801 tp!(r"foo\.", "bar", r"foo\.\bar");
3802 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3803 tp!("foo", "", "foo\\");
3804 tp!("foo", ".", r"foo\.");
3805 tp!("foo", "..", r"foo\..");
3806 tp!("foo", "/", "/");
3807 tp!("foo", r"\", r"\");
3808 tp!("/foo/bar", "/", "/");
3809 tp!(r"\foo\bar", r"\", r"\");
3810 tp!("/foo/bar", "/baz", "/baz");
3811 tp!("/foo/bar", r"\baz", r"\baz");
3812 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3813 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3815 tp!("c:\\", "windows", "c:\\windows");
3816 tp!("c:", "windows", "c:windows");
3818 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3819 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3820 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3821 tp!("a\\b", "\\c\\d", "\\c\\d");
3822 tp!("a\\b", ".", "a\\b\\.");
3823 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3824 tp!("a\\b", "C:a.txt", "C:a.txt");
3825 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3826 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3827 tp!("C:\\a\\b\\c", "C:d", "C:d");
3828 tp!("C:a\\b\\c", "C:d", "C:d");
3829 tp!("C:", r"a\b\c", r"C:a\b\c");
3830 tp!("C:", r"..\a", r"C:..\a");
3831 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
3832 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3833 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3834 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3835 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3836 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3837 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
3838 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3839 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3841 // Note: modified from old path API
3842 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3844 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
3845 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3846 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3847 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3848 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3850 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3857 ($path:expr, $expected:expr, $output:expr) => ( {
3858 let mut actual = PathBuf::from($path);
3859 let output = actual.pop();
3860 assert!(actual.to_str() == Some($expected) && output == $output,
3861 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3862 $path, $expected, $output,
3863 actual.to_str().unwrap(), output);
3868 tp!("/", "/", false);
3869 tp!("foo", "", true);
3871 tp!("/foo", "/", true);
3872 tp!("/foo/bar", "/foo", true);
3873 tp!("foo/bar", "foo", true);
3874 tp!("foo/.", "", true);
3875 tp!("foo//bar", "foo", true);
3878 tp!("a\\b\\c", "a\\b", true);
3879 tp!("\\a", "\\", true);
3880 tp!("\\", "\\", false);
3882 tp!("C:\\a\\b", "C:\\a", true);
3883 tp!("C:\\a", "C:\\", true);
3884 tp!("C:\\", "C:\\", false);
3885 tp!("C:a\\b", "C:a", true);
3886 tp!("C:a", "C:", true);
3887 tp!("C:", "C:", false);
3888 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3889 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3890 tp!("\\\\server\\share", "\\\\server\\share", false);
3891 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3892 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3893 tp!("\\\\?\\a", "\\\\?\\a", false);
3894 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3895 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3896 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3897 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
3898 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
3899 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
3900 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3901 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3902 tp!("\\\\.\\a", "\\\\.\\a", false);
3904 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3909 pub fn test_set_file_name() {
3911 ($path:expr, $file:expr, $expected:expr) => ( {
3912 let mut p = PathBuf::from($path);
3913 p.set_file_name($file);
3914 assert!(p.to_str() == Some($expected),
3915 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3916 $path, $file, $expected,
3917 p.to_str().unwrap());
3921 tfn!("foo", "foo", "foo");
3922 tfn!("foo", "bar", "bar");
3923 tfn!("foo", "", "");
3924 tfn!("", "foo", "foo");
3925 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3926 tfn!(".", "foo", "./foo");
3927 tfn!("foo/", "bar", "bar");
3928 tfn!("foo/.", "bar", "bar");
3929 tfn!("..", "foo", "../foo");
3930 tfn!("foo/..", "bar", "foo/../bar");
3931 tfn!("/", "foo", "/foo");
3933 tfn!(".", "foo", r".\foo");
3934 tfn!(r"foo\", "bar", r"bar");
3935 tfn!(r"foo\.", "bar", r"bar");
3936 tfn!("..", "foo", r"..\foo");
3937 tfn!(r"foo\..", "bar", r"foo\..\bar");
3938 tfn!(r"\", "foo", r"\foo");
3943 pub fn test_set_extension() {
3945 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3946 let mut p = PathBuf::from($path);
3947 let output = p.set_extension($ext);
3948 assert!(p.to_str() == Some($expected) && output == $output,
3949 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3950 $path, $ext, $expected, $output,
3951 p.to_str().unwrap(), output);
3955 tfe!("foo", "txt", "foo.txt", true);
3956 tfe!("foo.bar", "txt", "foo.txt", true);
3957 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3958 tfe!(".test", "txt", ".test.txt", true);
3959 tfe!("foo.txt", "", "foo", true);
3960 tfe!("foo", "", "foo", true);
3961 tfe!("", "foo", "", false);
3962 tfe!(".", "foo", ".", false);
3963 tfe!("foo/", "bar", "foo.bar", true);
3964 tfe!("foo/.", "bar", "foo.bar", true);
3965 tfe!("..", "foo", "..", false);
3966 tfe!("foo/..", "bar", "foo/..", false);
3967 tfe!("/", "foo", "/", false);
3971 fn test_eq_receivers() {
3972 use crate::borrow::Cow;
3974 let borrowed: &Path = Path::new("foo/bar");
3975 let mut owned: PathBuf = PathBuf::new();
3978 let borrowed_cow: Cow<'_, Path> = borrowed.into();
3979 let owned_cow: Cow<'_, Path> = owned.clone().into();
3982 ($($current:expr),+) => {
3984 assert_eq!($current, borrowed);
3985 assert_eq!($current, owned);
3986 assert_eq!($current, borrowed_cow);
3987 assert_eq!($current, owned_cow);
3992 t!(borrowed, owned, borrowed_cow, owned_cow);
3996 pub fn test_compare() {
3997 use crate::collections::hash_map::DefaultHasher;
3998 use crate::hash::{Hash, Hasher};
4000 fn hash<T: Hash>(t: T) -> u64 {
4001 let mut s = DefaultHasher::new();
4007 ($path1:expr, $path2:expr, eq: $eq:expr,
4008 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4009 relative_from: $relative_from:expr) => ({
4010 let path1 = Path::new($path1);
4011 let path2 = Path::new($path2);
4013 let eq = path1 == path2;
4014 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4015 $path1, $path2, $eq, eq);
4016 assert!($eq == (hash(path1) == hash(path2)),
4017 "{:?} == {:?}, expected {:?}, got {} and {}",
4018 $path1, $path2, $eq, hash(path1), hash(path2));
4020 let starts_with = path1.starts_with(path2);
4021 assert!(starts_with == $starts_with,
4022 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4023 $starts_with, starts_with);
4025 let ends_with = path1.ends_with(path2);
4026 assert!(ends_with == $ends_with,
4027 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4028 $ends_with, ends_with);
4030 let relative_from = path1.strip_prefix(path2)
4031 .map(|p| p.to_str().unwrap())
4033 let exp: Option<&str> = $relative_from;
4034 assert!(relative_from == exp,
4035 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4036 $path1, $path2, exp, relative_from);
4044 relative_from: Some("")
4051 relative_from: Some("foo")
4065 relative_from: Some("")
4072 relative_from: Some("")
4075 tc!("foo/bar", "foo",
4079 relative_from: Some("bar")
4082 tc!("foo/bar/baz", "foo/bar",
4086 relative_from: Some("baz")
4089 tc!("foo/bar", "foo/bar/baz",
4096 tc!("./foo/bar/", ".",
4100 relative_from: Some("foo/bar")
4104 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4105 r"c:\src\rust\cargo-test\test",
4109 relative_from: Some("Cargo.toml")
4112 tc!(r"c:\foo", r"C:\foo",
4116 relative_from: Some("")
4122 fn test_components_debug() {
4123 let path = Path::new("/tmp");
4125 let mut components = path.components();
4127 let expected = "Components([RootDir, Normal(\"tmp\")])";
4128 let actual = format!("{:?}", components);
4129 assert_eq!(expected, actual);
4131 let _ = components.next().unwrap();
4132 let expected = "Components([Normal(\"tmp\")])";
4133 let actual = format!("{:?}", components);
4134 assert_eq!(expected, actual);
4136 let _ = components.next().unwrap();
4137 let expected = "Components([])";
4138 let actual = format!("{:?}", components);
4139 assert_eq!(expected, actual);
4144 fn test_iter_debug() {
4145 let path = Path::new("/tmp");
4147 let mut iter = path.iter();
4149 let expected = "Iter([\"/\", \"tmp\"])";
4150 let actual = format!("{:?}", iter);
4151 assert_eq!(expected, actual);
4153 let _ = iter.next().unwrap();
4154 let expected = "Iter([\"tmp\"])";
4155 let actual = format!("{:?}", iter);
4156 assert_eq!(expected, actual);
4158 let _ = iter.next().unwrap();
4159 let expected = "Iter([])";
4160 let actual = format!("{:?}", iter);
4161 assert_eq!(expected, actual);
4166 let orig: &str = "some/sort/of/path";
4167 let path = Path::new(orig);
4168 let boxed: Box<Path> = Box::from(path);
4169 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4170 assert_eq!(path, &*boxed);
4171 assert_eq!(&*boxed, &*path_buf);
4172 assert_eq!(&*path_buf, path);
4176 fn test_clone_into() {
4177 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4178 let path = Path::new("short");
4179 path.clone_into(&mut path_buf);
4180 assert_eq!(path, path_buf);
4181 assert!(path_buf.into_os_string().capacity() >= 15);
4185 fn display_format_flags() {
4186 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4187 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4192 let orig = "hello/world";
4193 let path = Path::new(orig);
4194 let rc: Rc<Path> = Rc::from(path);
4195 let arc: Arc<Path> = Arc::from(path);
4197 assert_eq!(&*rc, path);
4198 assert_eq!(&*arc, path);
4200 let rc2: Rc<Path> = Rc::from(path.to_owned());
4201 let arc2: Arc<Path> = Arc::from(path.to_owned());
4203 assert_eq!(&*rc2, path);
4204 assert_eq!(&*arc2, path);