1 // ignore-tidy-filelength
3 //! Cross-platform path manipulation.
5 //! This module provides two types, [`PathBuf`] and [`Path`] (akin to [`String`]
6 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
7 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
8 //! on strings according to the local platform's path syntax.
10 //! Paths can be parsed into [`Component`]s by iterating over the structure
11 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
12 //! correspond to the substrings between path separators (`/` or `\`). You can
13 //! reconstruct an equivalent path from components with the [`push`] method on
14 //! [`PathBuf`]; note that the paths may differ syntactically by the
15 //! normalization described in the documentation for the [`components`] method.
19 //! Path manipulation includes both parsing components from slices and building
22 //! To parse a path, you can create a [`Path`] slice from a [`str`]
23 //! slice and start asking questions:
26 //! use std::path::Path;
27 //! use std::ffi::OsStr;
29 //! let path = Path::new("/tmp/foo/bar.txt");
31 //! let parent = path.parent();
32 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
34 //! let file_stem = path.file_stem();
35 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
37 //! let extension = path.extension();
38 //! assert_eq!(extension, Some(OsStr::new("txt")));
41 //! To build or modify paths, use [`PathBuf`]:
44 //! use std::path::PathBuf;
46 //! // This way works...
47 //! let mut path = PathBuf::from("c:\\");
49 //! path.push("windows");
50 //! path.push("system32");
52 //! path.set_extension("dll");
54 //! // ... but push is best used if you don't know everything up
55 //! // front. If you do, this way is better:
56 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
59 //! [`components`]: Path::components
60 //! [`push`]: PathBuf::push
62 #![stable(feature = "rust1", since = "1.0.0")]
63 #![deny(unsafe_op_in_unsafe_fn)]
65 use crate::borrow::{Borrow, Cow};
67 use crate::error::Error;
70 use crate::hash::{Hash, Hasher};
72 use crate::iter::{self, FusedIterator};
73 use crate::ops::{self, Deref};
75 use crate::str::FromStr;
78 use crate::ffi::{OsStr, OsString};
80 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
82 ////////////////////////////////////////////////////////////////////////////////
84 ////////////////////////////////////////////////////////////////////////////////
86 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
87 // taking advantage of the fact that OsStr always encodes ASCII characters
88 // as-is. Eventually, this transmutation should be replaced by direct uses of
89 // OsStr APIs for parsing, but it will take a while for those to become
92 ////////////////////////////////////////////////////////////////////////////////
94 ////////////////////////////////////////////////////////////////////////////////
96 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
98 /// Windows uses a variety of path prefix styles, including references to drive
99 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
100 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
101 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
102 /// no normalization is performed.
107 /// use std::path::{Component, Path, Prefix};
108 /// use std::path::Prefix::*;
109 /// use std::ffi::OsStr;
111 /// fn get_path_prefix(s: &str) -> Prefix {
112 /// let path = Path::new(s);
113 /// match path.components().next().unwrap() {
114 /// Component::Prefix(prefix_component) => prefix_component.kind(),
119 /// # if cfg!(windows) {
120 /// assert_eq!(Verbatim(OsStr::new("pictures")),
121 /// get_path_prefix(r"\\?\pictures\kittens"));
122 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
123 /// get_path_prefix(r"\\?\UNC\server\share"));
124 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
125 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
126 /// get_path_prefix(r"\\.\BrainInterface"));
127 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
128 /// get_path_prefix(r"\\server\share"));
129 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
132 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub enum Prefix<'a> {
135 /// Verbatim prefix, e.g., `\\?\cat_pics`.
137 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
139 #[stable(feature = "rust1", since = "1.0.0")]
140 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
142 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
143 /// e.g., `\\?\UNC\server\share`.
145 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
146 /// server's hostname and a share name.
147 #[stable(feature = "rust1", since = "1.0.0")]
149 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
150 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
153 /// Verbatim disk prefix, e.g., `\\?\C:`.
155 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
156 /// drive letter and `:`.
157 #[stable(feature = "rust1", since = "1.0.0")]
158 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
160 /// Device namespace prefix, e.g., `\\.\COM42`.
162 /// Device namespace prefixes consist of `\\.\` immediately followed by the
164 #[stable(feature = "rust1", since = "1.0.0")]
165 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
167 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
168 /// `\\server\share`.
170 /// UNC prefixes consist of the server's hostname and a share name.
171 #[stable(feature = "rust1", since = "1.0.0")]
173 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
174 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
177 /// Prefix `C:` for the given disk drive.
178 #[stable(feature = "rust1", since = "1.0.0")]
179 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
182 impl<'a> Prefix<'a> {
184 fn len(&self) -> usize {
186 fn os_str_len(s: &OsStr) -> usize {
187 os_str_as_u8_slice(s).len()
190 Verbatim(x) => 4 + os_str_len(x),
191 VerbatimUNC(x, y) => {
192 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
194 VerbatimDisk(_) => 6,
195 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
196 DeviceNS(x) => 4 + os_str_len(x),
201 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
206 /// use std::path::Prefix::*;
207 /// use std::ffi::OsStr;
209 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
210 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
211 /// assert!(VerbatimDisk(b'C').is_verbatim());
212 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
213 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
214 /// assert!(!Disk(b'C').is_verbatim());
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn is_verbatim(&self) -> bool {
220 matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
224 fn is_drive(&self) -> bool {
225 matches!(*self, Prefix::Disk(_))
229 fn has_implicit_root(&self) -> bool {
234 ////////////////////////////////////////////////////////////////////////////////
235 // Exposed parsing helpers
236 ////////////////////////////////////////////////////////////////////////////////
238 /// Determines whether the character is one of the permitted path
239 /// separators for the current platform.
246 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
247 /// assert!(!path::is_separator('❤'));
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub fn is_separator(c: char) -> bool {
251 c.is_ascii() && is_sep_byte(c as u8)
254 /// The primary separator of path components for the current platform.
256 /// For example, `/` on Unix and `\` on Windows.
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
260 ////////////////////////////////////////////////////////////////////////////////
262 ////////////////////////////////////////////////////////////////////////////////
264 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
265 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
266 // `iter` after having exhausted `prefix`.
267 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
269 I: Iterator<Item = Component<'a>> + Clone,
270 J: Iterator<Item = Component<'b>>,
273 let mut iter_next = iter.clone();
274 match (iter_next.next(), prefix.next()) {
275 (Some(ref x), Some(ref y)) if x == y => (),
276 (Some(_), Some(_)) => return None,
277 (Some(_), None) => return Some(iter),
278 (None, None) => return Some(iter),
279 (None, Some(_)) => return None,
285 // See note at the top of this module to understand why these are used:
287 // These casts are safe as OsStr is internally a wrapper around [u8] on all
290 // Note that currently this relies on the special knowledge that libstd has;
291 // these types are single-element structs but are not marked repr(transparent)
292 // or repr(C) which would make these casts allowable outside std.
293 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
294 unsafe { &*(s as *const OsStr as *const [u8]) }
296 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
297 // SAFETY: see the comment of `os_str_as_u8_slice`
298 unsafe { &*(s as *const [u8] as *const OsStr) }
301 // Detect scheme on Redox
302 fn has_redox_scheme(s: &[u8]) -> bool {
303 cfg!(target_os = "redox") && s.contains(&b':')
306 ////////////////////////////////////////////////////////////////////////////////
307 // Cross-platform, iterator-independent parsing
308 ////////////////////////////////////////////////////////////////////////////////
310 /// Says whether the first byte after the prefix is a separator.
311 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
312 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
313 !path.is_empty() && is_sep_byte(path[0])
316 // basic workhorse for splitting stem and extension
317 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
318 if os_str_as_u8_slice(file) == b".." {
319 return (Some(file), None);
322 // The unsafety here stems from converting between &OsStr and &[u8]
323 // and back. This is safe to do because (1) we only look at ASCII
324 // contents of the encoding and (2) new &OsStr values are produced
325 // only from ASCII-bounded slices of existing &OsStr values.
326 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
327 let after = iter.next();
328 let before = iter.next();
329 if before == Some(b"") {
332 unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
336 ////////////////////////////////////////////////////////////////////////////////
337 // The core iterators
338 ////////////////////////////////////////////////////////////////////////////////
340 /// Component parsing works by a double-ended state machine; the cursors at the
341 /// front and back of the path each keep track of what parts of the path have
342 /// been consumed so far.
344 /// Going front to back, a path is made up of a prefix, a starting
345 /// directory component, and a body (of normal components)
346 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
349 StartDir = 1, // / or . or nothing
350 Body = 2, // foo/bar/baz
354 /// A structure wrapping a Windows path prefix as well as its unparsed string
357 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
358 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
359 /// returned by [`as_os_str`].
361 /// Instances of this `struct` can be obtained by matching against the
362 /// [`Prefix` variant] on [`Component`].
364 /// Does not occur on Unix.
369 /// # if cfg!(windows) {
370 /// use std::path::{Component, Path, Prefix};
371 /// use std::ffi::OsStr;
373 /// let path = Path::new(r"c:\you\later\");
374 /// match path.components().next().unwrap() {
375 /// Component::Prefix(prefix_component) => {
376 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
377 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
379 /// _ => unreachable!(),
384 /// [`as_os_str`]: PrefixComponent::as_os_str
385 /// [`kind`]: PrefixComponent::kind
386 /// [`Prefix` variant]: Component::Prefix
387 #[stable(feature = "rust1", since = "1.0.0")]
388 #[derive(Copy, Clone, Eq, Debug)]
389 pub struct PrefixComponent<'a> {
390 /// The prefix as an unparsed `OsStr` slice.
393 /// The parsed prefix data.
397 impl<'a> PrefixComponent<'a> {
398 /// Returns the parsed prefix data.
400 /// See [`Prefix`]'s documentation for more information on the different
401 /// kinds of prefixes.
402 #[stable(feature = "rust1", since = "1.0.0")]
403 pub fn kind(&self) -> Prefix<'a> {
407 /// Returns the raw [`OsStr`] slice for this prefix.
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn as_os_str(&self) -> &'a OsStr {
414 #[stable(feature = "rust1", since = "1.0.0")]
415 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
416 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
417 cmp::PartialEq::eq(&self.parsed, &other.parsed)
421 #[stable(feature = "rust1", since = "1.0.0")]
422 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
423 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
424 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
428 #[stable(feature = "rust1", since = "1.0.0")]
429 impl cmp::Ord for PrefixComponent<'_> {
430 fn cmp(&self, other: &Self) -> cmp::Ordering {
431 cmp::Ord::cmp(&self.parsed, &other.parsed)
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl Hash for PrefixComponent<'_> {
437 fn hash<H: Hasher>(&self, h: &mut H) {
442 /// A single component of a path.
444 /// A `Component` roughly corresponds to a substring between path separators
447 /// This `enum` is created by iterating over [`Components`], which in turn is
448 /// created by the [`components`][`Path::components`] method on [`Path`].
453 /// use std::path::{Component, Path};
455 /// let path = Path::new("/tmp/foo/bar.txt");
456 /// let components = path.components().collect::<Vec<_>>();
457 /// assert_eq!(&components, &[
458 /// Component::RootDir,
459 /// Component::Normal("tmp".as_ref()),
460 /// Component::Normal("foo".as_ref()),
461 /// Component::Normal("bar.txt".as_ref()),
464 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub enum Component<'a> {
467 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
469 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
472 /// Does not occur on Unix.
473 #[stable(feature = "rust1", since = "1.0.0")]
474 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
476 /// The root directory component, appears after any prefix and before anything else.
478 /// It represents a separator that designates that a path starts from root.
479 #[stable(feature = "rust1", since = "1.0.0")]
482 /// A reference to the current directory, i.e., `.`.
483 #[stable(feature = "rust1", since = "1.0.0")]
486 /// A reference to the parent directory, i.e., `..`.
487 #[stable(feature = "rust1", since = "1.0.0")]
490 /// A normal component, e.g., `a` and `b` in `a/b`.
492 /// This variant is the most common one, it represents references to files
494 #[stable(feature = "rust1", since = "1.0.0")]
495 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
498 impl<'a> Component<'a> {
499 /// Extracts the underlying [`OsStr`] slice.
504 /// use std::path::Path;
506 /// let path = Path::new("./tmp/foo/bar.txt");
507 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
508 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn as_os_str(self) -> &'a OsStr {
513 Component::Prefix(p) => p.as_os_str(),
514 Component::RootDir => OsStr::new(MAIN_SEP_STR),
515 Component::CurDir => OsStr::new("."),
516 Component::ParentDir => OsStr::new(".."),
517 Component::Normal(path) => path,
522 #[stable(feature = "rust1", since = "1.0.0")]
523 impl AsRef<OsStr> for Component<'_> {
524 fn as_ref(&self) -> &OsStr {
529 #[stable(feature = "path_component_asref", since = "1.25.0")]
530 impl AsRef<Path> for Component<'_> {
531 fn as_ref(&self) -> &Path {
532 self.as_os_str().as_ref()
536 /// An iterator over the [`Component`]s of a [`Path`].
538 /// This `struct` is created by the [`components`] method on [`Path`].
539 /// See its documentation for more.
544 /// use std::path::Path;
546 /// let path = Path::new("/tmp/foo/bar.txt");
548 /// for component in path.components() {
549 /// println!("{:?}", component);
553 /// [`components`]: Path::components
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub struct Components<'a> {
557 // The path left to parse components from
560 // The prefix as it was originally parsed, if any
561 prefix: Option<Prefix<'a>>,
563 // true if path *physically* has a root separator; for most Windows
564 // prefixes, it may have a "logical" rootseparator for the purposes of
565 // normalization, e.g., \\server\share == \\server\share\.
566 has_physical_root: bool,
568 // The iterator is double-ended, and these two states keep track of what has
569 // been produced from either end
574 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
576 /// This `struct` is created by the [`iter`] method on [`Path`].
577 /// See its documentation for more.
579 /// [`iter`]: Path::iter
581 #[stable(feature = "rust1", since = "1.0.0")]
582 pub struct Iter<'a> {
583 inner: Components<'a>,
586 #[stable(feature = "path_components_debug", since = "1.13.0")]
587 impl fmt::Debug for Components<'_> {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 struct DebugHelper<'a>(&'a Path);
591 impl fmt::Debug for DebugHelper<'_> {
592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 f.debug_list().entries(self.0.components()).finish()
597 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
601 impl<'a> Components<'a> {
602 // how long is the prefix, if any?
604 fn prefix_len(&self) -> usize {
605 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
609 fn prefix_verbatim(&self) -> bool {
610 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
613 /// how much of the prefix is left from the point of view of iteration?
615 fn prefix_remaining(&self) -> usize {
616 if self.front == State::Prefix { self.prefix_len() } else { 0 }
619 // Given the iteration so far, how much of the pre-State::Body path is left?
621 fn len_before_body(&self) -> usize {
622 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
623 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
624 self.prefix_remaining() + root + cur_dir
627 // is the iteration complete?
629 fn finished(&self) -> bool {
630 self.front == State::Done || self.back == State::Done || self.front > self.back
634 fn is_sep_byte(&self, b: u8) -> bool {
635 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
638 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
643 /// use std::path::Path;
645 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
646 /// components.next();
647 /// components.next();
649 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
651 #[stable(feature = "rust1", since = "1.0.0")]
652 pub fn as_path(&self) -> &'a Path {
653 let mut comps = self.clone();
654 if comps.front == State::Body {
657 if comps.back == State::Body {
660 unsafe { Path::from_u8_slice(comps.path) }
663 /// Is the *original* path rooted?
664 fn has_root(&self) -> bool {
665 if self.has_physical_root {
668 if let Some(p) = self.prefix {
669 if p.has_implicit_root() {
676 /// Should the normalized path include a leading . ?
677 fn include_cur_dir(&self) -> bool {
681 let mut iter = self.path[self.prefix_len()..].iter();
682 match (iter.next(), iter.next()) {
683 (Some(&b'.'), None) => true,
684 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
689 // parse a given byte sequence into the corresponding path component
690 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
692 b"." if self.prefix_verbatim() => Some(Component::CurDir),
693 b"." => None, // . components are normalized away, except at
694 // the beginning of a path, which is treated
695 // separately via `include_cur_dir`
696 b".." => Some(Component::ParentDir),
698 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
702 // parse a component from the left, saying how many bytes to consume to
703 // remove the component
704 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
705 debug_assert!(self.front == State::Body);
706 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
707 None => (0, self.path),
708 Some(i) => (1, &self.path[..i]),
710 (comp.len() + extra, self.parse_single_component(comp))
713 // parse a component from the right, saying how many bytes to consume to
714 // remove the component
715 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
716 debug_assert!(self.back == State::Body);
717 let start = self.len_before_body();
718 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
719 None => (0, &self.path[start..]),
720 Some(i) => (1, &self.path[start + i + 1..]),
722 (comp.len() + extra, self.parse_single_component(comp))
725 // trim away repeated separators (i.e., empty components) on the left
726 fn trim_left(&mut self) {
727 while !self.path.is_empty() {
728 let (size, comp) = self.parse_next_component();
732 self.path = &self.path[size..];
737 // trim away repeated separators (i.e., empty components) on the right
738 fn trim_right(&mut self) {
739 while self.path.len() > self.len_before_body() {
740 let (size, comp) = self.parse_next_component_back();
744 self.path = &self.path[..self.path.len() - size];
750 #[stable(feature = "rust1", since = "1.0.0")]
751 impl AsRef<Path> for Components<'_> {
752 fn as_ref(&self) -> &Path {
757 #[stable(feature = "rust1", since = "1.0.0")]
758 impl AsRef<OsStr> for Components<'_> {
759 fn as_ref(&self) -> &OsStr {
760 self.as_path().as_os_str()
764 #[stable(feature = "path_iter_debug", since = "1.13.0")]
765 impl fmt::Debug for Iter<'_> {
766 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
767 struct DebugHelper<'a>(&'a Path);
769 impl fmt::Debug for DebugHelper<'_> {
770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771 f.debug_list().entries(self.0.iter()).finish()
775 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
780 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
785 /// use std::path::Path;
787 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
791 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
793 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn as_path(&self) -> &'a Path {
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl AsRef<Path> for Iter<'_> {
801 fn as_ref(&self) -> &Path {
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl AsRef<OsStr> for Iter<'_> {
808 fn as_ref(&self) -> &OsStr {
809 self.as_path().as_os_str()
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl<'a> Iterator for Iter<'a> {
815 type Item = &'a OsStr;
817 fn next(&mut self) -> Option<&'a OsStr> {
818 self.inner.next().map(Component::as_os_str)
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<'a> DoubleEndedIterator for Iter<'a> {
824 fn next_back(&mut self) -> Option<&'a OsStr> {
825 self.inner.next_back().map(Component::as_os_str)
829 #[stable(feature = "fused", since = "1.26.0")]
830 impl FusedIterator for Iter<'_> {}
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<'a> Iterator for Components<'a> {
834 type Item = Component<'a>;
836 fn next(&mut self) -> Option<Component<'a>> {
837 while !self.finished() {
839 State::Prefix if self.prefix_len() > 0 => {
840 self.front = State::StartDir;
841 debug_assert!(self.prefix_len() <= self.path.len());
842 let raw = &self.path[..self.prefix_len()];
843 self.path = &self.path[self.prefix_len()..];
844 return Some(Component::Prefix(PrefixComponent {
845 raw: unsafe { u8_slice_as_os_str(raw) },
846 parsed: self.prefix.unwrap(),
850 self.front = State::StartDir;
853 self.front = State::Body;
854 if self.has_physical_root {
855 debug_assert!(!self.path.is_empty());
856 self.path = &self.path[1..];
857 return Some(Component::RootDir);
858 } else if let Some(p) = self.prefix {
859 if p.has_implicit_root() && !p.is_verbatim() {
860 return Some(Component::RootDir);
862 } else if self.include_cur_dir() {
863 debug_assert!(!self.path.is_empty());
864 self.path = &self.path[1..];
865 return Some(Component::CurDir);
868 State::Body if !self.path.is_empty() => {
869 let (size, comp) = self.parse_next_component();
870 self.path = &self.path[size..];
876 self.front = State::Done;
878 State::Done => unreachable!(),
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a> DoubleEndedIterator for Components<'a> {
887 fn next_back(&mut self) -> Option<Component<'a>> {
888 while !self.finished() {
890 State::Body if self.path.len() > self.len_before_body() => {
891 let (size, comp) = self.parse_next_component_back();
892 self.path = &self.path[..self.path.len() - size];
898 self.back = State::StartDir;
901 self.back = State::Prefix;
902 if self.has_physical_root {
903 self.path = &self.path[..self.path.len() - 1];
904 return Some(Component::RootDir);
905 } else if let Some(p) = self.prefix {
906 if p.has_implicit_root() && !p.is_verbatim() {
907 return Some(Component::RootDir);
909 } else if self.include_cur_dir() {
910 self.path = &self.path[..self.path.len() - 1];
911 return Some(Component::CurDir);
914 State::Prefix if self.prefix_len() > 0 => {
915 self.back = State::Done;
916 return Some(Component::Prefix(PrefixComponent {
917 raw: unsafe { u8_slice_as_os_str(self.path) },
918 parsed: self.prefix.unwrap(),
922 self.back = State::Done;
925 State::Done => unreachable!(),
932 #[stable(feature = "fused", since = "1.26.0")]
933 impl FusedIterator for Components<'_> {}
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<'a> cmp::PartialEq for Components<'a> {
937 fn eq(&self, other: &Components<'a>) -> bool {
938 Iterator::eq(self.clone(), other.clone())
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl cmp::Eq for Components<'_> {}
945 #[stable(feature = "rust1", since = "1.0.0")]
946 impl<'a> cmp::PartialOrd for Components<'a> {
947 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
948 Iterator::partial_cmp(self.clone(), other.clone())
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl cmp::Ord for Components<'_> {
954 fn cmp(&self, other: &Self) -> cmp::Ordering {
955 Iterator::cmp(self.clone(), other.clone())
959 /// An iterator over [`Path`] and its ancestors.
961 /// This `struct` is created by the [`ancestors`] method on [`Path`].
962 /// See its documentation for more.
967 /// use std::path::Path;
969 /// let path = Path::new("/foo/bar");
971 /// for ancestor in path.ancestors() {
972 /// println!("{}", ancestor.display());
976 /// [`ancestors`]: Path::ancestors
977 #[derive(Copy, Clone, Debug)]
978 #[stable(feature = "path_ancestors", since = "1.28.0")]
979 pub struct Ancestors<'a> {
980 next: Option<&'a Path>,
983 #[stable(feature = "path_ancestors", since = "1.28.0")]
984 impl<'a> Iterator for Ancestors<'a> {
985 type Item = &'a Path;
987 fn next(&mut self) -> Option<Self::Item> {
988 let next = self.next;
989 self.next = next.and_then(Path::parent);
994 #[stable(feature = "path_ancestors", since = "1.28.0")]
995 impl FusedIterator for Ancestors<'_> {}
997 ////////////////////////////////////////////////////////////////////////////////
998 // Basic types and traits
999 ////////////////////////////////////////////////////////////////////////////////
1001 /// An owned, mutable path (akin to [`String`]).
1003 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1004 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1005 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1007 /// [`push`]: PathBuf::push
1008 /// [`set_extension`]: PathBuf::set_extension
1010 /// More details about the overall approach can be found in
1011 /// the [module documentation](index.html).
1015 /// You can use [`push`] to build up a `PathBuf` from
1019 /// use std::path::PathBuf;
1021 /// let mut path = PathBuf::new();
1023 /// path.push(r"C:\");
1024 /// path.push("windows");
1025 /// path.push("system32");
1027 /// path.set_extension("dll");
1030 /// However, [`push`] is best used for dynamic situations. This is a better way
1031 /// to do this when you know all of the components ahead of time:
1034 /// use std::path::PathBuf;
1036 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1039 /// We can still do better than this! Since these are all strings, we can use
1043 /// use std::path::PathBuf;
1045 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1048 /// Which method works best depends on what kind of situation you're in.
1050 #[stable(feature = "rust1", since = "1.0.0")]
1052 // `PathBuf::as_mut_vec` current implementation relies
1053 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1054 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1055 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1056 // not documented and must not be relied upon.
1057 pub struct PathBuf {
1062 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1063 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1066 /// Allocates an empty `PathBuf`.
1071 /// use std::path::PathBuf;
1073 /// let path = PathBuf::new();
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 pub fn new() -> PathBuf {
1077 PathBuf { inner: OsString::new() }
1080 /// Creates a new `PathBuf` with a given capacity used to create the
1081 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1086 /// use std::path::PathBuf;
1088 /// let mut path = PathBuf::with_capacity(10);
1089 /// let capacity = path.capacity();
1091 /// // This push is done without reallocating
1092 /// path.push(r"C:\");
1094 /// assert_eq!(capacity, path.capacity());
1097 /// [`with_capacity`]: OsString::with_capacity
1098 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1099 pub fn with_capacity(capacity: usize) -> PathBuf {
1100 PathBuf { inner: OsString::with_capacity(capacity) }
1103 /// Coerces to a [`Path`] slice.
1108 /// use std::path::{Path, PathBuf};
1110 /// let p = PathBuf::from("/test");
1111 /// assert_eq!(Path::new("/test"), p.as_path());
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub fn as_path(&self) -> &Path {
1118 /// Extends `self` with `path`.
1120 /// If `path` is absolute, it replaces the current path.
1124 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1125 /// replaces everything except for the prefix (if any) of `self`.
1126 /// * if `path` has a prefix but no root, it replaces `self`.
1130 /// Pushing a relative path extends the existing path:
1133 /// use std::path::PathBuf;
1135 /// let mut path = PathBuf::from("/tmp");
1136 /// path.push("file.bk");
1137 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1140 /// Pushing an absolute path replaces the existing path:
1143 /// use std::path::PathBuf;
1145 /// let mut path = PathBuf::from("/tmp");
1146 /// path.push("/etc");
1147 /// assert_eq!(path, PathBuf::from("/etc"));
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1151 self._push(path.as_ref())
1154 fn _push(&mut self, path: &Path) {
1155 // in general, a separator is needed if the rightmost byte is not a separator
1156 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1158 // in the special case of `C:` on Windows, do *not* add a separator
1160 let comps = self.components();
1161 if comps.prefix_len() > 0
1162 && comps.prefix_len() == comps.path.len()
1163 && comps.prefix.unwrap().is_drive()
1169 // absolute `path` replaces `self`
1170 if path.is_absolute() || path.prefix().is_some() {
1171 self.as_mut_vec().truncate(0);
1173 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1174 } else if path.has_root() {
1175 let prefix_len = self.components().prefix_remaining();
1176 self.as_mut_vec().truncate(prefix_len);
1178 // `path` is a pure relative path
1179 } else if need_sep {
1180 self.inner.push(MAIN_SEP_STR);
1183 self.inner.push(path);
1186 /// Truncates `self` to [`self.parent`].
1188 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1189 /// Otherwise, returns `true`.
1191 /// [`self.parent`]: Path::parent
1196 /// use std::path::{Path, PathBuf};
1198 /// let mut p = PathBuf::from("/spirited/away.rs");
1201 /// assert_eq!(Path::new("/spirited"), p);
1203 /// assert_eq!(Path::new("/"), p);
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 pub fn pop(&mut self) -> bool {
1207 match self.parent().map(|p| p.as_u8_slice().len()) {
1209 self.as_mut_vec().truncate(len);
1216 /// Updates [`self.file_name`] to `file_name`.
1218 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1221 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1222 /// `file_name`. The new path will be a sibling of the original path.
1223 /// (That is, it will have the same parent.)
1225 /// [`self.file_name`]: Path::file_name
1226 /// [`pop`]: PathBuf::pop
1231 /// use std::path::PathBuf;
1233 /// let mut buf = PathBuf::from("/");
1234 /// assert!(buf.file_name() == None);
1235 /// buf.set_file_name("bar");
1236 /// assert!(buf == PathBuf::from("/bar"));
1237 /// assert!(buf.file_name().is_some());
1238 /// buf.set_file_name("baz.txt");
1239 /// assert!(buf == PathBuf::from("/baz.txt"));
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1243 self._set_file_name(file_name.as_ref())
1246 fn _set_file_name(&mut self, file_name: &OsStr) {
1247 if self.file_name().is_some() {
1248 let popped = self.pop();
1249 debug_assert!(popped);
1251 self.push(file_name);
1254 /// Updates [`self.extension`] to `extension`.
1256 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1257 /// returns `true` and updates the extension otherwise.
1259 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1262 /// [`self.file_name`]: Path::file_name
1263 /// [`self.extension`]: Path::extension
1268 /// use std::path::{Path, PathBuf};
1270 /// let mut p = PathBuf::from("/feel/the");
1272 /// p.set_extension("force");
1273 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1275 /// p.set_extension("dark_side");
1276 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1280 self._set_extension(extension.as_ref())
1283 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1284 let file_stem = match self.file_stem() {
1285 None => return false,
1286 Some(f) => os_str_as_u8_slice(f),
1289 // truncate until right after the file stem
1290 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1291 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1292 let v = self.as_mut_vec();
1293 v.truncate(end_file_stem.wrapping_sub(start));
1295 // add the new extension, if any
1296 let new = os_str_as_u8_slice(extension);
1297 if !new.is_empty() {
1298 v.reserve_exact(new.len() + 1);
1300 v.extend_from_slice(new);
1306 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1311 /// use std::path::PathBuf;
1313 /// let p = PathBuf::from("/the/head");
1314 /// let os_str = p.into_os_string();
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub fn into_os_string(self) -> OsString {
1321 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1322 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1323 pub fn into_boxed_path(self) -> Box<Path> {
1324 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1325 unsafe { Box::from_raw(rw) }
1328 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1330 /// [`capacity`]: OsString::capacity
1331 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1332 pub fn capacity(&self) -> usize {
1333 self.inner.capacity()
1336 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1338 /// [`clear`]: OsString::clear
1339 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1340 pub fn clear(&mut self) {
1344 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1346 /// [`reserve`]: OsString::reserve
1347 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1348 pub fn reserve(&mut self, additional: usize) {
1349 self.inner.reserve(additional)
1352 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1354 /// [`reserve_exact`]: OsString::reserve_exact
1355 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1356 pub fn reserve_exact(&mut self, additional: usize) {
1357 self.inner.reserve_exact(additional)
1360 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1362 /// [`shrink_to_fit`]: OsString::shrink_to_fit
1363 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1364 pub fn shrink_to_fit(&mut self) {
1365 self.inner.shrink_to_fit()
1368 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1370 /// [`shrink_to`]: OsString::shrink_to
1371 #[unstable(feature = "shrink_to", issue = "56431")]
1372 pub fn shrink_to(&mut self, min_capacity: usize) {
1373 self.inner.shrink_to(min_capacity)
1377 #[stable(feature = "box_from_path", since = "1.17.0")]
1378 impl From<&Path> for Box<Path> {
1379 fn from(path: &Path) -> Box<Path> {
1380 let boxed: Box<OsStr> = path.inner.into();
1381 let rw = Box::into_raw(boxed) as *mut Path;
1382 unsafe { Box::from_raw(rw) }
1386 #[stable(feature = "box_from_cow", since = "1.45.0")]
1387 impl From<Cow<'_, Path>> for Box<Path> {
1389 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1391 Cow::Borrowed(path) => Box::from(path),
1392 Cow::Owned(path) => Box::from(path),
1397 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1398 impl From<Box<Path>> for PathBuf {
1399 /// Converts a `Box<Path>` into a `PathBuf`
1401 /// This conversion does not allocate or copy memory.
1402 fn from(boxed: Box<Path>) -> PathBuf {
1403 boxed.into_path_buf()
1407 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1408 impl From<PathBuf> for Box<Path> {
1409 /// Converts a `PathBuf` into a `Box<Path>`
1411 /// This conversion currently should not allocate memory,
1412 /// but this behavior is not guaranteed on all platforms or in all future versions.
1413 fn from(p: PathBuf) -> Box<Path> {
1418 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1419 impl Clone for Box<Path> {
1421 fn clone(&self) -> Self {
1422 self.to_path_buf().into_boxed_path()
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1428 fn from(s: &T) -> PathBuf {
1429 PathBuf::from(s.as_ref().to_os_string())
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl From<OsString> for PathBuf {
1435 /// Converts a `OsString` into a `PathBuf`
1437 /// This conversion does not allocate or copy memory.
1439 fn from(s: OsString) -> PathBuf {
1440 PathBuf { inner: s }
1444 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1445 impl From<PathBuf> for OsString {
1446 /// Converts a `PathBuf` into a `OsString`
1448 /// This conversion does not allocate or copy memory.
1449 fn from(path_buf: PathBuf) -> OsString {
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 impl From<String> for PathBuf {
1456 /// Converts a `String` into a `PathBuf`
1458 /// This conversion does not allocate or copy memory.
1459 fn from(s: String) -> PathBuf {
1460 PathBuf::from(OsString::from(s))
1464 #[stable(feature = "path_from_str", since = "1.32.0")]
1465 impl FromStr for PathBuf {
1466 type Err = core::convert::Infallible;
1468 fn from_str(s: &str) -> Result<Self, Self::Err> {
1469 Ok(PathBuf::from(s))
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1475 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1476 let mut buf = PathBuf::new();
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1484 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1485 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1489 fn extend_one(&mut self, p: P) {
1490 self.push(p.as_ref());
1494 #[stable(feature = "rust1", since = "1.0.0")]
1495 impl fmt::Debug for PathBuf {
1496 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1497 fmt::Debug::fmt(&**self, formatter)
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl ops::Deref for PathBuf {
1505 fn deref(&self) -> &Path {
1506 Path::new(&self.inner)
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 impl Borrow<Path> for PathBuf {
1512 fn borrow(&self) -> &Path {
1517 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1518 impl Default for PathBuf {
1519 fn default() -> Self {
1524 #[stable(feature = "cow_from_path", since = "1.6.0")]
1525 impl<'a> From<&'a Path> for Cow<'a, Path> {
1527 fn from(s: &'a Path) -> Cow<'a, Path> {
1532 #[stable(feature = "cow_from_path", since = "1.6.0")]
1533 impl<'a> From<PathBuf> for Cow<'a, Path> {
1535 fn from(s: PathBuf) -> Cow<'a, Path> {
1540 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1541 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1543 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1544 Cow::Borrowed(p.as_path())
1548 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1549 impl<'a> From<Cow<'a, Path>> for PathBuf {
1551 fn from(p: Cow<'a, Path>) -> Self {
1556 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1557 impl From<PathBuf> for Arc<Path> {
1558 /// Converts a `PathBuf` into an `Arc` by moving the `PathBuf` data into a new `Arc` buffer.
1560 fn from(s: PathBuf) -> Arc<Path> {
1561 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1562 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1566 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1567 impl From<&Path> for Arc<Path> {
1568 /// Converts a `Path` into an `Arc` by copying the `Path` data into a new `Arc` buffer.
1570 fn from(s: &Path) -> Arc<Path> {
1571 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1572 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1576 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1577 impl From<PathBuf> for Rc<Path> {
1578 /// Converts a `PathBuf` into an `Rc` by moving the `PathBuf` data into a new `Rc` buffer.
1580 fn from(s: PathBuf) -> Rc<Path> {
1581 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1582 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1586 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1587 impl From<&Path> for Rc<Path> {
1588 /// Converts a `Path` into an `Rc` by copying the `Path` data into a new `Rc` buffer.
1590 fn from(s: &Path) -> Rc<Path> {
1591 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1592 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl ToOwned for Path {
1598 type Owned = PathBuf;
1599 fn to_owned(&self) -> PathBuf {
1602 fn clone_into(&self, target: &mut PathBuf) {
1603 self.inner.clone_into(&mut target.inner);
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl cmp::PartialEq for PathBuf {
1609 fn eq(&self, other: &PathBuf) -> bool {
1610 self.components() == other.components()
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl Hash for PathBuf {
1616 fn hash<H: Hasher>(&self, h: &mut H) {
1617 self.as_path().hash(h)
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl cmp::Eq for PathBuf {}
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl cmp::PartialOrd for PathBuf {
1626 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1627 self.components().partial_cmp(other.components())
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl cmp::Ord for PathBuf {
1633 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1634 self.components().cmp(other.components())
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl AsRef<OsStr> for PathBuf {
1640 fn as_ref(&self) -> &OsStr {
1645 /// A slice of a path (akin to [`str`]).
1647 /// This type supports a number of operations for inspecting a path, including
1648 /// breaking the path into its components (separated by `/` on Unix and by either
1649 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1650 /// is absolute, and so on.
1652 /// This is an *unsized* type, meaning that it must always be used behind a
1653 /// pointer like `&` or [`Box`]. For an owned version of this type,
1654 /// see [`PathBuf`].
1656 /// More details about the overall approach can be found in
1657 /// the [module documentation](index.html).
1662 /// use std::path::Path;
1663 /// use std::ffi::OsStr;
1665 /// // Note: this example does work on Windows
1666 /// let path = Path::new("./foo/bar.txt");
1668 /// let parent = path.parent();
1669 /// assert_eq!(parent, Some(Path::new("./foo")));
1671 /// let file_stem = path.file_stem();
1672 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1674 /// let extension = path.extension();
1675 /// assert_eq!(extension, Some(OsStr::new("txt")));
1677 #[stable(feature = "rust1", since = "1.0.0")]
1679 // `Path::new` current implementation relies
1680 // on `Path` being layout-compatible with `OsStr`.
1681 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1682 // Anyway, `Path` representation and layout are considered implementation detail, are
1683 // not documented and must not be relied upon.
1688 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1691 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1692 /// See its documentation for more.
1694 /// [`strip_prefix`]: Path::strip_prefix
1695 #[derive(Debug, Clone, PartialEq, Eq)]
1696 #[stable(since = "1.7.0", feature = "strip_prefix")]
1697 pub struct StripPrefixError(());
1700 // The following (private!) function allows construction of a path from a u8
1701 // slice, which is only safe when it is known to follow the OsStr encoding.
1702 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1703 unsafe { Path::new(u8_slice_as_os_str(s)) }
1705 // The following (private!) function reveals the byte encoding used for OsStr.
1706 fn as_u8_slice(&self) -> &[u8] {
1707 os_str_as_u8_slice(&self.inner)
1710 /// Directly wraps a string slice as a `Path` slice.
1712 /// This is a cost-free conversion.
1717 /// use std::path::Path;
1719 /// Path::new("foo.txt");
1722 /// You can create `Path`s from `String`s, or even other `Path`s:
1725 /// use std::path::Path;
1727 /// let string = String::from("foo.txt");
1728 /// let from_string = Path::new(&string);
1729 /// let from_path = Path::new(&from_string);
1730 /// assert_eq!(from_string, from_path);
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1734 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1737 /// Yields the underlying [`OsStr`] slice.
1742 /// use std::path::Path;
1744 /// let os_str = Path::new("foo.txt").as_os_str();
1745 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 pub fn as_os_str(&self) -> &OsStr {
1752 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1754 /// This conversion may entail doing a check for UTF-8 validity.
1755 /// Note that validation is performed because non-UTF-8 strings are
1756 /// perfectly valid for some OS.
1763 /// use std::path::Path;
1765 /// let path = Path::new("foo.txt");
1766 /// assert_eq!(path.to_str(), Some("foo.txt"));
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 pub fn to_str(&self) -> Option<&str> {
1773 /// Converts a `Path` to a [`Cow<str>`].
1775 /// Any non-Unicode sequences are replaced with
1776 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1778 /// [`Cow<str>`]: Cow
1779 /// [U+FFFD]: super::char::REPLACEMENT_CHARACTER
1783 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1786 /// use std::path::Path;
1788 /// let path = Path::new("foo.txt");
1789 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1792 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1793 /// have returned `"fo�.txt"`.
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1796 self.inner.to_string_lossy()
1799 /// Converts a `Path` to an owned [`PathBuf`].
1804 /// use std::path::Path;
1806 /// let path_buf = Path::new("foo.txt").to_path_buf();
1807 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1809 #[rustc_conversion_suggestion]
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 pub fn to_path_buf(&self) -> PathBuf {
1812 PathBuf::from(self.inner.to_os_string())
1815 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1816 /// the current directory.
1818 /// * On Unix, a path is absolute if it starts with the root, so
1819 /// `is_absolute` and [`has_root`] are equivalent.
1821 /// * On Windows, a path is absolute if it has a prefix and starts with the
1822 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1827 /// use std::path::Path;
1829 /// assert!(!Path::new("foo.txt").is_absolute());
1832 /// [`has_root`]: Path::has_root
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 #[allow(deprecated)]
1835 pub fn is_absolute(&self) -> bool {
1836 if cfg!(target_os = "redox") {
1837 // FIXME: Allow Redox prefixes
1838 self.has_root() || has_redox_scheme(self.as_u8_slice())
1840 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1844 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1846 /// See [`is_absolute`]'s documentation for more details.
1851 /// use std::path::Path;
1853 /// assert!(Path::new("foo.txt").is_relative());
1856 /// [`is_absolute`]: Path::is_absolute
1857 #[stable(feature = "rust1", since = "1.0.0")]
1858 pub fn is_relative(&self) -> bool {
1862 fn prefix(&self) -> Option<Prefix<'_>> {
1863 self.components().prefix
1866 /// Returns `true` if the `Path` has a root.
1868 /// * On Unix, a path has a root if it begins with `/`.
1870 /// * On Windows, a path has a root if it:
1871 /// * has no prefix and begins with a separator, e.g., `\windows`
1872 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1873 /// * has any non-disk prefix, e.g., `\\server\share`
1878 /// use std::path::Path;
1880 /// assert!(Path::new("/etc/passwd").has_root());
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn has_root(&self) -> bool {
1884 self.components().has_root()
1887 /// Returns the `Path` without its final component, if there is one.
1889 /// Returns [`None`] if the path terminates in a root or prefix.
1894 /// use std::path::Path;
1896 /// let path = Path::new("/foo/bar");
1897 /// let parent = path.parent().unwrap();
1898 /// assert_eq!(parent, Path::new("/foo"));
1900 /// let grand_parent = parent.parent().unwrap();
1901 /// assert_eq!(grand_parent, Path::new("/"));
1902 /// assert_eq!(grand_parent.parent(), None);
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 pub fn parent(&self) -> Option<&Path> {
1906 let mut comps = self.components();
1907 let comp = comps.next_back();
1908 comp.and_then(|p| match p {
1909 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
1910 Some(comps.as_path())
1916 /// Produces an iterator over `Path` and its ancestors.
1918 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1919 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1920 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1921 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1927 /// use std::path::Path;
1929 /// let mut ancestors = Path::new("/foo/bar").ancestors();
1930 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1931 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1932 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1933 /// assert_eq!(ancestors.next(), None);
1935 /// let mut ancestors = Path::new("../foo/bar").ancestors();
1936 /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
1937 /// assert_eq!(ancestors.next(), Some(Path::new("../foo")));
1938 /// assert_eq!(ancestors.next(), Some(Path::new("..")));
1939 /// assert_eq!(ancestors.next(), Some(Path::new("")));
1940 /// assert_eq!(ancestors.next(), None);
1943 /// [`parent`]: Path::parent
1944 #[stable(feature = "path_ancestors", since = "1.28.0")]
1945 pub fn ancestors(&self) -> Ancestors<'_> {
1946 Ancestors { next: Some(&self) }
1949 /// Returns the final component of the `Path`, if there is one.
1951 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1952 /// is the directory name.
1954 /// Returns [`None`] if the path terminates in `..`.
1959 /// use std::path::Path;
1960 /// use std::ffi::OsStr;
1962 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1963 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1964 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1965 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1966 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1967 /// assert_eq!(None, Path::new("/").file_name());
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 pub fn file_name(&self) -> Option<&OsStr> {
1971 self.components().next_back().and_then(|p| match p {
1972 Component::Normal(p) => Some(p),
1977 /// Returns a path that, when joined onto `base`, yields `self`.
1981 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
1982 /// returns `false`), returns [`Err`].
1984 /// [`starts_with`]: Path::starts_with
1989 /// use std::path::{Path, PathBuf};
1991 /// let path = Path::new("/test/haha/foo.txt");
1993 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
1994 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1995 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
1996 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
1997 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
1999 /// assert!(path.strip_prefix("test").is_err());
2000 /// assert!(path.strip_prefix("/haha").is_err());
2002 /// let prefix = PathBuf::from("/test/");
2003 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2005 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2006 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2010 self._strip_prefix(base.as_ref())
2013 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2014 iter_after(self.components(), base.components())
2015 .map(|c| c.as_path())
2016 .ok_or(StripPrefixError(()))
2019 /// Determines whether `base` is a prefix of `self`.
2021 /// Only considers whole path components to match.
2026 /// use std::path::Path;
2028 /// let path = Path::new("/etc/passwd");
2030 /// assert!(path.starts_with("/etc"));
2031 /// assert!(path.starts_with("/etc/"));
2032 /// assert!(path.starts_with("/etc/passwd"));
2033 /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
2034 /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
2036 /// assert!(!path.starts_with("/e"));
2037 /// assert!(!path.starts_with("/etc/passwd.txt"));
2039 /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
2041 #[stable(feature = "rust1", since = "1.0.0")]
2042 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2043 self._starts_with(base.as_ref())
2046 fn _starts_with(&self, base: &Path) -> bool {
2047 iter_after(self.components(), base.components()).is_some()
2050 /// Determines whether `child` is a suffix of `self`.
2052 /// Only considers whole path components to match.
2057 /// use std::path::Path;
2059 /// let path = Path::new("/etc/passwd");
2061 /// assert!(path.ends_with("passwd"));
2063 #[stable(feature = "rust1", since = "1.0.0")]
2064 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2065 self._ends_with(child.as_ref())
2068 fn _ends_with(&self, child: &Path) -> bool {
2069 iter_after(self.components().rev(), child.components().rev()).is_some()
2072 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2074 /// [`self.file_name`]: Path::file_name
2078 /// * [`None`], if there is no file name;
2079 /// * The entire file name if there is no embedded `.`;
2080 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2081 /// * Otherwise, the portion of the file name before the final `.`
2086 /// use std::path::Path;
2088 /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
2089 /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 pub fn file_stem(&self) -> Option<&OsStr> {
2093 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2096 /// Extracts the extension of [`self.file_name`], if possible.
2098 /// The extension is:
2100 /// * [`None`], if there is no file name;
2101 /// * [`None`], if there is no embedded `.`;
2102 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2103 /// * Otherwise, the portion of the file name after the final `.`
2105 /// [`self.file_name`]: Path::file_name
2110 /// use std::path::Path;
2112 /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
2113 /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 pub fn extension(&self) -> Option<&OsStr> {
2117 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2120 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2122 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2127 /// use std::path::{Path, PathBuf};
2129 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2131 #[stable(feature = "rust1", since = "1.0.0")]
2133 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2134 self._join(path.as_ref())
2137 fn _join(&self, path: &Path) -> PathBuf {
2138 let mut buf = self.to_path_buf();
2143 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2145 /// See [`PathBuf::set_file_name`] for more details.
2150 /// use std::path::{Path, PathBuf};
2152 /// let path = Path::new("/tmp/foo.txt");
2153 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2155 /// let path = Path::new("/tmp");
2156 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2160 self._with_file_name(file_name.as_ref())
2163 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2164 let mut buf = self.to_path_buf();
2165 buf.set_file_name(file_name);
2169 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2171 /// See [`PathBuf::set_extension`] for more details.
2176 /// use std::path::{Path, PathBuf};
2178 /// let path = Path::new("foo.rs");
2179 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2181 /// let path = Path::new("foo.tar.gz");
2182 /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
2183 /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
2184 /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
2186 #[stable(feature = "rust1", since = "1.0.0")]
2187 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2188 self._with_extension(extension.as_ref())
2191 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2192 let mut buf = self.to_path_buf();
2193 buf.set_extension(extension);
2197 /// Produces an iterator over the [`Component`]s of the path.
2199 /// When parsing the path, there is a small amount of normalization:
2201 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2202 /// `a` and `b` as components.
2204 /// * Occurrences of `.` are normalized away, except if they are at the
2205 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2206 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2207 /// an additional [`CurDir`] component.
2209 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2211 /// Note that no other normalization takes place; in particular, `a/c`
2212 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2213 /// is a symbolic link (so its parent isn't `a`).
2218 /// use std::path::{Path, Component};
2219 /// use std::ffi::OsStr;
2221 /// let mut components = Path::new("/tmp/foo.txt").components();
2223 /// assert_eq!(components.next(), Some(Component::RootDir));
2224 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2225 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2226 /// assert_eq!(components.next(), None)
2229 /// [`CurDir`]: Component::CurDir
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 pub fn components(&self) -> Components<'_> {
2232 let prefix = parse_prefix(self.as_os_str());
2234 path: self.as_u8_slice(),
2236 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2237 || has_redox_scheme(self.as_u8_slice()),
2238 front: State::Prefix,
2243 /// Produces an iterator over the path's components viewed as [`OsStr`]
2246 /// For more information about the particulars of how the path is separated
2247 /// into components, see [`components`].
2249 /// [`components`]: Path::components
2254 /// use std::path::{self, Path};
2255 /// use std::ffi::OsStr;
2257 /// let mut it = Path::new("/tmp/foo.txt").iter();
2258 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2259 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2260 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2261 /// assert_eq!(it.next(), None)
2263 #[stable(feature = "rust1", since = "1.0.0")]
2264 pub fn iter(&self) -> Iter<'_> {
2265 Iter { inner: self.components() }
2268 /// Returns an object that implements [`Display`] for safely printing paths
2269 /// that may contain non-Unicode data.
2271 /// [`Display`]: fmt::Display
2276 /// use std::path::Path;
2278 /// let path = Path::new("/tmp/foo.rs");
2280 /// println!("{}", path.display());
2282 #[stable(feature = "rust1", since = "1.0.0")]
2283 pub fn display(&self) -> Display<'_> {
2284 Display { path: self }
2287 /// Queries the file system to get information about a file, directory, etc.
2289 /// This function will traverse symbolic links to query information about the
2290 /// destination file.
2292 /// This is an alias to [`fs::metadata`].
2297 /// use std::path::Path;
2299 /// let path = Path::new("/Minas/tirith");
2300 /// let metadata = path.metadata().expect("metadata call failed");
2301 /// println!("{:?}", metadata.file_type());
2303 #[stable(feature = "path_ext", since = "1.5.0")]
2304 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2308 /// Queries the metadata about a file without following symlinks.
2310 /// This is an alias to [`fs::symlink_metadata`].
2315 /// use std::path::Path;
2317 /// let path = Path::new("/Minas/tirith");
2318 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2319 /// println!("{:?}", metadata.file_type());
2321 #[stable(feature = "path_ext", since = "1.5.0")]
2322 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2323 fs::symlink_metadata(self)
2326 /// Returns the canonical, absolute form of the path with all intermediate
2327 /// components normalized and symbolic links resolved.
2329 /// This is an alias to [`fs::canonicalize`].
2334 /// use std::path::{Path, PathBuf};
2336 /// let path = Path::new("/foo/test/../test/bar.rs");
2337 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2339 #[stable(feature = "path_ext", since = "1.5.0")]
2340 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2341 fs::canonicalize(self)
2344 /// Reads a symbolic link, returning the file that the link points to.
2346 /// This is an alias to [`fs::read_link`].
2351 /// use std::path::Path;
2353 /// let path = Path::new("/laputa/sky_castle.rs");
2354 /// let path_link = path.read_link().expect("read_link call failed");
2356 #[stable(feature = "path_ext", since = "1.5.0")]
2357 pub fn read_link(&self) -> io::Result<PathBuf> {
2361 /// Returns an iterator over the entries within a directory.
2363 /// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New
2364 /// errors may be encountered after an iterator is initially constructed.
2366 /// This is an alias to [`fs::read_dir`].
2371 /// use std::path::Path;
2373 /// let path = Path::new("/laputa");
2374 /// for entry in path.read_dir().expect("read_dir call failed") {
2375 /// if let Ok(entry) = entry {
2376 /// println!("{:?}", entry.path());
2380 #[stable(feature = "path_ext", since = "1.5.0")]
2381 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2385 /// Returns `true` if the path points at an existing entity.
2387 /// This function will traverse symbolic links to query information about the
2388 /// destination file. In case of broken symbolic links this will return `false`.
2390 /// If you cannot access the directory containing the file, e.g., because of a
2391 /// permission error, this will return `false`.
2396 /// use std::path::Path;
2397 /// assert!(!Path::new("does_not_exist.txt").exists());
2402 /// This is a convenience function that coerces errors to false. If you want to
2403 /// check errors, call [`fs::metadata`].
2404 #[stable(feature = "path_ext", since = "1.5.0")]
2405 pub fn exists(&self) -> bool {
2406 fs::metadata(self).is_ok()
2409 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2411 /// This function will traverse symbolic links to query information about the
2412 /// destination file. In case of broken symbolic links this will return `false`.
2414 /// If you cannot access the directory containing the file, e.g., because of a
2415 /// permission error, this will return `false`.
2420 /// use std::path::Path;
2421 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2422 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2427 /// This is a convenience function that coerces errors to false. If you want to
2428 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2429 /// [`fs::Metadata::is_file`] if it was [`Ok`].
2431 /// When the goal is simply to read from (or write to) the source, the most
2432 /// reliable way to test the source can be read (or written to) is to open
2433 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2434 /// a Unix-like system for example. See [`fs::File::open`] or
2435 /// [`fs::OpenOptions::open`] for more information.
2436 #[stable(feature = "path_ext", since = "1.5.0")]
2437 pub fn is_file(&self) -> bool {
2438 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2441 /// Returns `true` if the path exists on disk and is pointing at a directory.
2443 /// This function will traverse symbolic links to query information about the
2444 /// destination file. In case of broken symbolic links this will return `false`.
2446 /// If you cannot access the directory containing the file, e.g., because of a
2447 /// permission error, this will return `false`.
2452 /// use std::path::Path;
2453 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2454 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2459 /// This is a convenience function that coerces errors to false. If you want to
2460 /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
2461 /// [`fs::Metadata::is_dir`] if it was [`Ok`].
2462 #[stable(feature = "path_ext", since = "1.5.0")]
2463 pub fn is_dir(&self) -> bool {
2464 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2467 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2469 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2470 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2471 let rw = Box::into_raw(self) as *mut OsStr;
2472 let inner = unsafe { Box::from_raw(rw) };
2473 PathBuf { inner: OsString::from(inner) }
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl AsRef<OsStr> for Path {
2479 fn as_ref(&self) -> &OsStr {
2484 #[stable(feature = "rust1", since = "1.0.0")]
2485 impl fmt::Debug for Path {
2486 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2487 fmt::Debug::fmt(&self.inner, formatter)
2491 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2493 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2494 /// [`Display`] trait in a way that mitigates that. It is created by the
2495 /// [`display`][`Path::display`] method on [`Path`].
2500 /// use std::path::Path;
2502 /// let path = Path::new("/tmp/foo.rs");
2504 /// println!("{}", path.display());
2507 /// [`Display`]: fmt::Display
2508 /// [`format!`]: crate::format
2509 #[stable(feature = "rust1", since = "1.0.0")]
2510 pub struct Display<'a> {
2514 #[stable(feature = "rust1", since = "1.0.0")]
2515 impl fmt::Debug for Display<'_> {
2516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2517 fmt::Debug::fmt(&self.path, f)
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl fmt::Display for Display<'_> {
2523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2524 self.path.inner.display(f)
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 impl cmp::PartialEq for Path {
2530 fn eq(&self, other: &Path) -> bool {
2531 self.components().eq(other.components())
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 impl Hash for Path {
2537 fn hash<H: Hasher>(&self, h: &mut H) {
2538 for component in self.components() {
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl cmp::Eq for Path {}
2547 #[stable(feature = "rust1", since = "1.0.0")]
2548 impl cmp::PartialOrd for Path {
2549 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2550 self.components().partial_cmp(other.components())
2554 #[stable(feature = "rust1", since = "1.0.0")]
2555 impl cmp::Ord for Path {
2556 fn cmp(&self, other: &Path) -> cmp::Ordering {
2557 self.components().cmp(other.components())
2561 #[stable(feature = "rust1", since = "1.0.0")]
2562 impl AsRef<Path> for Path {
2563 fn as_ref(&self) -> &Path {
2568 #[stable(feature = "rust1", since = "1.0.0")]
2569 impl AsRef<Path> for OsStr {
2570 fn as_ref(&self) -> &Path {
2575 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2576 impl AsRef<Path> for Cow<'_, OsStr> {
2577 fn as_ref(&self) -> &Path {
2582 #[stable(feature = "rust1", since = "1.0.0")]
2583 impl AsRef<Path> for OsString {
2584 fn as_ref(&self) -> &Path {
2589 #[stable(feature = "rust1", since = "1.0.0")]
2590 impl AsRef<Path> for str {
2592 fn as_ref(&self) -> &Path {
2597 #[stable(feature = "rust1", since = "1.0.0")]
2598 impl AsRef<Path> for String {
2599 fn as_ref(&self) -> &Path {
2604 #[stable(feature = "rust1", since = "1.0.0")]
2605 impl AsRef<Path> for PathBuf {
2607 fn as_ref(&self) -> &Path {
2612 #[stable(feature = "path_into_iter", since = "1.6.0")]
2613 impl<'a> IntoIterator for &'a PathBuf {
2614 type Item = &'a OsStr;
2615 type IntoIter = Iter<'a>;
2616 fn into_iter(self) -> Iter<'a> {
2621 #[stable(feature = "path_into_iter", since = "1.6.0")]
2622 impl<'a> IntoIterator for &'a Path {
2623 type Item = &'a OsStr;
2624 type IntoIter = Iter<'a>;
2625 fn into_iter(self) -> Iter<'a> {
2630 macro_rules! impl_cmp {
2631 ($lhs:ty, $rhs: ty) => {
2632 #[stable(feature = "partialeq_path", since = "1.6.0")]
2633 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2635 fn eq(&self, other: &$rhs) -> bool {
2636 <Path as PartialEq>::eq(self, other)
2640 #[stable(feature = "partialeq_path", since = "1.6.0")]
2641 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2643 fn eq(&self, other: &$lhs) -> bool {
2644 <Path as PartialEq>::eq(self, other)
2648 #[stable(feature = "cmp_path", since = "1.8.0")]
2649 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2651 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2652 <Path as PartialOrd>::partial_cmp(self, other)
2656 #[stable(feature = "cmp_path", since = "1.8.0")]
2657 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2659 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2660 <Path as PartialOrd>::partial_cmp(self, other)
2666 impl_cmp!(PathBuf, Path);
2667 impl_cmp!(PathBuf, &'a Path);
2668 impl_cmp!(Cow<'a, Path>, Path);
2669 impl_cmp!(Cow<'a, Path>, &'b Path);
2670 impl_cmp!(Cow<'a, Path>, PathBuf);
2672 macro_rules! impl_cmp_os_str {
2673 ($lhs:ty, $rhs: ty) => {
2674 #[stable(feature = "cmp_path", since = "1.8.0")]
2675 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2677 fn eq(&self, other: &$rhs) -> bool {
2678 <Path as PartialEq>::eq(self, other.as_ref())
2682 #[stable(feature = "cmp_path", since = "1.8.0")]
2683 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2685 fn eq(&self, other: &$lhs) -> bool {
2686 <Path as PartialEq>::eq(self.as_ref(), other)
2690 #[stable(feature = "cmp_path", since = "1.8.0")]
2691 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2693 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2694 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2698 #[stable(feature = "cmp_path", since = "1.8.0")]
2699 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2701 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2702 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2708 impl_cmp_os_str!(PathBuf, OsStr);
2709 impl_cmp_os_str!(PathBuf, &'a OsStr);
2710 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2711 impl_cmp_os_str!(PathBuf, OsString);
2712 impl_cmp_os_str!(Path, OsStr);
2713 impl_cmp_os_str!(Path, &'a OsStr);
2714 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2715 impl_cmp_os_str!(Path, OsString);
2716 impl_cmp_os_str!(&'a Path, OsStr);
2717 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2718 impl_cmp_os_str!(&'a Path, OsString);
2719 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2720 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2721 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2723 #[stable(since = "1.7.0", feature = "strip_prefix")]
2724 impl fmt::Display for StripPrefixError {
2725 #[allow(deprecated, deprecated_in_future)]
2726 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2727 self.description().fmt(f)
2731 #[stable(since = "1.7.0", feature = "strip_prefix")]
2732 impl Error for StripPrefixError {
2733 #[allow(deprecated)]
2734 fn description(&self) -> &str {
2744 use crate::sync::Arc;
2747 ($path:expr, iter: $iter:expr) => (
2749 let path = Path::new($path);
2751 // Forward iteration
2752 let comps = path.iter()
2753 .map(|p| p.to_string_lossy().into_owned())
2754 .collect::<Vec<String>>();
2755 let exp: &[&str] = &$iter;
2756 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2757 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2760 // Reverse iteration
2761 let comps = Path::new($path).iter().rev()
2762 .map(|p| p.to_string_lossy().into_owned())
2763 .collect::<Vec<String>>();
2764 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2765 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2770 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2772 let path = Path::new($path);
2774 let act_root = path.has_root();
2775 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2776 $has_root, act_root);
2778 let act_abs = path.is_absolute();
2779 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2780 $is_absolute, act_abs);
2784 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2786 let path = Path::new($path);
2788 let parent = path.parent().map(|p| p.to_str().unwrap());
2789 let exp_parent: Option<&str> = $parent;
2790 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2791 exp_parent, parent);
2793 let file = path.file_name().map(|p| p.to_str().unwrap());
2794 let exp_file: Option<&str> = $file;
2795 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2800 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2802 let path = Path::new($path);
2804 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2805 let exp_stem: Option<&str> = $file_stem;
2806 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2809 let ext = path.extension().map(|p| p.to_str().unwrap());
2810 let exp_ext: Option<&str> = $extension;
2811 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2816 ($path:expr, iter: $iter:expr,
2817 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2818 parent: $parent:expr, file_name: $file:expr,
2819 file_stem: $file_stem:expr, extension: $extension:expr) => (
2821 t!($path, iter: $iter);
2822 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2823 t!($path, parent: $parent, file_name: $file);
2824 t!($path, file_stem: $file_stem, extension: $extension);
2831 use crate::borrow::Cow;
2833 let static_path = Path::new("/home/foo");
2834 let static_cow_path: Cow<'static, Path> = static_path.into();
2835 let pathbuf = PathBuf::from("/home/foo");
2838 let path: &Path = &pathbuf;
2839 let borrowed_cow_path: Cow<'_, Path> = path.into();
2841 assert_eq!(static_cow_path, borrowed_cow_path);
2844 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2846 assert_eq!(static_cow_path, owned_cow_path);
2851 pub fn test_decompositions_unix() {
2867 file_name: Some("foo"),
2868 file_stem: Some("foo"),
2887 file_name: Some("foo"),
2888 file_stem: Some("foo"),
2897 file_name: Some("foo"),
2898 file_stem: Some("foo"),
2907 file_name: Some("foo"),
2908 file_stem: Some("foo"),
2913 iter: ["foo", "bar"],
2916 parent: Some("foo"),
2917 file_name: Some("bar"),
2918 file_stem: Some("bar"),
2923 iter: ["/", "foo", "bar"],
2926 parent: Some("/foo"),
2927 file_name: Some("bar"),
2928 file_stem: Some("bar"),
2937 file_name: Some("foo"),
2938 file_stem: Some("foo"),
2943 iter: ["/", "foo", "bar"],
2946 parent: Some("///foo"),
2947 file_name: Some("bar"),
2948 file_stem: Some("bar"),
2987 file_name: Some("foo"),
2988 file_stem: Some("foo"),
2993 iter: ["foo", ".."],
2996 parent: Some("foo"),
3007 file_name: Some("foo"),
3008 file_stem: Some("foo"),
3013 iter: ["foo", "bar"],
3016 parent: Some("foo"),
3017 file_name: Some("bar"),
3018 file_stem: Some("bar"),
3023 iter: ["foo", ".."],
3026 parent: Some("foo"),
3033 iter: ["foo", "..", "bar"],
3036 parent: Some("foo/.."),
3037 file_name: Some("bar"),
3038 file_stem: Some("bar"),
3047 file_name: Some("a"),
3048 file_stem: Some("a"),
3077 file_name: Some("b"),
3078 file_stem: Some("b"),
3087 file_name: Some("b"),
3088 file_stem: Some("b"),
3097 file_name: Some("b"),
3098 file_stem: Some("b"),
3103 iter: ["a", "b", "c"],
3106 parent: Some("a/b"),
3107 file_name: Some("c"),
3108 file_stem: Some("c"),
3117 file_name: Some(".foo"),
3118 file_stem: Some(".foo"),
3125 pub fn test_decompositions_windows() {
3141 file_name: Some("foo"),
3142 file_stem: Some("foo"),
3197 iter: ["\\", "foo"],
3201 file_name: Some("foo"),
3202 file_stem: Some("foo"),
3211 file_name: Some("foo"),
3212 file_stem: Some("foo"),
3217 iter: ["\\", "foo"],
3221 file_name: Some("foo"),
3222 file_stem: Some("foo"),
3227 iter: ["foo", "bar"],
3230 parent: Some("foo"),
3231 file_name: Some("bar"),
3232 file_stem: Some("bar"),
3237 iter: ["\\", "foo", "bar"],
3240 parent: Some("/foo"),
3241 file_name: Some("bar"),
3242 file_stem: Some("bar"),
3247 iter: ["\\", "foo"],
3251 file_name: Some("foo"),
3252 file_stem: Some("foo"),
3257 iter: ["\\", "foo", "bar"],
3260 parent: Some("///foo"),
3261 file_name: Some("bar"),
3262 file_stem: Some("bar"),
3301 file_name: Some("foo"),
3302 file_stem: Some("foo"),
3307 iter: ["foo", ".."],
3310 parent: Some("foo"),
3321 file_name: Some("foo"),
3322 file_stem: Some("foo"),
3327 iter: ["foo", "bar"],
3330 parent: Some("foo"),
3331 file_name: Some("bar"),
3332 file_stem: Some("bar"),
3337 iter: ["foo", ".."],
3340 parent: Some("foo"),
3347 iter: ["foo", "..", "bar"],
3350 parent: Some("foo/.."),
3351 file_name: Some("bar"),
3352 file_stem: Some("bar"),
3361 file_name: Some("a"),
3362 file_stem: Some("a"),
3391 file_name: Some("b"),
3392 file_stem: Some("b"),
3401 file_name: Some("b"),
3402 file_stem: Some("b"),
3411 file_name: Some("b"),
3412 file_stem: Some("b"),
3417 iter: ["a", "b", "c"],
3420 parent: Some("a/b"),
3421 file_name: Some("c"),
3422 file_stem: Some("c"),
3426 iter: ["a", "b", "c"],
3429 parent: Some("a\\b"),
3430 file_name: Some("c"),
3431 file_stem: Some("c"),
3440 file_name: Some("a"),
3441 file_stem: Some("a"),
3446 iter: ["c:", "\\", "foo.txt"],
3449 parent: Some("c:\\"),
3450 file_name: Some("foo.txt"),
3451 file_stem: Some("foo"),
3452 extension: Some("txt")
3455 t!("\\\\server\\share\\foo.txt",
3456 iter: ["\\\\server\\share", "\\", "foo.txt"],
3459 parent: Some("\\\\server\\share\\"),
3460 file_name: Some("foo.txt"),
3461 file_stem: Some("foo"),
3462 extension: Some("txt")
3465 t!("\\\\server\\share",
3466 iter: ["\\\\server\\share", "\\"],
3476 iter: ["\\", "server"],
3480 file_name: Some("server"),
3481 file_stem: Some("server"),
3485 t!("\\\\?\\bar\\foo.txt",
3486 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3489 parent: Some("\\\\?\\bar\\"),
3490 file_name: Some("foo.txt"),
3491 file_stem: Some("foo"),
3492 extension: Some("txt")
3496 iter: ["\\\\?\\bar"],
3515 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3516 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3519 parent: Some("\\\\?\\UNC\\server\\share\\"),
3520 file_name: Some("foo.txt"),
3521 file_stem: Some("foo"),
3522 extension: Some("txt")
3525 t!("\\\\?\\UNC\\server",
3526 iter: ["\\\\?\\UNC\\server"],
3536 iter: ["\\\\?\\UNC\\"],
3545 t!("\\\\?\\C:\\foo.txt",
3546 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3549 parent: Some("\\\\?\\C:\\"),
3550 file_name: Some("foo.txt"),
3551 file_stem: Some("foo"),
3552 extension: Some("txt")
3556 iter: ["\\\\?\\C:", "\\"],
3566 iter: ["\\\\?\\C:"],
3575 t!("\\\\?\\foo/bar",
3576 iter: ["\\\\?\\foo/bar"],
3586 iter: ["\\\\?\\C:/foo"],
3595 t!("\\\\.\\foo\\bar",
3596 iter: ["\\\\.\\foo", "\\", "bar"],
3599 parent: Some("\\\\.\\foo\\"),
3600 file_name: Some("bar"),
3601 file_stem: Some("bar"),
3606 iter: ["\\\\.\\foo", "\\"],
3615 t!("\\\\.\\foo/bar",
3616 iter: ["\\\\.\\foo/bar", "\\"],
3625 t!("\\\\.\\foo\\bar/baz",
3626 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3629 parent: Some("\\\\.\\foo\\bar"),
3630 file_name: Some("baz"),
3631 file_stem: Some("baz"),
3636 iter: ["\\\\.\\", "\\"],
3646 iter: ["\\\\?\\a", "\\", "b"],
3649 parent: Some("\\\\?\\a\\"),
3650 file_name: Some("b"),
3651 file_stem: Some("b"),
3657 pub fn test_stem_ext() {
3659 file_stem: Some("foo"),
3664 file_stem: Some("foo"),
3669 file_stem: Some(".foo"),
3674 file_stem: Some("foo"),
3675 extension: Some("txt")
3679 file_stem: Some("foo.bar"),
3680 extension: Some("txt")
3684 file_stem: Some("foo.bar"),
3688 t!(".", file_stem: None, extension: None);
3690 t!("..", file_stem: None, extension: None);
3692 t!("", file_stem: None, extension: None);
3696 pub fn test_push() {
3698 ($path:expr, $push:expr, $expected:expr) => ( {
3699 let mut actual = PathBuf::from($path);
3701 assert!(actual.to_str() == Some($expected),
3702 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3703 $push, $path, $expected, actual.to_str().unwrap());
3707 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3708 tp!("", "foo", "foo");
3709 tp!("foo", "bar", "foo/bar");
3710 tp!("foo/", "bar", "foo/bar");
3711 tp!("foo//", "bar", "foo//bar");
3712 tp!("foo/.", "bar", "foo/./bar");
3713 tp!("foo./.", "bar", "foo././bar");
3714 tp!("foo", "", "foo/");
3715 tp!("foo", ".", "foo/.");
3716 tp!("foo", "..", "foo/..");
3717 tp!("foo", "/", "/");
3718 tp!("/foo/bar", "/", "/");
3719 tp!("/foo/bar", "/baz", "/baz");
3720 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3722 tp!("", "foo", "foo");
3723 tp!("foo", "bar", r"foo\bar");
3724 tp!("foo/", "bar", r"foo/bar");
3725 tp!(r"foo\", "bar", r"foo\bar");
3726 tp!("foo//", "bar", r"foo//bar");
3727 tp!(r"foo\\", "bar", r"foo\\bar");
3728 tp!("foo/.", "bar", r"foo/.\bar");
3729 tp!("foo./.", "bar", r"foo./.\bar");
3730 tp!(r"foo\.", "bar", r"foo\.\bar");
3731 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3732 tp!("foo", "", "foo\\");
3733 tp!("foo", ".", r"foo\.");
3734 tp!("foo", "..", r"foo\..");
3735 tp!("foo", "/", "/");
3736 tp!("foo", r"\", r"\");
3737 tp!("/foo/bar", "/", "/");
3738 tp!(r"\foo\bar", r"\", r"\");
3739 tp!("/foo/bar", "/baz", "/baz");
3740 tp!("/foo/bar", r"\baz", r"\baz");
3741 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3742 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3744 tp!("c:\\", "windows", "c:\\windows");
3745 tp!("c:", "windows", "c:windows");
3747 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3748 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3749 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3750 tp!("a\\b", "\\c\\d", "\\c\\d");
3751 tp!("a\\b", ".", "a\\b\\.");
3752 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3753 tp!("a\\b", "C:a.txt", "C:a.txt");
3754 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3755 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3756 tp!("C:\\a\\b\\c", "C:d", "C:d");
3757 tp!("C:a\\b\\c", "C:d", "C:d");
3758 tp!("C:", r"a\b\c", r"C:a\b\c");
3759 tp!("C:", r"..\a", r"C:..\a");
3760 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
3761 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3762 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3763 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3764 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3765 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3766 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
3767 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3768 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3770 // Note: modified from old path API
3771 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3773 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
3774 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3775 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3776 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3777 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3779 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3786 ($path:expr, $expected:expr, $output:expr) => ( {
3787 let mut actual = PathBuf::from($path);
3788 let output = actual.pop();
3789 assert!(actual.to_str() == Some($expected) && output == $output,
3790 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3791 $path, $expected, $output,
3792 actual.to_str().unwrap(), output);
3797 tp!("/", "/", false);
3798 tp!("foo", "", true);
3800 tp!("/foo", "/", true);
3801 tp!("/foo/bar", "/foo", true);
3802 tp!("foo/bar", "foo", true);
3803 tp!("foo/.", "", true);
3804 tp!("foo//bar", "foo", true);
3807 tp!("a\\b\\c", "a\\b", true);
3808 tp!("\\a", "\\", true);
3809 tp!("\\", "\\", false);
3811 tp!("C:\\a\\b", "C:\\a", true);
3812 tp!("C:\\a", "C:\\", true);
3813 tp!("C:\\", "C:\\", false);
3814 tp!("C:a\\b", "C:a", true);
3815 tp!("C:a", "C:", true);
3816 tp!("C:", "C:", false);
3817 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3818 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3819 tp!("\\\\server\\share", "\\\\server\\share", false);
3820 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3821 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3822 tp!("\\\\?\\a", "\\\\?\\a", false);
3823 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3824 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3825 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3826 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
3827 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
3828 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
3829 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3830 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3831 tp!("\\\\.\\a", "\\\\.\\a", false);
3833 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3838 pub fn test_set_file_name() {
3840 ($path:expr, $file:expr, $expected:expr) => ( {
3841 let mut p = PathBuf::from($path);
3842 p.set_file_name($file);
3843 assert!(p.to_str() == Some($expected),
3844 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3845 $path, $file, $expected,
3846 p.to_str().unwrap());
3850 tfn!("foo", "foo", "foo");
3851 tfn!("foo", "bar", "bar");
3852 tfn!("foo", "", "");
3853 tfn!("", "foo", "foo");
3854 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3855 tfn!(".", "foo", "./foo");
3856 tfn!("foo/", "bar", "bar");
3857 tfn!("foo/.", "bar", "bar");
3858 tfn!("..", "foo", "../foo");
3859 tfn!("foo/..", "bar", "foo/../bar");
3860 tfn!("/", "foo", "/foo");
3862 tfn!(".", "foo", r".\foo");
3863 tfn!(r"foo\", "bar", r"bar");
3864 tfn!(r"foo\.", "bar", r"bar");
3865 tfn!("..", "foo", r"..\foo");
3866 tfn!(r"foo\..", "bar", r"foo\..\bar");
3867 tfn!(r"\", "foo", r"\foo");
3872 pub fn test_set_extension() {
3874 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3875 let mut p = PathBuf::from($path);
3876 let output = p.set_extension($ext);
3877 assert!(p.to_str() == Some($expected) && output == $output,
3878 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3879 $path, $ext, $expected, $output,
3880 p.to_str().unwrap(), output);
3884 tfe!("foo", "txt", "foo.txt", true);
3885 tfe!("foo.bar", "txt", "foo.txt", true);
3886 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3887 tfe!(".test", "txt", ".test.txt", true);
3888 tfe!("foo.txt", "", "foo", true);
3889 tfe!("foo", "", "foo", true);
3890 tfe!("", "foo", "", false);
3891 tfe!(".", "foo", ".", false);
3892 tfe!("foo/", "bar", "foo.bar", true);
3893 tfe!("foo/.", "bar", "foo.bar", true);
3894 tfe!("..", "foo", "..", false);
3895 tfe!("foo/..", "bar", "foo/..", false);
3896 tfe!("/", "foo", "/", false);
3900 fn test_eq_receivers() {
3901 use crate::borrow::Cow;
3903 let borrowed: &Path = Path::new("foo/bar");
3904 let mut owned: PathBuf = PathBuf::new();
3907 let borrowed_cow: Cow<'_, Path> = borrowed.into();
3908 let owned_cow: Cow<'_, Path> = owned.clone().into();
3911 ($($current:expr),+) => {
3913 assert_eq!($current, borrowed);
3914 assert_eq!($current, owned);
3915 assert_eq!($current, borrowed_cow);
3916 assert_eq!($current, owned_cow);
3921 t!(borrowed, owned, borrowed_cow, owned_cow);
3925 pub fn test_compare() {
3926 use crate::collections::hash_map::DefaultHasher;
3927 use crate::hash::{Hash, Hasher};
3929 fn hash<T: Hash>(t: T) -> u64 {
3930 let mut s = DefaultHasher::new();
3936 ($path1:expr, $path2:expr, eq: $eq:expr,
3937 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3938 relative_from: $relative_from:expr) => ({
3939 let path1 = Path::new($path1);
3940 let path2 = Path::new($path2);
3942 let eq = path1 == path2;
3943 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3944 $path1, $path2, $eq, eq);
3945 assert!($eq == (hash(path1) == hash(path2)),
3946 "{:?} == {:?}, expected {:?}, got {} and {}",
3947 $path1, $path2, $eq, hash(path1), hash(path2));
3949 let starts_with = path1.starts_with(path2);
3950 assert!(starts_with == $starts_with,
3951 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3952 $starts_with, starts_with);
3954 let ends_with = path1.ends_with(path2);
3955 assert!(ends_with == $ends_with,
3956 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3957 $ends_with, ends_with);
3959 let relative_from = path1.strip_prefix(path2)
3960 .map(|p| p.to_str().unwrap())
3962 let exp: Option<&str> = $relative_from;
3963 assert!(relative_from == exp,
3964 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3965 $path1, $path2, exp, relative_from);
3973 relative_from: Some("")
3980 relative_from: Some("foo")
3994 relative_from: Some("")
4001 relative_from: Some("")
4004 tc!("foo/bar", "foo",
4008 relative_from: Some("bar")
4011 tc!("foo/bar/baz", "foo/bar",
4015 relative_from: Some("baz")
4018 tc!("foo/bar", "foo/bar/baz",
4025 tc!("./foo/bar/", ".",
4029 relative_from: Some("foo/bar")
4033 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4034 r"c:\src\rust\cargo-test\test",
4038 relative_from: Some("Cargo.toml")
4041 tc!(r"c:\foo", r"C:\foo",
4045 relative_from: Some("")
4051 fn test_components_debug() {
4052 let path = Path::new("/tmp");
4054 let mut components = path.components();
4056 let expected = "Components([RootDir, Normal(\"tmp\")])";
4057 let actual = format!("{:?}", components);
4058 assert_eq!(expected, actual);
4060 let _ = components.next().unwrap();
4061 let expected = "Components([Normal(\"tmp\")])";
4062 let actual = format!("{:?}", components);
4063 assert_eq!(expected, actual);
4065 let _ = components.next().unwrap();
4066 let expected = "Components([])";
4067 let actual = format!("{:?}", components);
4068 assert_eq!(expected, actual);
4073 fn test_iter_debug() {
4074 let path = Path::new("/tmp");
4076 let mut iter = path.iter();
4078 let expected = "Iter([\"/\", \"tmp\"])";
4079 let actual = format!("{:?}", iter);
4080 assert_eq!(expected, actual);
4082 let _ = iter.next().unwrap();
4083 let expected = "Iter([\"tmp\"])";
4084 let actual = format!("{:?}", iter);
4085 assert_eq!(expected, actual);
4087 let _ = iter.next().unwrap();
4088 let expected = "Iter([])";
4089 let actual = format!("{:?}", iter);
4090 assert_eq!(expected, actual);
4095 let orig: &str = "some/sort/of/path";
4096 let path = Path::new(orig);
4097 let boxed: Box<Path> = Box::from(path);
4098 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4099 assert_eq!(path, &*boxed);
4100 assert_eq!(&*boxed, &*path_buf);
4101 assert_eq!(&*path_buf, path);
4105 fn test_clone_into() {
4106 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4107 let path = Path::new("short");
4108 path.clone_into(&mut path_buf);
4109 assert_eq!(path, path_buf);
4110 assert!(path_buf.into_os_string().capacity() >= 15);
4114 fn display_format_flags() {
4115 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4116 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4121 let orig = "hello/world";
4122 let path = Path::new(orig);
4123 let rc: Rc<Path> = Rc::from(path);
4124 let arc: Arc<Path> = Arc::from(path);
4126 assert_eq!(&*rc, path);
4127 assert_eq!(&*arc, path);
4129 let rc2: Rc<Path> = Rc::from(path.to_owned());
4130 let arc2: Arc<Path> = Arc::from(path.to_owned());
4132 assert_eq!(&*rc2, path);
4133 assert_eq!(&*arc2, path);