1 // ignore-tidy-filelength
3 //! Cross-platform path manipulation.
5 //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
6 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
7 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
8 //! on strings according to the local platform's path syntax.
10 //! Paths can be parsed into [`Component`]s by iterating over the structure
11 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
12 //! correspond to the substrings between path separators (`/` or `\`). You can
13 //! reconstruct an equivalent path from components with the [`push`] method on
14 //! [`PathBuf`]; note that the paths may differ syntactically by the
15 //! normalization described in the documentation for the [`components`] method.
19 //! Path manipulation includes both parsing components from slices and building
22 //! To parse a path, you can create a [`Path`] slice from a [`str`]
23 //! slice and start asking questions:
26 //! use std::path::Path;
27 //! use std::ffi::OsStr;
29 //! let path = Path::new("/tmp/foo/bar.txt");
31 //! let parent = path.parent();
32 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
34 //! let file_stem = path.file_stem();
35 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
37 //! let extension = path.extension();
38 //! assert_eq!(extension, Some(OsStr::new("txt")));
41 //! To build or modify paths, use [`PathBuf`]:
44 //! use std::path::PathBuf;
46 //! // This way works...
47 //! let mut path = PathBuf::from("c:\\");
49 //! path.push("windows");
50 //! path.push("system32");
52 //! path.set_extension("dll");
54 //! // ... but push is best used if you don't know everything up
55 //! // front. If you do, this way is better:
56 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
59 //! [`Component`]: ../../std/path/enum.Component.html
60 //! [`components`]: ../../std/path/struct.Path.html#method.components
61 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
62 //! [`Path`]: ../../std/path/struct.Path.html
63 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
64 //! [`String`]: ../../std/string/struct.String.html
66 //! [`str`]: ../../std/primitive.str.html
67 //! [`OsString`]: ../../std/ffi/struct.OsString.html
68 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
70 #![stable(feature = "rust1", since = "1.0.0")]
72 use crate::borrow::{Borrow, Cow};
74 use crate::error::Error;
77 use crate::hash::{Hash, Hasher};
79 use crate::iter::{self, FusedIterator};
80 use crate::ops::{self, Deref};
82 use crate::str::FromStr;
85 use crate::ffi::{OsStr, OsString};
87 use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
89 ////////////////////////////////////////////////////////////////////////////////
91 ////////////////////////////////////////////////////////////////////////////////
93 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
94 // taking advantage of the fact that OsStr always encodes ASCII characters
95 // as-is. Eventually, this transmutation should be replaced by direct uses of
96 // OsStr APIs for parsing, but it will take a while for those to become
99 ////////////////////////////////////////////////////////////////////////////////
101 ////////////////////////////////////////////////////////////////////////////////
103 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
105 /// Windows uses a variety of path prefix styles, including references to drive
106 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
107 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
108 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
109 /// no normalization is performed.
114 /// use std::path::{Component, Path, Prefix};
115 /// use std::path::Prefix::*;
116 /// use std::ffi::OsStr;
118 /// fn get_path_prefix(s: &str) -> Prefix {
119 /// let path = Path::new(s);
120 /// match path.components().next().unwrap() {
121 /// Component::Prefix(prefix_component) => prefix_component.kind(),
126 /// # if cfg!(windows) {
127 /// assert_eq!(Verbatim(OsStr::new("pictures")),
128 /// get_path_prefix(r"\\?\pictures\kittens"));
129 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
130 /// get_path_prefix(r"\\?\UNC\server\share"));
131 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
132 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
133 /// get_path_prefix(r"\\.\BrainInterface"));
134 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
135 /// get_path_prefix(r"\\server\share"));
136 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
139 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub enum Prefix<'a> {
142 /// Verbatim prefix, e.g., `\\?\cat_pics`.
144 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
146 #[stable(feature = "rust1", since = "1.0.0")]
147 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
149 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
150 /// e.g., `\\?\UNC\server\share`.
152 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
153 /// server's hostname and a share name.
154 #[stable(feature = "rust1", since = "1.0.0")]
156 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
157 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
160 /// Verbatim disk prefix, e.g., `\\?\C:\`.
162 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
163 /// drive letter and `:\`.
164 #[stable(feature = "rust1", since = "1.0.0")]
165 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
167 /// Device namespace prefix, e.g., `\\.\COM42`.
169 /// Device namespace prefixes consist of `\\.\` immediately followed by the
171 #[stable(feature = "rust1", since = "1.0.0")]
172 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
174 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
175 /// `\\server\share`.
177 /// UNC prefixes consist of the server's hostname and a share name.
178 #[stable(feature = "rust1", since = "1.0.0")]
180 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
181 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
184 /// Prefix `C:` for the given disk drive.
185 #[stable(feature = "rust1", since = "1.0.0")]
186 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
189 impl<'a> Prefix<'a> {
191 fn len(&self) -> usize {
193 fn os_str_len(s: &OsStr) -> usize {
194 os_str_as_u8_slice(s).len()
197 Verbatim(x) => 4 + os_str_len(x),
198 VerbatimUNC(x, y) => {
199 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
201 VerbatimDisk(_) => 6,
202 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
203 DeviceNS(x) => 4 + os_str_len(x),
208 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
213 /// use std::path::Prefix::*;
214 /// use std::ffi::OsStr;
216 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
217 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
218 /// assert!(VerbatimDisk(b'C').is_verbatim());
219 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
220 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
221 /// assert!(!Disk(b'C').is_verbatim());
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn is_verbatim(&self) -> bool {
228 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
234 fn is_drive(&self) -> bool {
236 Prefix::Disk(_) => true,
242 fn has_implicit_root(&self) -> bool {
247 ////////////////////////////////////////////////////////////////////////////////
248 // Exposed parsing helpers
249 ////////////////////////////////////////////////////////////////////////////////
251 /// Determines whether the character is one of the permitted path
252 /// separators for the current platform.
259 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
260 /// assert!(!path::is_separator('❤'));
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn is_separator(c: char) -> bool {
264 c.is_ascii() && is_sep_byte(c as u8)
267 /// The primary separator of path components for the current platform.
269 /// For example, `/` on Unix and `\` on Windows.
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
273 ////////////////////////////////////////////////////////////////////////////////
275 ////////////////////////////////////////////////////////////////////////////////
277 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
278 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
279 // `iter` after having exhausted `prefix`.
280 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
282 I: Iterator<Item = Component<'a>> + Clone,
283 J: Iterator<Item = Component<'b>>,
286 let mut iter_next = iter.clone();
287 match (iter_next.next(), prefix.next()) {
288 (Some(ref x), Some(ref y)) if x == y => (),
289 (Some(_), Some(_)) => return None,
290 (Some(_), None) => return Some(iter),
291 (None, None) => return Some(iter),
292 (None, Some(_)) => return None,
298 // See note at the top of this module to understand why these are used:
299 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
300 unsafe { &*(s as *const OsStr as *const [u8]) }
302 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
303 &*(s as *const [u8] as *const OsStr)
306 // Detect scheme on Redox
307 fn has_redox_scheme(s: &[u8]) -> bool {
308 cfg!(target_os = "redox") && s.contains(&b':')
311 ////////////////////////////////////////////////////////////////////////////////
312 // Cross-platform, iterator-independent parsing
313 ////////////////////////////////////////////////////////////////////////////////
315 /// Says whether the first byte after the prefix is a separator.
316 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
317 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
318 !path.is_empty() && is_sep_byte(path[0])
321 // basic workhorse for splitting stem and extension
322 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
324 if os_str_as_u8_slice(file) == b".." {
325 return (Some(file), None);
328 // The unsafety here stems from converting between &OsStr and &[u8]
329 // and back. This is safe to do because (1) we only look at ASCII
330 // contents of the encoding and (2) new &OsStr values are produced
331 // only from ASCII-bounded slices of existing &OsStr values.
333 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
334 let after = iter.next();
335 let before = iter.next();
336 if before == Some(b"") {
339 (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s)))
344 ////////////////////////////////////////////////////////////////////////////////
345 // The core iterators
346 ////////////////////////////////////////////////////////////////////////////////
348 /// Component parsing works by a double-ended state machine; the cursors at the
349 /// front and back of the path each keep track of what parts of the path have
350 /// been consumed so far.
352 /// Going front to back, a path is made up of a prefix, a starting
353 /// directory component, and a body (of normal components)
354 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
357 StartDir = 1, // / or . or nothing
358 Body = 2, // foo/bar/baz
362 /// A structure wrapping a Windows path prefix as well as its unparsed string
365 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
366 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
367 /// returned by [`as_os_str`].
369 /// Instances of this `struct` can be obtained by matching against the
370 /// [`Prefix` variant] on [`Component`].
372 /// Does not occur on Unix.
377 /// # if cfg!(windows) {
378 /// use std::path::{Component, Path, Prefix};
379 /// use std::ffi::OsStr;
381 /// let path = Path::new(r"c:\you\later\");
382 /// match path.components().next().unwrap() {
383 /// Component::Prefix(prefix_component) => {
384 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
385 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
387 /// _ => unreachable!(),
392 /// [`as_os_str`]: #method.as_os_str
393 /// [`Component`]: enum.Component.html
394 /// [`kind`]: #method.kind
395 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
396 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
397 /// [`Prefix`]: enum.Prefix.html
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[derive(Copy, Clone, Eq, Debug)]
400 pub struct PrefixComponent<'a> {
401 /// The prefix as an unparsed `OsStr` slice.
404 /// The parsed prefix data.
408 impl<'a> PrefixComponent<'a> {
409 /// Returns the parsed prefix data.
411 /// See [`Prefix`]'s documentation for more information on the different
412 /// kinds of prefixes.
414 /// [`Prefix`]: enum.Prefix.html
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn kind(&self) -> Prefix<'a> {
420 /// Returns the raw [`OsStr`] slice for this prefix.
422 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn as_os_str(&self) -> &'a OsStr {
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
431 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
432 cmp::PartialEq::eq(&self.parsed, &other.parsed)
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
438 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
439 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl cmp::Ord for PrefixComponent<'_> {
445 fn cmp(&self, other: &Self) -> cmp::Ordering {
446 cmp::Ord::cmp(&self.parsed, &other.parsed)
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl Hash for PrefixComponent<'_> {
452 fn hash<H: Hasher>(&self, h: &mut H) {
457 /// A single component of a path.
459 /// A `Component` roughly corresponds to a substring between path separators
462 /// This `enum` is created by iterating over [`Components`], which in turn is
463 /// created by the [`components`][`Path::components`] method on [`Path`].
468 /// use std::path::{Component, Path};
470 /// let path = Path::new("/tmp/foo/bar.txt");
471 /// let components = path.components().collect::<Vec<_>>();
472 /// assert_eq!(&components, &[
473 /// Component::RootDir,
474 /// Component::Normal("tmp".as_ref()),
475 /// Component::Normal("foo".as_ref()),
476 /// Component::Normal("bar.txt".as_ref()),
480 /// [`Components`]: struct.Components.html
481 /// [`Path`]: struct.Path.html
482 /// [`Path::components`]: struct.Path.html#method.components
483 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub enum Component<'a> {
486 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
488 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
491 /// Does not occur on Unix.
493 /// [`Prefix`]: enum.Prefix.html
494 #[stable(feature = "rust1", since = "1.0.0")]
495 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
497 /// The root directory component, appears after any prefix and before anything else.
499 /// It represents a separator that designates that a path starts from root.
500 #[stable(feature = "rust1", since = "1.0.0")]
503 /// A reference to the current directory, i.e., `.`.
504 #[stable(feature = "rust1", since = "1.0.0")]
507 /// A reference to the parent directory, i.e., `..`.
508 #[stable(feature = "rust1", since = "1.0.0")]
511 /// A normal component, e.g., `a` and `b` in `a/b`.
513 /// This variant is the most common one, it represents references to files
515 #[stable(feature = "rust1", since = "1.0.0")]
516 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
519 impl<'a> Component<'a> {
520 /// Extracts the underlying [`OsStr`] slice.
525 /// use std::path::Path;
527 /// let path = Path::new("./tmp/foo/bar.txt");
528 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
529 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
532 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
533 #[stable(feature = "rust1", since = "1.0.0")]
534 pub fn as_os_str(self) -> &'a OsStr {
536 Component::Prefix(p) => p.as_os_str(),
537 Component::RootDir => OsStr::new(MAIN_SEP_STR),
538 Component::CurDir => OsStr::new("."),
539 Component::ParentDir => OsStr::new(".."),
540 Component::Normal(path) => path,
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl AsRef<OsStr> for Component<'_> {
547 fn as_ref(&self) -> &OsStr {
552 #[stable(feature = "path_component_asref", since = "1.25.0")]
553 impl AsRef<Path> for Component<'_> {
554 fn as_ref(&self) -> &Path {
555 self.as_os_str().as_ref()
559 /// An iterator over the [`Component`]s of a [`Path`].
561 /// This `struct` is created by the [`components`] method on [`Path`].
562 /// See its documentation for more.
567 /// use std::path::Path;
569 /// let path = Path::new("/tmp/foo/bar.txt");
571 /// for component in path.components() {
572 /// println!("{:?}", component);
576 /// [`Component`]: enum.Component.html
577 /// [`components`]: struct.Path.html#method.components
578 /// [`Path`]: struct.Path.html
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub struct Components<'a> {
582 // The path left to parse components from
585 // The prefix as it was originally parsed, if any
586 prefix: Option<Prefix<'a>>,
588 // true if path *physically* has a root separator; for most Windows
589 // prefixes, it may have a "logical" rootseparator for the purposes of
590 // normalization, e.g., \\server\share == \\server\share\.
591 has_physical_root: bool,
593 // The iterator is double-ended, and these two states keep track of what has
594 // been produced from either end
599 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
601 /// This `struct` is created by the [`iter`] method on [`Path`].
602 /// See its documentation for more.
604 /// [`Component`]: enum.Component.html
605 /// [`iter`]: struct.Path.html#method.iter
606 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
607 /// [`Path`]: struct.Path.html
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub struct Iter<'a> {
611 inner: Components<'a>,
614 #[stable(feature = "path_components_debug", since = "1.13.0")]
615 impl fmt::Debug for Components<'_> {
616 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617 struct DebugHelper<'a>(&'a Path);
619 impl fmt::Debug for DebugHelper<'_> {
620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 f.debug_list().entries(self.0.components()).finish()
625 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
629 impl<'a> Components<'a> {
630 // how long is the prefix, if any?
632 fn prefix_len(&self) -> usize {
633 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
637 fn prefix_verbatim(&self) -> bool {
638 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
641 /// how much of the prefix is left from the point of view of iteration?
643 fn prefix_remaining(&self) -> usize {
644 if self.front == State::Prefix { self.prefix_len() } else { 0 }
647 // Given the iteration so far, how much of the pre-State::Body path is left?
649 fn len_before_body(&self) -> usize {
650 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
651 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
652 self.prefix_remaining() + root + cur_dir
655 // is the iteration complete?
657 fn finished(&self) -> bool {
658 self.front == State::Done || self.back == State::Done || self.front > self.back
662 fn is_sep_byte(&self, b: u8) -> bool {
663 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
666 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
671 /// use std::path::Path;
673 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
674 /// components.next();
675 /// components.next();
677 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
679 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn as_path(&self) -> &'a Path {
681 let mut comps = self.clone();
682 if comps.front == State::Body {
685 if comps.back == State::Body {
688 unsafe { Path::from_u8_slice(comps.path) }
691 /// Is the *original* path rooted?
692 fn has_root(&self) -> bool {
693 if self.has_physical_root {
696 if let Some(p) = self.prefix {
697 if p.has_implicit_root() {
704 /// Should the normalized path include a leading . ?
705 fn include_cur_dir(&self) -> bool {
709 let mut iter = self.path[self.prefix_len()..].iter();
710 match (iter.next(), iter.next()) {
711 (Some(&b'.'), None) => true,
712 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
717 // parse a given byte sequence into the corresponding path component
718 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
720 b"." if self.prefix_verbatim() => Some(Component::CurDir),
721 b"." => None, // . components are normalized away, except at
722 // the beginning of a path, which is treated
723 // separately via `include_cur_dir`
724 b".." => Some(Component::ParentDir),
726 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
730 // parse a component from the left, saying how many bytes to consume to
731 // remove the component
732 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
733 debug_assert!(self.front == State::Body);
734 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
735 None => (0, self.path),
736 Some(i) => (1, &self.path[..i]),
738 (comp.len() + extra, self.parse_single_component(comp))
741 // parse a component from the right, saying how many bytes to consume to
742 // remove the component
743 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
744 debug_assert!(self.back == State::Body);
745 let start = self.len_before_body();
746 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
747 None => (0, &self.path[start..]),
748 Some(i) => (1, &self.path[start + i + 1..]),
750 (comp.len() + extra, self.parse_single_component(comp))
753 // trim away repeated separators (i.e., empty components) on the left
754 fn trim_left(&mut self) {
755 while !self.path.is_empty() {
756 let (size, comp) = self.parse_next_component();
760 self.path = &self.path[size..];
765 // trim away repeated separators (i.e., empty components) on the right
766 fn trim_right(&mut self) {
767 while self.path.len() > self.len_before_body() {
768 let (size, comp) = self.parse_next_component_back();
772 self.path = &self.path[..self.path.len() - size];
778 #[stable(feature = "rust1", since = "1.0.0")]
779 impl AsRef<Path> for Components<'_> {
780 fn as_ref(&self) -> &Path {
785 #[stable(feature = "rust1", since = "1.0.0")]
786 impl AsRef<OsStr> for Components<'_> {
787 fn as_ref(&self) -> &OsStr {
788 self.as_path().as_os_str()
792 #[stable(feature = "path_iter_debug", since = "1.13.0")]
793 impl fmt::Debug for Iter<'_> {
794 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
795 struct DebugHelper<'a>(&'a Path);
797 impl fmt::Debug for DebugHelper<'_> {
798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799 f.debug_list().entries(self.0.iter()).finish()
803 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
808 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
813 /// use std::path::Path;
815 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
819 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn as_path(&self) -> &'a Path {
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl AsRef<Path> for Iter<'_> {
829 fn as_ref(&self) -> &Path {
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl AsRef<OsStr> for Iter<'_> {
836 fn as_ref(&self) -> &OsStr {
837 self.as_path().as_os_str()
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<'a> Iterator for Iter<'a> {
843 type Item = &'a OsStr;
845 fn next(&mut self) -> Option<&'a OsStr> {
846 self.inner.next().map(Component::as_os_str)
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a> DoubleEndedIterator for Iter<'a> {
852 fn next_back(&mut self) -> Option<&'a OsStr> {
853 self.inner.next_back().map(Component::as_os_str)
857 #[stable(feature = "fused", since = "1.26.0")]
858 impl FusedIterator for Iter<'_> {}
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl<'a> Iterator for Components<'a> {
862 type Item = Component<'a>;
864 fn next(&mut self) -> Option<Component<'a>> {
865 while !self.finished() {
867 State::Prefix if self.prefix_len() > 0 => {
868 self.front = State::StartDir;
869 debug_assert!(self.prefix_len() <= self.path.len());
870 let raw = &self.path[..self.prefix_len()];
871 self.path = &self.path[self.prefix_len()..];
872 return Some(Component::Prefix(PrefixComponent {
873 raw: unsafe { u8_slice_as_os_str(raw) },
874 parsed: self.prefix.unwrap(),
878 self.front = State::StartDir;
881 self.front = State::Body;
882 if self.has_physical_root {
883 debug_assert!(!self.path.is_empty());
884 self.path = &self.path[1..];
885 return Some(Component::RootDir);
886 } else if let Some(p) = self.prefix {
887 if p.has_implicit_root() && !p.is_verbatim() {
888 return Some(Component::RootDir);
890 } else if self.include_cur_dir() {
891 debug_assert!(!self.path.is_empty());
892 self.path = &self.path[1..];
893 return Some(Component::CurDir);
896 State::Body if !self.path.is_empty() => {
897 let (size, comp) = self.parse_next_component();
898 self.path = &self.path[size..];
904 self.front = State::Done;
906 State::Done => unreachable!(),
913 #[stable(feature = "rust1", since = "1.0.0")]
914 impl<'a> DoubleEndedIterator for Components<'a> {
915 fn next_back(&mut self) -> Option<Component<'a>> {
916 while !self.finished() {
918 State::Body if self.path.len() > self.len_before_body() => {
919 let (size, comp) = self.parse_next_component_back();
920 self.path = &self.path[..self.path.len() - size];
926 self.back = State::StartDir;
929 self.back = State::Prefix;
930 if self.has_physical_root {
931 self.path = &self.path[..self.path.len() - 1];
932 return Some(Component::RootDir);
933 } else if let Some(p) = self.prefix {
934 if p.has_implicit_root() && !p.is_verbatim() {
935 return Some(Component::RootDir);
937 } else if self.include_cur_dir() {
938 self.path = &self.path[..self.path.len() - 1];
939 return Some(Component::CurDir);
942 State::Prefix if self.prefix_len() > 0 => {
943 self.back = State::Done;
944 return Some(Component::Prefix(PrefixComponent {
945 raw: unsafe { u8_slice_as_os_str(self.path) },
946 parsed: self.prefix.unwrap(),
950 self.back = State::Done;
953 State::Done => unreachable!(),
960 #[stable(feature = "fused", since = "1.26.0")]
961 impl FusedIterator for Components<'_> {}
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl<'a> cmp::PartialEq for Components<'a> {
965 fn eq(&self, other: &Components<'a>) -> bool {
966 Iterator::eq(self.clone(), other.clone())
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl cmp::Eq for Components<'_> {}
973 #[stable(feature = "rust1", since = "1.0.0")]
974 impl<'a> cmp::PartialOrd for Components<'a> {
975 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
976 Iterator::partial_cmp(self.clone(), other.clone())
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl cmp::Ord for Components<'_> {
982 fn cmp(&self, other: &Self) -> cmp::Ordering {
983 Iterator::cmp(self.clone(), other.clone())
987 /// An iterator over [`Path`] and its ancestors.
989 /// This `struct` is created by the [`ancestors`] method on [`Path`].
990 /// See its documentation for more.
995 /// use std::path::Path;
997 /// let path = Path::new("/foo/bar");
999 /// for ancestor in path.ancestors() {
1000 /// println!("{}", ancestor.display());
1004 /// [`ancestors`]: struct.Path.html#method.ancestors
1005 /// [`Path`]: struct.Path.html
1006 #[derive(Copy, Clone, Debug)]
1007 #[stable(feature = "path_ancestors", since = "1.28.0")]
1008 pub struct Ancestors<'a> {
1009 next: Option<&'a Path>,
1012 #[stable(feature = "path_ancestors", since = "1.28.0")]
1013 impl<'a> Iterator for Ancestors<'a> {
1014 type Item = &'a Path;
1016 fn next(&mut self) -> Option<Self::Item> {
1017 let next = self.next;
1018 self.next = next.and_then(Path::parent);
1023 #[stable(feature = "path_ancestors", since = "1.28.0")]
1024 impl FusedIterator for Ancestors<'_> {}
1026 ////////////////////////////////////////////////////////////////////////////////
1027 // Basic types and traits
1028 ////////////////////////////////////////////////////////////////////////////////
1030 /// An owned, mutable path (akin to [`String`]).
1032 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1033 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1034 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1036 /// [`String`]: ../string/struct.String.html
1037 /// [`Path`]: struct.Path.html
1038 /// [`push`]: struct.PathBuf.html#method.push
1039 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1040 /// [`Deref`]: ../ops/trait.Deref.html
1042 /// More details about the overall approach can be found in
1043 /// the [module documentation](index.html).
1047 /// You can use [`push`] to build up a `PathBuf` from
1051 /// use std::path::PathBuf;
1053 /// let mut path = PathBuf::new();
1055 /// path.push(r"C:\");
1056 /// path.push("windows");
1057 /// path.push("system32");
1059 /// path.set_extension("dll");
1062 /// However, [`push`] is best used for dynamic situations. This is a better way
1063 /// to do this when you know all of the components ahead of time:
1066 /// use std::path::PathBuf;
1068 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1071 /// We can still do better than this! Since these are all strings, we can use
1075 /// use std::path::PathBuf;
1077 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1080 /// Which method works best depends on what kind of situation you're in.
1082 #[stable(feature = "rust1", since = "1.0.0")]
1084 // `PathBuf::as_mut_vec` current implementation relies
1085 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1086 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1087 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1088 // not documented and must not be relied upon.
1089 pub struct PathBuf {
1094 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1095 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1098 /// Allocates an empty `PathBuf`.
1103 /// use std::path::PathBuf;
1105 /// let path = PathBuf::new();
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn new() -> PathBuf {
1109 PathBuf { inner: OsString::new() }
1112 /// Creates a new `PathBuf` with a given capacity used to create the
1113 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1118 /// #![feature(path_buf_capacity)]
1119 /// use std::path::PathBuf;
1121 /// let mut path = PathBuf::with_capacity(10);
1122 /// let capacity = path.capacity();
1124 /// // This push is done without reallocating
1125 /// path.push(r"C:\");
1127 /// assert_eq!(capacity, path.capacity());
1130 /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1131 /// [`OsString`]: ../ffi/struct.OsString.html
1132 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1133 pub fn with_capacity(capacity: usize) -> PathBuf {
1134 PathBuf { inner: OsString::with_capacity(capacity) }
1137 /// Coerces to a [`Path`] slice.
1139 /// [`Path`]: struct.Path.html
1144 /// use std::path::{Path, PathBuf};
1146 /// let p = PathBuf::from("/test");
1147 /// assert_eq!(Path::new("/test"), p.as_path());
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub fn as_path(&self) -> &Path {
1154 /// Extends `self` with `path`.
1156 /// If `path` is absolute, it replaces the current path.
1160 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1161 /// replaces everything except for the prefix (if any) of `self`.
1162 /// * if `path` has a prefix but no root, it replaces `self`.
1166 /// Pushing a relative path extends the existing path:
1169 /// use std::path::PathBuf;
1171 /// let mut path = PathBuf::from("/tmp");
1172 /// path.push("file.bk");
1173 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1176 /// Pushing an absolute path replaces the existing path:
1179 /// use std::path::PathBuf;
1181 /// let mut path = PathBuf::from("/tmp");
1182 /// path.push("/etc");
1183 /// assert_eq!(path, PathBuf::from("/etc"));
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1187 self._push(path.as_ref())
1190 fn _push(&mut self, path: &Path) {
1191 // in general, a separator is needed if the rightmost byte is not a separator
1192 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1194 // in the special case of `C:` on Windows, do *not* add a separator
1196 let comps = self.components();
1197 if comps.prefix_len() > 0
1198 && comps.prefix_len() == comps.path.len()
1199 && comps.prefix.unwrap().is_drive()
1205 // absolute `path` replaces `self`
1206 if path.is_absolute() || path.prefix().is_some() {
1207 self.as_mut_vec().truncate(0);
1209 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1210 } else if path.has_root() {
1211 let prefix_len = self.components().prefix_remaining();
1212 self.as_mut_vec().truncate(prefix_len);
1214 // `path` is a pure relative path
1215 } else if need_sep {
1216 self.inner.push(MAIN_SEP_STR);
1219 self.inner.push(path);
1222 /// Truncates `self` to [`self.parent`].
1224 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1225 /// Otherwise, returns `true`.
1227 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1228 /// [`self.parent`]: struct.PathBuf.html#method.parent
1233 /// use std::path::{Path, PathBuf};
1235 /// let mut p = PathBuf::from("/test/test.rs");
1238 /// assert_eq!(Path::new("/test"), p);
1240 /// assert_eq!(Path::new("/"), p);
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 pub fn pop(&mut self) -> bool {
1244 match self.parent().map(|p| p.as_u8_slice().len()) {
1246 self.as_mut_vec().truncate(len);
1253 /// Updates [`self.file_name`] to `file_name`.
1255 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1258 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1259 /// `file_name`. The new path will be a sibling of the original path.
1260 /// (That is, it will have the same parent.)
1262 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1263 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1264 /// [`pop`]: struct.PathBuf.html#method.pop
1269 /// use std::path::PathBuf;
1271 /// let mut buf = PathBuf::from("/");
1272 /// assert!(buf.file_name() == None);
1273 /// buf.set_file_name("bar");
1274 /// assert!(buf == PathBuf::from("/bar"));
1275 /// assert!(buf.file_name().is_some());
1276 /// buf.set_file_name("baz.txt");
1277 /// assert!(buf == PathBuf::from("/baz.txt"));
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1281 self._set_file_name(file_name.as_ref())
1284 fn _set_file_name(&mut self, file_name: &OsStr) {
1285 if self.file_name().is_some() {
1286 let popped = self.pop();
1287 debug_assert!(popped);
1289 self.push(file_name);
1292 /// Updates [`self.extension`] to `extension`.
1294 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1295 /// returns `true` and updates the extension otherwise.
1297 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1300 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1301 /// [`self.extension`]: struct.PathBuf.html#method.extension
1302 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1307 /// use std::path::{Path, PathBuf};
1309 /// let mut p = PathBuf::from("/feel/the");
1311 /// p.set_extension("force");
1312 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1314 /// p.set_extension("dark_side");
1315 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1319 self._set_extension(extension.as_ref())
1322 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1323 let file_stem = match self.file_stem() {
1324 None => return false,
1325 Some(f) => os_str_as_u8_slice(f),
1328 // truncate until right after the file stem
1329 let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize;
1330 let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize;
1331 let v = self.as_mut_vec();
1332 v.truncate(end_file_stem.wrapping_sub(start));
1334 // add the new extension, if any
1335 let new = os_str_as_u8_slice(extension);
1336 if !new.is_empty() {
1337 v.reserve_exact(new.len() + 1);
1339 v.extend_from_slice(new);
1345 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1347 /// [`OsString`]: ../ffi/struct.OsString.html
1352 /// use std::path::PathBuf;
1354 /// let p = PathBuf::from("/the/head");
1355 /// let os_str = p.into_os_string();
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub fn into_os_string(self) -> OsString {
1362 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1364 /// [`Box`]: ../../std/boxed/struct.Box.html
1365 /// [`Path`]: struct.Path.html
1366 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1367 pub fn into_boxed_path(self) -> Box<Path> {
1368 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1369 unsafe { Box::from_raw(rw) }
1372 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1374 /// [`capacity`]: ../ffi/struct.OsString.html#method.capacity
1375 /// [`OsString`]: ../ffi/struct.OsString.html
1376 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1377 pub fn capacity(&self) -> usize {
1378 self.inner.capacity()
1381 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1383 /// [`clear`]: ../ffi/struct.OsString.html#method.clear
1384 /// [`OsString`]: ../ffi/struct.OsString.html
1385 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1386 pub fn clear(&mut self) {
1390 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1392 /// [`reserve`]: ../ffi/struct.OsString.html#method.reserve
1393 /// [`OsString`]: ../ffi/struct.OsString.html
1394 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1395 pub fn reserve(&mut self, additional: usize) {
1396 self.inner.reserve(additional)
1399 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1401 /// [`reserve_exact`]: ../ffi/struct.OsString.html#method.reserve_exact
1402 /// [`OsString`]: ../ffi/struct.OsString.html
1403 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1404 pub fn reserve_exact(&mut self, additional: usize) {
1405 self.inner.reserve_exact(additional)
1408 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1410 /// [`shrink_to_fit`]: ../ffi/struct.OsString.html#method.shrink_to_fit
1411 /// [`OsString`]: ../ffi/struct.OsString.html
1412 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1413 pub fn shrink_to_fit(&mut self) {
1414 self.inner.shrink_to_fit()
1417 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1419 /// [`shrink_to`]: ../ffi/struct.OsString.html#method.shrink_to
1420 /// [`OsString`]: ../ffi/struct.OsString.html
1421 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1422 pub fn shrink_to(&mut self, min_capacity: usize) {
1423 self.inner.shrink_to(min_capacity)
1427 #[stable(feature = "box_from_path", since = "1.17.0")]
1428 impl From<&Path> for Box<Path> {
1429 fn from(path: &Path) -> Box<Path> {
1430 let boxed: Box<OsStr> = path.inner.into();
1431 let rw = Box::into_raw(boxed) as *mut Path;
1432 unsafe { Box::from_raw(rw) }
1436 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1437 impl From<Box<Path>> for PathBuf {
1438 /// Converts a `Box<Path>` into a `PathBuf`
1440 /// This conversion does not allocate or copy memory.
1441 fn from(boxed: Box<Path>) -> PathBuf {
1442 boxed.into_path_buf()
1446 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1447 impl From<PathBuf> for Box<Path> {
1448 /// Converts a `PathBuf` into a `Box<Path>`
1450 /// This conversion currently should not allocate memory,
1451 /// but this behavior is not guaranteed on all platforms or in all future versions.
1452 fn from(p: PathBuf) -> Box<Path> {
1457 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1458 impl Clone for Box<Path> {
1460 fn clone(&self) -> Self {
1461 self.to_path_buf().into_boxed_path()
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1467 fn from(s: &T) -> PathBuf {
1468 PathBuf::from(s.as_ref().to_os_string())
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 impl From<OsString> for PathBuf {
1474 /// Converts a `OsString` into a `PathBuf`
1476 /// This conversion does not allocate or copy memory.
1477 fn from(s: OsString) -> PathBuf {
1478 PathBuf { inner: s }
1482 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1483 impl From<PathBuf> for OsString {
1484 /// Converts a `PathBuf` into a `OsString`
1486 /// This conversion does not allocate or copy memory.
1487 fn from(path_buf: PathBuf) -> OsString {
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl From<String> for PathBuf {
1494 /// Converts a `String` into a `PathBuf`
1496 /// This conversion does not allocate or copy memory.
1497 fn from(s: String) -> PathBuf {
1498 PathBuf::from(OsString::from(s))
1502 #[stable(feature = "path_from_str", since = "1.32.0")]
1503 impl FromStr for PathBuf {
1504 type Err = core::convert::Infallible;
1506 fn from_str(s: &str) -> Result<Self, Self::Err> {
1507 Ok(PathBuf::from(s))
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1513 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1514 let mut buf = PathBuf::new();
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1522 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1523 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 impl fmt::Debug for PathBuf {
1529 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1530 fmt::Debug::fmt(&**self, formatter)
1534 #[stable(feature = "rust1", since = "1.0.0")]
1535 impl ops::Deref for PathBuf {
1538 fn deref(&self) -> &Path {
1539 Path::new(&self.inner)
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl Borrow<Path> for PathBuf {
1545 fn borrow(&self) -> &Path {
1550 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1551 impl Default for PathBuf {
1552 fn default() -> Self {
1557 #[stable(feature = "cow_from_path", since = "1.6.0")]
1558 impl<'a> From<&'a Path> for Cow<'a, Path> {
1560 fn from(s: &'a Path) -> Cow<'a, Path> {
1565 #[stable(feature = "cow_from_path", since = "1.6.0")]
1566 impl<'a> From<PathBuf> for Cow<'a, Path> {
1568 fn from(s: PathBuf) -> Cow<'a, Path> {
1573 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1574 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1576 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1577 Cow::Borrowed(p.as_path())
1581 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1582 impl<'a> From<Cow<'a, Path>> for PathBuf {
1584 fn from(p: Cow<'a, Path>) -> Self {
1589 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1590 impl From<PathBuf> for Arc<Path> {
1591 /// Converts a `PathBuf` into an `Arc` by moving the `PathBuf` data into a new `Arc` buffer.
1593 fn from(s: PathBuf) -> Arc<Path> {
1594 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1595 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1599 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1600 impl From<&Path> for Arc<Path> {
1601 /// Converts a `Path` into an `Arc` by copying the `Path` data into a new `Arc` buffer.
1603 fn from(s: &Path) -> Arc<Path> {
1604 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1605 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1609 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1610 impl From<PathBuf> for Rc<Path> {
1611 /// Converts a `PathBuf` into an `Rc` by moving the `PathBuf` data into a new `Rc` buffer.
1613 fn from(s: PathBuf) -> Rc<Path> {
1614 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1615 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1619 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1620 impl From<&Path> for Rc<Path> {
1621 /// Converts a `Path` into an `Rc` by copying the `Path` data into a new `Rc` buffer.
1623 fn from(s: &Path) -> Rc<Path> {
1624 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1625 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1629 #[stable(feature = "rust1", since = "1.0.0")]
1630 impl ToOwned for Path {
1631 type Owned = PathBuf;
1632 fn to_owned(&self) -> PathBuf {
1635 fn clone_into(&self, target: &mut PathBuf) {
1636 self.inner.clone_into(&mut target.inner);
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 impl cmp::PartialEq for PathBuf {
1642 fn eq(&self, other: &PathBuf) -> bool {
1643 self.components() == other.components()
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl Hash for PathBuf {
1649 fn hash<H: Hasher>(&self, h: &mut H) {
1650 self.as_path().hash(h)
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl cmp::Eq for PathBuf {}
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 impl cmp::PartialOrd for PathBuf {
1659 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1660 self.components().partial_cmp(other.components())
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl cmp::Ord for PathBuf {
1666 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1667 self.components().cmp(other.components())
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl AsRef<OsStr> for PathBuf {
1673 fn as_ref(&self) -> &OsStr {
1678 /// A slice of a path (akin to [`str`]).
1680 /// This type supports a number of operations for inspecting a path, including
1681 /// breaking the path into its components (separated by `/` on Unix and by either
1682 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1683 /// is absolute, and so on.
1685 /// This is an *unsized* type, meaning that it must always be used behind a
1686 /// pointer like `&` or [`Box`]. For an owned version of this type,
1687 /// see [`PathBuf`].
1689 /// [`str`]: ../primitive.str.html
1690 /// [`Box`]: ../boxed/struct.Box.html
1691 /// [`PathBuf`]: struct.PathBuf.html
1693 /// More details about the overall approach can be found in
1694 /// the [module documentation](index.html).
1699 /// use std::path::Path;
1700 /// use std::ffi::OsStr;
1702 /// // Note: this example does work on Windows
1703 /// let path = Path::new("./foo/bar.txt");
1705 /// let parent = path.parent();
1706 /// assert_eq!(parent, Some(Path::new("./foo")));
1708 /// let file_stem = path.file_stem();
1709 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1711 /// let extension = path.extension();
1712 /// assert_eq!(extension, Some(OsStr::new("txt")));
1714 #[stable(feature = "rust1", since = "1.0.0")]
1716 // `Path::new` current implementation relies
1717 // on `Path` being layout-compatible with `OsStr`.
1718 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1719 // Anyway, `Path` representation and layout are considered implementation detail, are
1720 // not documented and must not be relied upon.
1725 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1728 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1729 /// See its documentation for more.
1731 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1732 /// [`Path`]: struct.Path.html
1733 #[derive(Debug, Clone, PartialEq, Eq)]
1734 #[stable(since = "1.7.0", feature = "strip_prefix")]
1735 pub struct StripPrefixError(());
1738 // The following (private!) function allows construction of a path from a u8
1739 // slice, which is only safe when it is known to follow the OsStr encoding.
1740 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1741 Path::new(u8_slice_as_os_str(s))
1743 // The following (private!) function reveals the byte encoding used for OsStr.
1744 fn as_u8_slice(&self) -> &[u8] {
1745 os_str_as_u8_slice(&self.inner)
1748 /// Directly wraps a string slice as a `Path` slice.
1750 /// This is a cost-free conversion.
1755 /// use std::path::Path;
1757 /// Path::new("foo.txt");
1760 /// You can create `Path`s from `String`s, or even other `Path`s:
1763 /// use std::path::Path;
1765 /// let string = String::from("foo.txt");
1766 /// let from_string = Path::new(&string);
1767 /// let from_path = Path::new(&from_string);
1768 /// assert_eq!(from_string, from_path);
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1772 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1775 /// Yields the underlying [`OsStr`] slice.
1777 /// [`OsStr`]: ../ffi/struct.OsStr.html
1782 /// use std::path::Path;
1784 /// let os_str = Path::new("foo.txt").as_os_str();
1785 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 pub fn as_os_str(&self) -> &OsStr {
1792 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1794 /// This conversion may entail doing a check for UTF-8 validity.
1795 /// Note that validation is performed because non-UTF-8 strings are
1796 /// perfectly valid for some OS.
1798 /// [`&str`]: ../primitive.str.html
1803 /// use std::path::Path;
1805 /// let path = Path::new("foo.txt");
1806 /// assert_eq!(path.to_str(), Some("foo.txt"));
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 pub fn to_str(&self) -> Option<&str> {
1813 /// Converts a `Path` to a [`Cow<str>`].
1815 /// Any non-Unicode sequences are replaced with
1816 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1818 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1819 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1823 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1826 /// use std::path::Path;
1828 /// let path = Path::new("foo.txt");
1829 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1832 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1833 /// have returned `"fo�.txt"`.
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1836 self.inner.to_string_lossy()
1839 /// Converts a `Path` to an owned [`PathBuf`].
1841 /// [`PathBuf`]: struct.PathBuf.html
1846 /// use std::path::Path;
1848 /// let path_buf = Path::new("foo.txt").to_path_buf();
1849 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1851 #[rustc_conversion_suggestion]
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 pub fn to_path_buf(&self) -> PathBuf {
1854 PathBuf::from(self.inner.to_os_string())
1857 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1858 /// the current directory.
1860 /// * On Unix, a path is absolute if it starts with the root, so
1861 /// `is_absolute` and [`has_root`] are equivalent.
1863 /// * On Windows, a path is absolute if it has a prefix and starts with the
1864 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1869 /// use std::path::Path;
1871 /// assert!(!Path::new("foo.txt").is_absolute());
1874 /// [`has_root`]: #method.has_root
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 #[allow(deprecated)]
1877 pub fn is_absolute(&self) -> bool {
1878 if cfg!(target_os = "redox") {
1879 // FIXME: Allow Redox prefixes
1880 self.has_root() || has_redox_scheme(self.as_u8_slice())
1882 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1886 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1888 /// See [`is_absolute`]'s documentation for more details.
1893 /// use std::path::Path;
1895 /// assert!(Path::new("foo.txt").is_relative());
1898 /// [`is_absolute`]: #method.is_absolute
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 pub fn is_relative(&self) -> bool {
1904 fn prefix(&self) -> Option<Prefix<'_>> {
1905 self.components().prefix
1908 /// Returns `true` if the `Path` has a root.
1910 /// * On Unix, a path has a root if it begins with `/`.
1912 /// * On Windows, a path has a root if it:
1913 /// * has no prefix and begins with a separator, e.g., `\windows`
1914 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1915 /// * has any non-disk prefix, e.g., `\\server\share`
1920 /// use std::path::Path;
1922 /// assert!(Path::new("/etc/passwd").has_root());
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 pub fn has_root(&self) -> bool {
1926 self.components().has_root()
1929 /// Returns the `Path` without its final component, if there is one.
1931 /// Returns [`None`] if the path terminates in a root or prefix.
1933 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1938 /// use std::path::Path;
1940 /// let path = Path::new("/foo/bar");
1941 /// let parent = path.parent().unwrap();
1942 /// assert_eq!(parent, Path::new("/foo"));
1944 /// let grand_parent = parent.parent().unwrap();
1945 /// assert_eq!(grand_parent, Path::new("/"));
1946 /// assert_eq!(grand_parent.parent(), None);
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 pub fn parent(&self) -> Option<&Path> {
1950 let mut comps = self.components();
1951 let comp = comps.next_back();
1952 comp.and_then(|p| match p {
1953 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
1954 Some(comps.as_path())
1960 /// Produces an iterator over `Path` and its ancestors.
1962 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1963 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1964 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1965 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1971 /// use std::path::Path;
1973 /// let mut ancestors = Path::new("/foo/bar").ancestors();
1974 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1975 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1976 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1977 /// assert_eq!(ancestors.next(), None);
1980 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1981 /// [`parent`]: struct.Path.html#method.parent
1982 #[stable(feature = "path_ancestors", since = "1.28.0")]
1983 pub fn ancestors(&self) -> Ancestors<'_> {
1984 Ancestors { next: Some(&self) }
1987 /// Returns the final component of the `Path`, if there is one.
1989 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1990 /// is the directory name.
1992 /// Returns [`None`] if the path terminates in `..`.
1994 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1999 /// use std::path::Path;
2000 /// use std::ffi::OsStr;
2002 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2003 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2004 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2005 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2006 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2007 /// assert_eq!(None, Path::new("/").file_name());
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 pub fn file_name(&self) -> Option<&OsStr> {
2011 self.components().next_back().and_then(|p| match p {
2012 Component::Normal(p) => Some(p.as_ref()),
2017 /// Returns a path that, when joined onto `base`, yields `self`.
2021 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2022 /// returns `false`), returns [`Err`].
2024 /// [`starts_with`]: #method.starts_with
2025 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2030 /// use std::path::{Path, PathBuf};
2032 /// let path = Path::new("/test/haha/foo.txt");
2034 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2035 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2036 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2037 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2038 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2039 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2040 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2042 /// let prefix = PathBuf::from("/test/");
2043 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2045 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2046 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2050 self._strip_prefix(base.as_ref())
2053 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2054 iter_after(self.components(), base.components())
2055 .map(|c| c.as_path())
2056 .ok_or(StripPrefixError(()))
2059 /// Determines whether `base` is a prefix of `self`.
2061 /// Only considers whole path components to match.
2066 /// use std::path::Path;
2068 /// let path = Path::new("/etc/passwd");
2070 /// assert!(path.starts_with("/etc"));
2071 /// assert!(path.starts_with("/etc/"));
2072 /// assert!(path.starts_with("/etc/passwd"));
2073 /// assert!(path.starts_with("/etc/passwd/"));
2075 /// assert!(!path.starts_with("/e"));
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2079 self._starts_with(base.as_ref())
2082 fn _starts_with(&self, base: &Path) -> bool {
2083 iter_after(self.components(), base.components()).is_some()
2086 /// Determines whether `child` is a suffix of `self`.
2088 /// Only considers whole path components to match.
2093 /// use std::path::Path;
2095 /// let path = Path::new("/etc/passwd");
2097 /// assert!(path.ends_with("passwd"));
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2101 self._ends_with(child.as_ref())
2104 fn _ends_with(&self, child: &Path) -> bool {
2105 iter_after(self.components().rev(), child.components().rev()).is_some()
2108 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2110 /// [`self.file_name`]: struct.Path.html#method.file_name
2114 /// * [`None`], if there is no file name;
2115 /// * The entire file name if there is no embedded `.`;
2116 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2117 /// * Otherwise, the portion of the file name before the final `.`
2119 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2124 /// use std::path::Path;
2126 /// let path = Path::new("foo.rs");
2128 /// assert_eq!("foo", path.file_stem().unwrap());
2130 #[stable(feature = "rust1", since = "1.0.0")]
2131 pub fn file_stem(&self) -> Option<&OsStr> {
2132 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2135 /// Extracts the extension of [`self.file_name`], if possible.
2137 /// The extension is:
2139 /// * [`None`], if there is no file name;
2140 /// * [`None`], if there is no embedded `.`;
2141 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2142 /// * Otherwise, the portion of the file name after the final `.`
2144 /// [`self.file_name`]: struct.Path.html#method.file_name
2145 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2150 /// use std::path::Path;
2152 /// let path = Path::new("foo.rs");
2154 /// assert_eq!("rs", path.extension().unwrap());
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 pub fn extension(&self) -> Option<&OsStr> {
2158 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2161 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2163 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2165 /// [`PathBuf`]: struct.PathBuf.html
2166 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2171 /// use std::path::{Path, PathBuf};
2173 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2175 #[stable(feature = "rust1", since = "1.0.0")]
2177 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2178 self._join(path.as_ref())
2181 fn _join(&self, path: &Path) -> PathBuf {
2182 let mut buf = self.to_path_buf();
2187 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2189 /// See [`PathBuf::set_file_name`] for more details.
2191 /// [`PathBuf`]: struct.PathBuf.html
2192 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2197 /// use std::path::{Path, PathBuf};
2199 /// let path = Path::new("/tmp/foo.txt");
2200 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2202 /// let path = Path::new("/tmp");
2203 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2205 #[stable(feature = "rust1", since = "1.0.0")]
2206 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2207 self._with_file_name(file_name.as_ref())
2210 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2211 let mut buf = self.to_path_buf();
2212 buf.set_file_name(file_name);
2216 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2218 /// See [`PathBuf::set_extension`] for more details.
2220 /// [`PathBuf`]: struct.PathBuf.html
2221 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2226 /// use std::path::{Path, PathBuf};
2228 /// let path = Path::new("foo.rs");
2229 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2231 #[stable(feature = "rust1", since = "1.0.0")]
2232 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2233 self._with_extension(extension.as_ref())
2236 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2237 let mut buf = self.to_path_buf();
2238 buf.set_extension(extension);
2242 /// Produces an iterator over the [`Component`]s of the path.
2244 /// When parsing the path, there is a small amount of normalization:
2246 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2247 /// `a` and `b` as components.
2249 /// * Occurrences of `.` are normalized away, except if they are at the
2250 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2251 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2252 /// an additional [`CurDir`] component.
2254 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2256 /// Note that no other normalization takes place; in particular, `a/c`
2257 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2258 /// is a symbolic link (so its parent isn't `a`).
2263 /// use std::path::{Path, Component};
2264 /// use std::ffi::OsStr;
2266 /// let mut components = Path::new("/tmp/foo.txt").components();
2268 /// assert_eq!(components.next(), Some(Component::RootDir));
2269 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2270 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2271 /// assert_eq!(components.next(), None)
2274 /// [`Component`]: enum.Component.html
2275 /// [`CurDir`]: enum.Component.html#variant.CurDir
2276 #[stable(feature = "rust1", since = "1.0.0")]
2277 pub fn components(&self) -> Components<'_> {
2278 let prefix = parse_prefix(self.as_os_str());
2280 path: self.as_u8_slice(),
2282 has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
2283 || has_redox_scheme(self.as_u8_slice()),
2284 front: State::Prefix,
2289 /// Produces an iterator over the path's components viewed as [`OsStr`]
2292 /// For more information about the particulars of how the path is separated
2293 /// into components, see [`components`].
2295 /// [`components`]: #method.components
2296 /// [`OsStr`]: ../ffi/struct.OsStr.html
2301 /// use std::path::{self, Path};
2302 /// use std::ffi::OsStr;
2304 /// let mut it = Path::new("/tmp/foo.txt").iter();
2305 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2306 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2307 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2308 /// assert_eq!(it.next(), None)
2310 #[stable(feature = "rust1", since = "1.0.0")]
2311 pub fn iter(&self) -> Iter<'_> {
2312 Iter { inner: self.components() }
2315 /// Returns an object that implements [`Display`] for safely printing paths
2316 /// that may contain non-Unicode data.
2318 /// [`Display`]: ../fmt/trait.Display.html
2323 /// use std::path::Path;
2325 /// let path = Path::new("/tmp/foo.rs");
2327 /// println!("{}", path.display());
2329 #[stable(feature = "rust1", since = "1.0.0")]
2330 pub fn display(&self) -> Display<'_> {
2331 Display { path: self }
2334 /// Queries the file system to get information about a file, directory, etc.
2336 /// This function will traverse symbolic links to query information about the
2337 /// destination file.
2339 /// This is an alias to [`fs::metadata`].
2341 /// [`fs::metadata`]: ../fs/fn.metadata.html
2346 /// use std::path::Path;
2348 /// let path = Path::new("/Minas/tirith");
2349 /// let metadata = path.metadata().expect("metadata call failed");
2350 /// println!("{:?}", metadata.file_type());
2352 #[stable(feature = "path_ext", since = "1.5.0")]
2353 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2357 /// Queries the metadata about a file without following symlinks.
2359 /// This is an alias to [`fs::symlink_metadata`].
2361 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2366 /// use std::path::Path;
2368 /// let path = Path::new("/Minas/tirith");
2369 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2370 /// println!("{:?}", metadata.file_type());
2372 #[stable(feature = "path_ext", since = "1.5.0")]
2373 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2374 fs::symlink_metadata(self)
2377 /// Returns the canonical, absolute form of the path with all intermediate
2378 /// components normalized and symbolic links resolved.
2380 /// This is an alias to [`fs::canonicalize`].
2382 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2387 /// use std::path::{Path, PathBuf};
2389 /// let path = Path::new("/foo/test/../test/bar.rs");
2390 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2392 #[stable(feature = "path_ext", since = "1.5.0")]
2393 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2394 fs::canonicalize(self)
2397 /// Reads a symbolic link, returning the file that the link points to.
2399 /// This is an alias to [`fs::read_link`].
2401 /// [`fs::read_link`]: ../fs/fn.read_link.html
2406 /// use std::path::Path;
2408 /// let path = Path::new("/laputa/sky_castle.rs");
2409 /// let path_link = path.read_link().expect("read_link call failed");
2411 #[stable(feature = "path_ext", since = "1.5.0")]
2412 pub fn read_link(&self) -> io::Result<PathBuf> {
2416 /// Returns an iterator over the entries within a directory.
2418 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2419 /// errors may be encountered after an iterator is initially constructed.
2421 /// This is an alias to [`fs::read_dir`].
2423 /// [`io::Result`]: ../io/type.Result.html
2424 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2425 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2430 /// use std::path::Path;
2432 /// let path = Path::new("/laputa");
2433 /// for entry in path.read_dir().expect("read_dir call failed") {
2434 /// if let Ok(entry) = entry {
2435 /// println!("{:?}", entry.path());
2439 #[stable(feature = "path_ext", since = "1.5.0")]
2440 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2444 /// Returns `true` if the path points at an existing entity.
2446 /// This function will traverse symbolic links to query information about the
2447 /// destination file. In case of broken symbolic links this will return `false`.
2449 /// If you cannot access the directory containing the file, e.g., because of a
2450 /// permission error, this will return `false`.
2455 /// use std::path::Path;
2456 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2461 /// This is a convenience function that coerces errors to false. If you want to
2462 /// check errors, call [fs::metadata].
2464 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2465 #[stable(feature = "path_ext", since = "1.5.0")]
2466 pub fn exists(&self) -> bool {
2467 fs::metadata(self).is_ok()
2470 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2472 /// This function will traverse symbolic links to query information about the
2473 /// destination file. In case of broken symbolic links this will return `false`.
2475 /// If you cannot access the directory containing the file, e.g., because of a
2476 /// permission error, this will return `false`.
2481 /// use std::path::Path;
2482 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2483 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2488 /// This is a convenience function that coerces errors to false. If you want to
2489 /// check errors, call [fs::metadata] and handle its Result. Then call
2490 /// [fs::Metadata::is_file] if it was Ok.
2492 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2493 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2494 #[stable(feature = "path_ext", since = "1.5.0")]
2495 pub fn is_file(&self) -> bool {
2496 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2499 /// Returns `true` if the path exists on disk and is pointing at a directory.
2501 /// This function will traverse symbolic links to query information about the
2502 /// destination file. In case of broken symbolic links this will return `false`.
2504 /// If you cannot access the directory containing the file, e.g., because of a
2505 /// permission error, this will return `false`.
2510 /// use std::path::Path;
2511 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2512 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2517 /// This is a convenience function that coerces errors to false. If you want to
2518 /// check errors, call [fs::metadata] and handle its Result. Then call
2519 /// [fs::Metadata::is_dir] if it was Ok.
2521 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2522 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2523 #[stable(feature = "path_ext", since = "1.5.0")]
2524 pub fn is_dir(&self) -> bool {
2525 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2528 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2531 /// [`Box`]: ../../std/boxed/struct.Box.html
2532 /// [`PathBuf`]: struct.PathBuf.html
2533 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2534 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2535 let rw = Box::into_raw(self) as *mut OsStr;
2536 let inner = unsafe { Box::from_raw(rw) };
2537 PathBuf { inner: OsString::from(inner) }
2541 #[stable(feature = "rust1", since = "1.0.0")]
2542 impl AsRef<OsStr> for Path {
2543 fn as_ref(&self) -> &OsStr {
2548 #[stable(feature = "rust1", since = "1.0.0")]
2549 impl fmt::Debug for Path {
2550 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2551 fmt::Debug::fmt(&self.inner, formatter)
2555 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2557 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2558 /// [`Display`] trait in a way that mitigates that. It is created by the
2559 /// [`display`][`Path::display`] method on [`Path`].
2564 /// use std::path::Path;
2566 /// let path = Path::new("/tmp/foo.rs");
2568 /// println!("{}", path.display());
2571 /// [`Display`]: ../../std/fmt/trait.Display.html
2572 /// [`format!`]: ../../std/macro.format.html
2573 /// [`Path`]: struct.Path.html
2574 /// [`Path::display`]: struct.Path.html#method.display
2575 #[stable(feature = "rust1", since = "1.0.0")]
2576 pub struct Display<'a> {
2580 #[stable(feature = "rust1", since = "1.0.0")]
2581 impl fmt::Debug for Display<'_> {
2582 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2583 fmt::Debug::fmt(&self.path, f)
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 impl fmt::Display for Display<'_> {
2589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2590 self.path.inner.display(f)
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 impl cmp::PartialEq for Path {
2596 fn eq(&self, other: &Path) -> bool {
2597 self.components().eq(other.components())
2601 #[stable(feature = "rust1", since = "1.0.0")]
2602 impl Hash for Path {
2603 fn hash<H: Hasher>(&self, h: &mut H) {
2604 for component in self.components() {
2610 #[stable(feature = "rust1", since = "1.0.0")]
2611 impl cmp::Eq for Path {}
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 impl cmp::PartialOrd for Path {
2615 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2616 self.components().partial_cmp(other.components())
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 impl cmp::Ord for Path {
2622 fn cmp(&self, other: &Path) -> cmp::Ordering {
2623 self.components().cmp(other.components())
2627 #[stable(feature = "rust1", since = "1.0.0")]
2628 impl AsRef<Path> for Path {
2629 fn as_ref(&self) -> &Path {
2634 #[stable(feature = "rust1", since = "1.0.0")]
2635 impl AsRef<Path> for OsStr {
2636 fn as_ref(&self) -> &Path {
2641 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2642 impl AsRef<Path> for Cow<'_, OsStr> {
2643 fn as_ref(&self) -> &Path {
2648 #[stable(feature = "rust1", since = "1.0.0")]
2649 impl AsRef<Path> for OsString {
2650 fn as_ref(&self) -> &Path {
2655 #[stable(feature = "rust1", since = "1.0.0")]
2656 impl AsRef<Path> for str {
2657 fn as_ref(&self) -> &Path {
2662 #[stable(feature = "rust1", since = "1.0.0")]
2663 impl AsRef<Path> for String {
2664 fn as_ref(&self) -> &Path {
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 impl AsRef<Path> for PathBuf {
2671 fn as_ref(&self) -> &Path {
2676 #[stable(feature = "path_into_iter", since = "1.6.0")]
2677 impl<'a> IntoIterator for &'a PathBuf {
2678 type Item = &'a OsStr;
2679 type IntoIter = Iter<'a>;
2680 fn into_iter(self) -> Iter<'a> {
2685 #[stable(feature = "path_into_iter", since = "1.6.0")]
2686 impl<'a> IntoIterator for &'a Path {
2687 type Item = &'a OsStr;
2688 type IntoIter = Iter<'a>;
2689 fn into_iter(self) -> Iter<'a> {
2694 macro_rules! impl_cmp {
2695 ($lhs:ty, $rhs: ty) => {
2696 #[stable(feature = "partialeq_path", since = "1.6.0")]
2697 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2699 fn eq(&self, other: &$rhs) -> bool {
2700 <Path as PartialEq>::eq(self, other)
2704 #[stable(feature = "partialeq_path", since = "1.6.0")]
2705 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2707 fn eq(&self, other: &$lhs) -> bool {
2708 <Path as PartialEq>::eq(self, other)
2712 #[stable(feature = "cmp_path", since = "1.8.0")]
2713 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2715 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2716 <Path as PartialOrd>::partial_cmp(self, other)
2720 #[stable(feature = "cmp_path", since = "1.8.0")]
2721 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2723 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2724 <Path as PartialOrd>::partial_cmp(self, other)
2730 impl_cmp!(PathBuf, Path);
2731 impl_cmp!(PathBuf, &'a Path);
2732 impl_cmp!(Cow<'a, Path>, Path);
2733 impl_cmp!(Cow<'a, Path>, &'b Path);
2734 impl_cmp!(Cow<'a, Path>, PathBuf);
2736 macro_rules! impl_cmp_os_str {
2737 ($lhs:ty, $rhs: ty) => {
2738 #[stable(feature = "cmp_path", since = "1.8.0")]
2739 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2741 fn eq(&self, other: &$rhs) -> bool {
2742 <Path as PartialEq>::eq(self, other.as_ref())
2746 #[stable(feature = "cmp_path", since = "1.8.0")]
2747 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2749 fn eq(&self, other: &$lhs) -> bool {
2750 <Path as PartialEq>::eq(self.as_ref(), other)
2754 #[stable(feature = "cmp_path", since = "1.8.0")]
2755 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2757 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2758 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2762 #[stable(feature = "cmp_path", since = "1.8.0")]
2763 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2765 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2766 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2772 impl_cmp_os_str!(PathBuf, OsStr);
2773 impl_cmp_os_str!(PathBuf, &'a OsStr);
2774 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2775 impl_cmp_os_str!(PathBuf, OsString);
2776 impl_cmp_os_str!(Path, OsStr);
2777 impl_cmp_os_str!(Path, &'a OsStr);
2778 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2779 impl_cmp_os_str!(Path, OsString);
2780 impl_cmp_os_str!(&'a Path, OsStr);
2781 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2782 impl_cmp_os_str!(&'a Path, OsString);
2783 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2784 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2785 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2787 #[stable(since = "1.7.0", feature = "strip_prefix")]
2788 impl fmt::Display for StripPrefixError {
2789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2790 self.description().fmt(f)
2794 #[stable(since = "1.7.0", feature = "strip_prefix")]
2795 impl Error for StripPrefixError {
2796 fn description(&self) -> &str {
2806 use crate::sync::Arc;
2809 ($path:expr, iter: $iter:expr) => (
2811 let path = Path::new($path);
2813 // Forward iteration
2814 let comps = path.iter()
2815 .map(|p| p.to_string_lossy().into_owned())
2816 .collect::<Vec<String>>();
2817 let exp: &[&str] = &$iter;
2818 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2819 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2822 // Reverse iteration
2823 let comps = Path::new($path).iter().rev()
2824 .map(|p| p.to_string_lossy().into_owned())
2825 .collect::<Vec<String>>();
2826 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2827 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2832 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2834 let path = Path::new($path);
2836 let act_root = path.has_root();
2837 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2838 $has_root, act_root);
2840 let act_abs = path.is_absolute();
2841 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2842 $is_absolute, act_abs);
2846 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2848 let path = Path::new($path);
2850 let parent = path.parent().map(|p| p.to_str().unwrap());
2851 let exp_parent: Option<&str> = $parent;
2852 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2853 exp_parent, parent);
2855 let file = path.file_name().map(|p| p.to_str().unwrap());
2856 let exp_file: Option<&str> = $file;
2857 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2862 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2864 let path = Path::new($path);
2866 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2867 let exp_stem: Option<&str> = $file_stem;
2868 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2871 let ext = path.extension().map(|p| p.to_str().unwrap());
2872 let exp_ext: Option<&str> = $extension;
2873 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2878 ($path:expr, iter: $iter:expr,
2879 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2880 parent: $parent:expr, file_name: $file:expr,
2881 file_stem: $file_stem:expr, extension: $extension:expr) => (
2883 t!($path, iter: $iter);
2884 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2885 t!($path, parent: $parent, file_name: $file);
2886 t!($path, file_stem: $file_stem, extension: $extension);
2893 use crate::borrow::Cow;
2895 let static_path = Path::new("/home/foo");
2896 let static_cow_path: Cow<'static, Path> = static_path.into();
2897 let pathbuf = PathBuf::from("/home/foo");
2900 let path: &Path = &pathbuf;
2901 let borrowed_cow_path: Cow<'_, Path> = path.into();
2903 assert_eq!(static_cow_path, borrowed_cow_path);
2906 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2908 assert_eq!(static_cow_path, owned_cow_path);
2913 pub fn test_decompositions_unix() {
2929 file_name: Some("foo"),
2930 file_stem: Some("foo"),
2949 file_name: Some("foo"),
2950 file_stem: Some("foo"),
2959 file_name: Some("foo"),
2960 file_stem: Some("foo"),
2969 file_name: Some("foo"),
2970 file_stem: Some("foo"),
2975 iter: ["foo", "bar"],
2978 parent: Some("foo"),
2979 file_name: Some("bar"),
2980 file_stem: Some("bar"),
2985 iter: ["/", "foo", "bar"],
2988 parent: Some("/foo"),
2989 file_name: Some("bar"),
2990 file_stem: Some("bar"),
2999 file_name: Some("foo"),
3000 file_stem: Some("foo"),
3005 iter: ["/", "foo", "bar"],
3008 parent: Some("///foo"),
3009 file_name: Some("bar"),
3010 file_stem: Some("bar"),
3049 file_name: Some("foo"),
3050 file_stem: Some("foo"),
3055 iter: ["foo", ".."],
3058 parent: Some("foo"),
3069 file_name: Some("foo"),
3070 file_stem: Some("foo"),
3075 iter: ["foo", "bar"],
3078 parent: Some("foo"),
3079 file_name: Some("bar"),
3080 file_stem: Some("bar"),
3085 iter: ["foo", ".."],
3088 parent: Some("foo"),
3095 iter: ["foo", "..", "bar"],
3098 parent: Some("foo/.."),
3099 file_name: Some("bar"),
3100 file_stem: Some("bar"),
3109 file_name: Some("a"),
3110 file_stem: Some("a"),
3139 file_name: Some("b"),
3140 file_stem: Some("b"),
3149 file_name: Some("b"),
3150 file_stem: Some("b"),
3159 file_name: Some("b"),
3160 file_stem: Some("b"),
3165 iter: ["a", "b", "c"],
3168 parent: Some("a/b"),
3169 file_name: Some("c"),
3170 file_stem: Some("c"),
3179 file_name: Some(".foo"),
3180 file_stem: Some(".foo"),
3187 pub fn test_decompositions_windows() {
3203 file_name: Some("foo"),
3204 file_stem: Some("foo"),
3259 iter: ["\\", "foo"],
3263 file_name: Some("foo"),
3264 file_stem: Some("foo"),
3273 file_name: Some("foo"),
3274 file_stem: Some("foo"),
3279 iter: ["\\", "foo"],
3283 file_name: Some("foo"),
3284 file_stem: Some("foo"),
3289 iter: ["foo", "bar"],
3292 parent: Some("foo"),
3293 file_name: Some("bar"),
3294 file_stem: Some("bar"),
3299 iter: ["\\", "foo", "bar"],
3302 parent: Some("/foo"),
3303 file_name: Some("bar"),
3304 file_stem: Some("bar"),
3309 iter: ["\\", "foo"],
3313 file_name: Some("foo"),
3314 file_stem: Some("foo"),
3319 iter: ["\\", "foo", "bar"],
3322 parent: Some("///foo"),
3323 file_name: Some("bar"),
3324 file_stem: Some("bar"),
3363 file_name: Some("foo"),
3364 file_stem: Some("foo"),
3369 iter: ["foo", ".."],
3372 parent: Some("foo"),
3383 file_name: Some("foo"),
3384 file_stem: Some("foo"),
3389 iter: ["foo", "bar"],
3392 parent: Some("foo"),
3393 file_name: Some("bar"),
3394 file_stem: Some("bar"),
3399 iter: ["foo", ".."],
3402 parent: Some("foo"),
3409 iter: ["foo", "..", "bar"],
3412 parent: Some("foo/.."),
3413 file_name: Some("bar"),
3414 file_stem: Some("bar"),
3423 file_name: Some("a"),
3424 file_stem: Some("a"),
3453 file_name: Some("b"),
3454 file_stem: Some("b"),
3463 file_name: Some("b"),
3464 file_stem: Some("b"),
3473 file_name: Some("b"),
3474 file_stem: Some("b"),
3479 iter: ["a", "b", "c"],
3482 parent: Some("a/b"),
3483 file_name: Some("c"),
3484 file_stem: Some("c"),
3488 iter: ["a", "b", "c"],
3491 parent: Some("a\\b"),
3492 file_name: Some("c"),
3493 file_stem: Some("c"),
3502 file_name: Some("a"),
3503 file_stem: Some("a"),
3508 iter: ["c:", "\\", "foo.txt"],
3511 parent: Some("c:\\"),
3512 file_name: Some("foo.txt"),
3513 file_stem: Some("foo"),
3514 extension: Some("txt")
3517 t!("\\\\server\\share\\foo.txt",
3518 iter: ["\\\\server\\share", "\\", "foo.txt"],
3521 parent: Some("\\\\server\\share\\"),
3522 file_name: Some("foo.txt"),
3523 file_stem: Some("foo"),
3524 extension: Some("txt")
3527 t!("\\\\server\\share",
3528 iter: ["\\\\server\\share", "\\"],
3538 iter: ["\\", "server"],
3542 file_name: Some("server"),
3543 file_stem: Some("server"),
3547 t!("\\\\?\\bar\\foo.txt",
3548 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3551 parent: Some("\\\\?\\bar\\"),
3552 file_name: Some("foo.txt"),
3553 file_stem: Some("foo"),
3554 extension: Some("txt")
3558 iter: ["\\\\?\\bar"],
3577 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3578 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3581 parent: Some("\\\\?\\UNC\\server\\share\\"),
3582 file_name: Some("foo.txt"),
3583 file_stem: Some("foo"),
3584 extension: Some("txt")
3587 t!("\\\\?\\UNC\\server",
3588 iter: ["\\\\?\\UNC\\server"],
3598 iter: ["\\\\?\\UNC\\"],
3607 t!("\\\\?\\C:\\foo.txt",
3608 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3611 parent: Some("\\\\?\\C:\\"),
3612 file_name: Some("foo.txt"),
3613 file_stem: Some("foo"),
3614 extension: Some("txt")
3618 iter: ["\\\\?\\C:", "\\"],
3628 iter: ["\\\\?\\C:"],
3637 t!("\\\\?\\foo/bar",
3638 iter: ["\\\\?\\foo/bar"],
3648 iter: ["\\\\?\\C:/foo"],
3657 t!("\\\\.\\foo\\bar",
3658 iter: ["\\\\.\\foo", "\\", "bar"],
3661 parent: Some("\\\\.\\foo\\"),
3662 file_name: Some("bar"),
3663 file_stem: Some("bar"),
3668 iter: ["\\\\.\\foo", "\\"],
3677 t!("\\\\.\\foo/bar",
3678 iter: ["\\\\.\\foo/bar", "\\"],
3687 t!("\\\\.\\foo\\bar/baz",
3688 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3691 parent: Some("\\\\.\\foo\\bar"),
3692 file_name: Some("baz"),
3693 file_stem: Some("baz"),
3698 iter: ["\\\\.\\", "\\"],
3708 iter: ["\\\\?\\a", "\\", "b"],
3711 parent: Some("\\\\?\\a\\"),
3712 file_name: Some("b"),
3713 file_stem: Some("b"),
3719 pub fn test_stem_ext() {
3721 file_stem: Some("foo"),
3726 file_stem: Some("foo"),
3731 file_stem: Some(".foo"),
3736 file_stem: Some("foo"),
3737 extension: Some("txt")
3741 file_stem: Some("foo.bar"),
3742 extension: Some("txt")
3746 file_stem: Some("foo.bar"),
3750 t!(".", file_stem: None, extension: None);
3752 t!("..", file_stem: None, extension: None);
3754 t!("", file_stem: None, extension: None);
3758 pub fn test_push() {
3760 ($path:expr, $push:expr, $expected:expr) => ( {
3761 let mut actual = PathBuf::from($path);
3763 assert!(actual.to_str() == Some($expected),
3764 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3765 $push, $path, $expected, actual.to_str().unwrap());
3769 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3770 tp!("", "foo", "foo");
3771 tp!("foo", "bar", "foo/bar");
3772 tp!("foo/", "bar", "foo/bar");
3773 tp!("foo//", "bar", "foo//bar");
3774 tp!("foo/.", "bar", "foo/./bar");
3775 tp!("foo./.", "bar", "foo././bar");
3776 tp!("foo", "", "foo/");
3777 tp!("foo", ".", "foo/.");
3778 tp!("foo", "..", "foo/..");
3779 tp!("foo", "/", "/");
3780 tp!("/foo/bar", "/", "/");
3781 tp!("/foo/bar", "/baz", "/baz");
3782 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3784 tp!("", "foo", "foo");
3785 tp!("foo", "bar", r"foo\bar");
3786 tp!("foo/", "bar", r"foo/bar");
3787 tp!(r"foo\", "bar", r"foo\bar");
3788 tp!("foo//", "bar", r"foo//bar");
3789 tp!(r"foo\\", "bar", r"foo\\bar");
3790 tp!("foo/.", "bar", r"foo/.\bar");
3791 tp!("foo./.", "bar", r"foo./.\bar");
3792 tp!(r"foo\.", "bar", r"foo\.\bar");
3793 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3794 tp!("foo", "", "foo\\");
3795 tp!("foo", ".", r"foo\.");
3796 tp!("foo", "..", r"foo\..");
3797 tp!("foo", "/", "/");
3798 tp!("foo", r"\", r"\");
3799 tp!("/foo/bar", "/", "/");
3800 tp!(r"\foo\bar", r"\", r"\");
3801 tp!("/foo/bar", "/baz", "/baz");
3802 tp!("/foo/bar", r"\baz", r"\baz");
3803 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3804 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3806 tp!("c:\\", "windows", "c:\\windows");
3807 tp!("c:", "windows", "c:windows");
3809 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3810 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3811 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3812 tp!("a\\b", "\\c\\d", "\\c\\d");
3813 tp!("a\\b", ".", "a\\b\\.");
3814 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3815 tp!("a\\b", "C:a.txt", "C:a.txt");
3816 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3817 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3818 tp!("C:\\a\\b\\c", "C:d", "C:d");
3819 tp!("C:a\\b\\c", "C:d", "C:d");
3820 tp!("C:", r"a\b\c", r"C:a\b\c");
3821 tp!("C:", r"..\a", r"C:..\a");
3822 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
3823 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3824 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3825 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3826 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3827 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3828 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
3829 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3830 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3832 // Note: modified from old path API
3833 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3835 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
3836 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3837 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3838 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3839 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3841 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3848 ($path:expr, $expected:expr, $output:expr) => ( {
3849 let mut actual = PathBuf::from($path);
3850 let output = actual.pop();
3851 assert!(actual.to_str() == Some($expected) && output == $output,
3852 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3853 $path, $expected, $output,
3854 actual.to_str().unwrap(), output);
3859 tp!("/", "/", false);
3860 tp!("foo", "", true);
3862 tp!("/foo", "/", true);
3863 tp!("/foo/bar", "/foo", true);
3864 tp!("foo/bar", "foo", true);
3865 tp!("foo/.", "", true);
3866 tp!("foo//bar", "foo", true);
3869 tp!("a\\b\\c", "a\\b", true);
3870 tp!("\\a", "\\", true);
3871 tp!("\\", "\\", false);
3873 tp!("C:\\a\\b", "C:\\a", true);
3874 tp!("C:\\a", "C:\\", true);
3875 tp!("C:\\", "C:\\", false);
3876 tp!("C:a\\b", "C:a", true);
3877 tp!("C:a", "C:", true);
3878 tp!("C:", "C:", false);
3879 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3880 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3881 tp!("\\\\server\\share", "\\\\server\\share", false);
3882 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3883 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3884 tp!("\\\\?\\a", "\\\\?\\a", false);
3885 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3886 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3887 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3888 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
3889 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
3890 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
3891 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3892 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3893 tp!("\\\\.\\a", "\\\\.\\a", false);
3895 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3900 pub fn test_set_file_name() {
3902 ($path:expr, $file:expr, $expected:expr) => ( {
3903 let mut p = PathBuf::from($path);
3904 p.set_file_name($file);
3905 assert!(p.to_str() == Some($expected),
3906 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3907 $path, $file, $expected,
3908 p.to_str().unwrap());
3912 tfn!("foo", "foo", "foo");
3913 tfn!("foo", "bar", "bar");
3914 tfn!("foo", "", "");
3915 tfn!("", "foo", "foo");
3916 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3917 tfn!(".", "foo", "./foo");
3918 tfn!("foo/", "bar", "bar");
3919 tfn!("foo/.", "bar", "bar");
3920 tfn!("..", "foo", "../foo");
3921 tfn!("foo/..", "bar", "foo/../bar");
3922 tfn!("/", "foo", "/foo");
3924 tfn!(".", "foo", r".\foo");
3925 tfn!(r"foo\", "bar", r"bar");
3926 tfn!(r"foo\.", "bar", r"bar");
3927 tfn!("..", "foo", r"..\foo");
3928 tfn!(r"foo\..", "bar", r"foo\..\bar");
3929 tfn!(r"\", "foo", r"\foo");
3934 pub fn test_set_extension() {
3936 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3937 let mut p = PathBuf::from($path);
3938 let output = p.set_extension($ext);
3939 assert!(p.to_str() == Some($expected) && output == $output,
3940 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3941 $path, $ext, $expected, $output,
3942 p.to_str().unwrap(), output);
3946 tfe!("foo", "txt", "foo.txt", true);
3947 tfe!("foo.bar", "txt", "foo.txt", true);
3948 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3949 tfe!(".test", "txt", ".test.txt", true);
3950 tfe!("foo.txt", "", "foo", true);
3951 tfe!("foo", "", "foo", true);
3952 tfe!("", "foo", "", false);
3953 tfe!(".", "foo", ".", false);
3954 tfe!("foo/", "bar", "foo.bar", true);
3955 tfe!("foo/.", "bar", "foo.bar", true);
3956 tfe!("..", "foo", "..", false);
3957 tfe!("foo/..", "bar", "foo/..", false);
3958 tfe!("/", "foo", "/", false);
3962 fn test_eq_receivers() {
3963 use crate::borrow::Cow;
3965 let borrowed: &Path = Path::new("foo/bar");
3966 let mut owned: PathBuf = PathBuf::new();
3969 let borrowed_cow: Cow<'_, Path> = borrowed.into();
3970 let owned_cow: Cow<'_, Path> = owned.clone().into();
3973 ($($current:expr),+) => {
3975 assert_eq!($current, borrowed);
3976 assert_eq!($current, owned);
3977 assert_eq!($current, borrowed_cow);
3978 assert_eq!($current, owned_cow);
3983 t!(borrowed, owned, borrowed_cow, owned_cow);
3987 pub fn test_compare() {
3988 use crate::collections::hash_map::DefaultHasher;
3989 use crate::hash::{Hash, Hasher};
3991 fn hash<T: Hash>(t: T) -> u64 {
3992 let mut s = DefaultHasher::new();
3998 ($path1:expr, $path2:expr, eq: $eq:expr,
3999 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4000 relative_from: $relative_from:expr) => ({
4001 let path1 = Path::new($path1);
4002 let path2 = Path::new($path2);
4004 let eq = path1 == path2;
4005 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4006 $path1, $path2, $eq, eq);
4007 assert!($eq == (hash(path1) == hash(path2)),
4008 "{:?} == {:?}, expected {:?}, got {} and {}",
4009 $path1, $path2, $eq, hash(path1), hash(path2));
4011 let starts_with = path1.starts_with(path2);
4012 assert!(starts_with == $starts_with,
4013 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4014 $starts_with, starts_with);
4016 let ends_with = path1.ends_with(path2);
4017 assert!(ends_with == $ends_with,
4018 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4019 $ends_with, ends_with);
4021 let relative_from = path1.strip_prefix(path2)
4022 .map(|p| p.to_str().unwrap())
4024 let exp: Option<&str> = $relative_from;
4025 assert!(relative_from == exp,
4026 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4027 $path1, $path2, exp, relative_from);
4035 relative_from: Some("")
4042 relative_from: Some("foo")
4056 relative_from: Some("")
4063 relative_from: Some("")
4066 tc!("foo/bar", "foo",
4070 relative_from: Some("bar")
4073 tc!("foo/bar/baz", "foo/bar",
4077 relative_from: Some("baz")
4080 tc!("foo/bar", "foo/bar/baz",
4087 tc!("./foo/bar/", ".",
4091 relative_from: Some("foo/bar")
4095 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4096 r"c:\src\rust\cargo-test\test",
4100 relative_from: Some("Cargo.toml")
4103 tc!(r"c:\foo", r"C:\foo",
4107 relative_from: Some("")
4113 fn test_components_debug() {
4114 let path = Path::new("/tmp");
4116 let mut components = path.components();
4118 let expected = "Components([RootDir, Normal(\"tmp\")])";
4119 let actual = format!("{:?}", components);
4120 assert_eq!(expected, actual);
4122 let _ = components.next().unwrap();
4123 let expected = "Components([Normal(\"tmp\")])";
4124 let actual = format!("{:?}", components);
4125 assert_eq!(expected, actual);
4127 let _ = components.next().unwrap();
4128 let expected = "Components([])";
4129 let actual = format!("{:?}", components);
4130 assert_eq!(expected, actual);
4135 fn test_iter_debug() {
4136 let path = Path::new("/tmp");
4138 let mut iter = path.iter();
4140 let expected = "Iter([\"/\", \"tmp\"])";
4141 let actual = format!("{:?}", iter);
4142 assert_eq!(expected, actual);
4144 let _ = iter.next().unwrap();
4145 let expected = "Iter([\"tmp\"])";
4146 let actual = format!("{:?}", iter);
4147 assert_eq!(expected, actual);
4149 let _ = iter.next().unwrap();
4150 let expected = "Iter([])";
4151 let actual = format!("{:?}", iter);
4152 assert_eq!(expected, actual);
4157 let orig: &str = "some/sort/of/path";
4158 let path = Path::new(orig);
4159 let boxed: Box<Path> = Box::from(path);
4160 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4161 assert_eq!(path, &*boxed);
4162 assert_eq!(&*boxed, &*path_buf);
4163 assert_eq!(&*path_buf, path);
4167 fn test_clone_into() {
4168 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4169 let path = Path::new("short");
4170 path.clone_into(&mut path_buf);
4171 assert_eq!(path, path_buf);
4172 assert!(path_buf.into_os_string().capacity() >= 15);
4176 fn display_format_flags() {
4177 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4178 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4183 let orig = "hello/world";
4184 let path = Path::new(orig);
4185 let rc: Rc<Path> = Rc::from(path);
4186 let arc: Arc<Path> = Arc::from(path);
4188 assert_eq!(&*rc, path);
4189 assert_eq!(&*arc, path);
4191 let rc2: Rc<Path> = Rc::from(path.to_owned());
4192 let arc2: Arc<Path> = Arc::from(path.to_owned());
4194 assert_eq!(&*rc2, path);
4195 assert_eq!(&*arc2, path);