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, MAIN_SEP_STR, parse_prefix};
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) => {
200 if os_str_len(y) > 0 {
206 VerbatimDisk(_) => 6,
209 if os_str_len(y) > 0 {
215 DeviceNS(x) => 4 + os_str_len(x),
221 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
226 /// use std::path::Prefix::*;
227 /// use std::ffi::OsStr;
229 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
230 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
231 /// assert!(VerbatimDisk(b'C').is_verbatim());
232 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
233 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
234 /// assert!(!Disk(b'C').is_verbatim());
237 #[stable(feature = "rust1", since = "1.0.0")]
238 pub fn is_verbatim(&self) -> bool {
241 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
247 fn is_drive(&self) -> bool {
249 Prefix::Disk(_) => true,
255 fn has_implicit_root(&self) -> bool {
260 ////////////////////////////////////////////////////////////////////////////////
261 // Exposed parsing helpers
262 ////////////////////////////////////////////////////////////////////////////////
264 /// Determines whether the character is one of the permitted path
265 /// separators for the current platform.
272 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
273 /// assert!(!path::is_separator('❤'));
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn is_separator(c: char) -> bool {
277 c.is_ascii() && is_sep_byte(c as u8)
280 /// The primary separator of path components for the current platform.
282 /// For example, `/` on Unix and `\` on Windows.
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
286 ////////////////////////////////////////////////////////////////////////////////
288 ////////////////////////////////////////////////////////////////////////////////
290 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
291 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
292 // `iter` after having exhausted `prefix`.
293 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
294 where I: Iterator<Item = Component<'a>> + Clone,
295 J: Iterator<Item = Component<'b>>,
298 let mut iter_next = iter.clone();
299 match (iter_next.next(), prefix.next()) {
300 (Some(ref x), Some(ref y)) if x == y => (),
301 (Some(_), Some(_)) => return None,
302 (Some(_), None) => return Some(iter),
303 (None, None) => return Some(iter),
304 (None, Some(_)) => return None,
310 // See note at the top of this module to understand why these are used:
311 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
312 unsafe { &*(s as *const OsStr as *const [u8]) }
314 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
315 &*(s as *const [u8] as *const OsStr)
318 // Detect scheme on Redox
319 fn has_redox_scheme(s: &[u8]) -> bool {
320 cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
323 ////////////////////////////////////////////////////////////////////////////////
324 // Cross-platform, iterator-independent parsing
325 ////////////////////////////////////////////////////////////////////////////////
327 /// Says whether the first byte after the prefix is a separator.
328 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
329 let path = if let Some(p) = prefix {
334 !path.is_empty() && is_sep_byte(path[0])
337 // basic workhorse for splitting stem and extension
338 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
340 if os_str_as_u8_slice(file) == b".." {
341 return (Some(file), None);
344 // The unsafety here stems from converting between &OsStr and &[u8]
345 // and back. This is safe to do because (1) we only look at ASCII
346 // contents of the encoding and (2) new &OsStr values are produced
347 // only from ASCII-bounded slices of existing &OsStr values.
349 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
350 let after = iter.next();
351 let before = iter.next();
352 if before == Some(b"") {
355 (before.map(|s| u8_slice_as_os_str(s)),
356 after.map(|s| u8_slice_as_os_str(s)))
361 ////////////////////////////////////////////////////////////////////////////////
362 // The core iterators
363 ////////////////////////////////////////////////////////////////////////////////
365 /// Component parsing works by a double-ended state machine; the cursors at the
366 /// front and back of the path each keep track of what parts of the path have
367 /// been consumed so far.
369 /// Going front to back, a path is made up of a prefix, a starting
370 /// directory component, and a body (of normal components)
371 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
374 StartDir = 1, // / or . or nothing
375 Body = 2, // foo/bar/baz
379 /// A structure wrapping a Windows path prefix as well as its unparsed string
382 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
383 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
384 /// returned by [`as_os_str`].
386 /// Instances of this `struct` can be obtained by matching against the
387 /// [`Prefix` variant] on [`Component`].
389 /// Does not occur on Unix.
394 /// # if cfg!(windows) {
395 /// use std::path::{Component, Path, Prefix};
396 /// use std::ffi::OsStr;
398 /// let path = Path::new(r"c:\you\later\");
399 /// match path.components().next().unwrap() {
400 /// Component::Prefix(prefix_component) => {
401 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
402 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
404 /// _ => unreachable!(),
409 /// [`as_os_str`]: #method.as_os_str
410 /// [`Component`]: enum.Component.html
411 /// [`kind`]: #method.kind
412 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
413 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
414 /// [`Prefix`]: enum.Prefix.html
415 #[stable(feature = "rust1", since = "1.0.0")]
416 #[derive(Copy, Clone, Eq, Debug)]
417 pub struct PrefixComponent<'a> {
418 /// The prefix as an unparsed `OsStr` slice.
421 /// The parsed prefix data.
425 impl<'a> PrefixComponent<'a> {
426 /// Returns the parsed prefix data.
428 /// See [`Prefix`]'s documentation for more information on the different
429 /// kinds of prefixes.
431 /// [`Prefix`]: enum.Prefix.html
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn kind(&self) -> Prefix<'a> {
437 /// Returns the raw [`OsStr`] slice for this prefix.
439 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn as_os_str(&self) -> &'a OsStr {
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
448 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
449 cmp::PartialEq::eq(&self.parsed, &other.parsed)
453 #[stable(feature = "rust1", since = "1.0.0")]
454 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
455 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
456 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl cmp::Ord for PrefixComponent<'_> {
462 fn cmp(&self, other: &Self) -> cmp::Ordering {
463 cmp::Ord::cmp(&self.parsed, &other.parsed)
467 #[stable(feature = "rust1", since = "1.0.0")]
468 impl Hash for PrefixComponent<'_> {
469 fn hash<H: Hasher>(&self, h: &mut H) {
474 /// A single component of a path.
476 /// A `Component` roughly corresponds to a substring between path separators
479 /// This `enum` is created by iterating over [`Components`], which in turn is
480 /// created by the [`components`][`Path::components`] method on [`Path`].
485 /// use std::path::{Component, Path};
487 /// let path = Path::new("/tmp/foo/bar.txt");
488 /// let components = path.components().collect::<Vec<_>>();
489 /// assert_eq!(&components, &[
490 /// Component::RootDir,
491 /// Component::Normal("tmp".as_ref()),
492 /// Component::Normal("foo".as_ref()),
493 /// Component::Normal("bar.txt".as_ref()),
497 /// [`Components`]: struct.Components.html
498 /// [`Path`]: struct.Path.html
499 /// [`Path::components`]: struct.Path.html#method.components
500 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub enum Component<'a> {
503 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
505 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
508 /// Does not occur on Unix.
510 /// [`Prefix`]: enum.Prefix.html
511 #[stable(feature = "rust1", since = "1.0.0")]
513 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
516 /// The root directory component, appears after any prefix and before anything else.
518 /// It represents a separator that designates that a path starts from root.
519 #[stable(feature = "rust1", since = "1.0.0")]
522 /// A reference to the current directory, i.e., `.`.
523 #[stable(feature = "rust1", since = "1.0.0")]
526 /// A reference to the parent directory, i.e., `..`.
527 #[stable(feature = "rust1", since = "1.0.0")]
530 /// A normal component, e.g., `a` and `b` in `a/b`.
532 /// This variant is the most common one, it represents references to files
534 #[stable(feature = "rust1", since = "1.0.0")]
535 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
538 impl<'a> Component<'a> {
539 /// Extracts the underlying [`OsStr`] slice.
544 /// use std::path::Path;
546 /// let path = Path::new("./tmp/foo/bar.txt");
547 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
548 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
551 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn as_os_str(self) -> &'a OsStr {
555 Component::Prefix(p) => p.as_os_str(),
556 Component::RootDir => OsStr::new(MAIN_SEP_STR),
557 Component::CurDir => OsStr::new("."),
558 Component::ParentDir => OsStr::new(".."),
559 Component::Normal(path) => path,
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl AsRef<OsStr> for Component<'_> {
566 fn as_ref(&self) -> &OsStr {
571 #[stable(feature = "path_component_asref", since = "1.25.0")]
572 impl AsRef<Path> for Component<'_> {
573 fn as_ref(&self) -> &Path {
574 self.as_os_str().as_ref()
578 /// An iterator over the [`Component`]s of a [`Path`].
580 /// This `struct` is created by the [`components`] method on [`Path`].
581 /// See its documentation for more.
586 /// use std::path::Path;
588 /// let path = Path::new("/tmp/foo/bar.txt");
590 /// for component in path.components() {
591 /// println!("{:?}", component);
595 /// [`Component`]: enum.Component.html
596 /// [`components`]: struct.Path.html#method.components
597 /// [`Path`]: struct.Path.html
599 #[stable(feature = "rust1", since = "1.0.0")]
600 pub struct Components<'a> {
601 // The path left to parse components from
604 // The prefix as it was originally parsed, if any
605 prefix: Option<Prefix<'a>>,
607 // true if path *physically* has a root separator; for most Windows
608 // prefixes, it may have a "logical" rootseparator for the purposes of
609 // normalization, e.g., \\server\share == \\server\share\.
610 has_physical_root: bool,
612 // The iterator is double-ended, and these two states keep track of what has
613 // been produced from either end
618 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
620 /// This `struct` is created by the [`iter`] method on [`Path`].
621 /// See its documentation for more.
623 /// [`Component`]: enum.Component.html
624 /// [`iter`]: struct.Path.html#method.iter
625 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
626 /// [`Path`]: struct.Path.html
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub struct Iter<'a> {
630 inner: Components<'a>,
633 #[stable(feature = "path_components_debug", since = "1.13.0")]
634 impl fmt::Debug for Components<'_> {
635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636 struct DebugHelper<'a>(&'a Path);
638 impl fmt::Debug for DebugHelper<'_> {
639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641 .entries(self.0.components())
646 f.debug_tuple("Components")
647 .field(&DebugHelper(self.as_path()))
652 impl<'a> Components<'a> {
653 // how long is the prefix, if any?
655 fn prefix_len(&self) -> usize {
656 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
660 fn prefix_verbatim(&self) -> bool {
661 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
664 /// how much of the prefix is left from the point of view of iteration?
666 fn prefix_remaining(&self) -> usize {
667 if self.front == State::Prefix {
674 // Given the iteration so far, how much of the pre-State::Body path is left?
676 fn len_before_body(&self) -> usize {
677 let root = if self.front <= State::StartDir && self.has_physical_root {
682 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
687 self.prefix_remaining() + root + cur_dir
690 // is the iteration complete?
692 fn finished(&self) -> bool {
693 self.front == State::Done || self.back == State::Done || self.front > self.back
697 fn is_sep_byte(&self, b: u8) -> bool {
698 if self.prefix_verbatim() {
705 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
710 /// use std::path::Path;
712 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
713 /// components.next();
714 /// components.next();
716 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn as_path(&self) -> &'a Path {
720 let mut comps = self.clone();
721 if comps.front == State::Body {
724 if comps.back == State::Body {
727 unsafe { Path::from_u8_slice(comps.path) }
730 /// Is the *original* path rooted?
731 fn has_root(&self) -> bool {
732 if self.has_physical_root {
735 if let Some(p) = self.prefix {
736 if p.has_implicit_root() {
743 /// Should the normalized path include a leading . ?
744 fn include_cur_dir(&self) -> bool {
748 let mut iter = self.path[self.prefix_len()..].iter();
749 match (iter.next(), iter.next()) {
750 (Some(&b'.'), None) => true,
751 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
756 // parse a given byte sequence into the corresponding path component
757 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
759 b"." if self.prefix_verbatim() => Some(Component::CurDir),
760 b"." => None, // . components are normalized away, except at
761 // the beginning of a path, which is treated
762 // separately via `include_cur_dir`
763 b".." => Some(Component::ParentDir),
765 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
769 // parse a component from the left, saying how many bytes to consume to
770 // remove the component
771 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
772 debug_assert!(self.front == State::Body);
773 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
774 None => (0, self.path),
775 Some(i) => (1, &self.path[..i]),
777 (comp.len() + extra, self.parse_single_component(comp))
780 // parse a component from the right, saying how many bytes to consume to
781 // remove the component
782 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
783 debug_assert!(self.back == State::Body);
784 let start = self.len_before_body();
785 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
786 None => (0, &self.path[start..]),
787 Some(i) => (1, &self.path[start + i + 1..]),
789 (comp.len() + extra, self.parse_single_component(comp))
792 // trim away repeated separators (i.e., empty components) on the left
793 fn trim_left(&mut self) {
794 while !self.path.is_empty() {
795 let (size, comp) = self.parse_next_component();
799 self.path = &self.path[size..];
804 // trim away repeated separators (i.e., empty components) on the right
805 fn trim_right(&mut self) {
806 while self.path.len() > self.len_before_body() {
807 let (size, comp) = self.parse_next_component_back();
811 self.path = &self.path[..self.path.len() - size];
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl AsRef<Path> for Components<'_> {
819 fn as_ref(&self) -> &Path {
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl AsRef<OsStr> for Components<'_> {
826 fn as_ref(&self) -> &OsStr {
827 self.as_path().as_os_str()
831 #[stable(feature = "path_iter_debug", since = "1.13.0")]
832 impl fmt::Debug for Iter<'_> {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 struct DebugHelper<'a>(&'a Path);
836 impl fmt::Debug for DebugHelper<'_> {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839 .entries(self.0.iter())
844 f.debug_tuple("Iter")
845 .field(&DebugHelper(self.as_path()))
851 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
856 /// use std::path::Path;
858 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
862 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn as_path(&self) -> &'a Path {
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl AsRef<Path> for Iter<'_> {
872 fn as_ref(&self) -> &Path {
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl AsRef<OsStr> for Iter<'_> {
879 fn as_ref(&self) -> &OsStr {
880 self.as_path().as_os_str()
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<'a> Iterator for Iter<'a> {
886 type Item = &'a OsStr;
888 fn next(&mut self) -> Option<&'a OsStr> {
889 self.inner.next().map(Component::as_os_str)
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<'a> DoubleEndedIterator for Iter<'a> {
895 fn next_back(&mut self) -> Option<&'a OsStr> {
896 self.inner.next_back().map(Component::as_os_str)
900 #[stable(feature = "fused", since = "1.26.0")]
901 impl FusedIterator for Iter<'_> {}
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl<'a> Iterator for Components<'a> {
905 type Item = Component<'a>;
907 fn next(&mut self) -> Option<Component<'a>> {
908 while !self.finished() {
910 State::Prefix if self.prefix_len() > 0 => {
911 self.front = State::StartDir;
912 debug_assert!(self.prefix_len() <= self.path.len());
913 let raw = &self.path[..self.prefix_len()];
914 self.path = &self.path[self.prefix_len()..];
915 return Some(Component::Prefix(PrefixComponent {
916 raw: unsafe { u8_slice_as_os_str(raw) },
917 parsed: self.prefix.unwrap(),
921 self.front = State::StartDir;
924 self.front = State::Body;
925 if self.has_physical_root {
926 debug_assert!(!self.path.is_empty());
927 self.path = &self.path[1..];
928 return Some(Component::RootDir);
929 } else if let Some(p) = self.prefix {
930 if p.has_implicit_root() && !p.is_verbatim() {
931 return Some(Component::RootDir);
933 } else if self.include_cur_dir() {
934 debug_assert!(!self.path.is_empty());
935 self.path = &self.path[1..];
936 return Some(Component::CurDir);
939 State::Body if !self.path.is_empty() => {
940 let (size, comp) = self.parse_next_component();
941 self.path = &self.path[size..];
947 self.front = State::Done;
949 State::Done => unreachable!(),
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<'a> DoubleEndedIterator for Components<'a> {
958 fn next_back(&mut self) -> Option<Component<'a>> {
959 while !self.finished() {
961 State::Body if self.path.len() > self.len_before_body() => {
962 let (size, comp) = self.parse_next_component_back();
963 self.path = &self.path[..self.path.len() - size];
969 self.back = State::StartDir;
972 self.back = State::Prefix;
973 if self.has_physical_root {
974 self.path = &self.path[..self.path.len() - 1];
975 return Some(Component::RootDir);
976 } else if let Some(p) = self.prefix {
977 if p.has_implicit_root() && !p.is_verbatim() {
978 return Some(Component::RootDir);
980 } else if self.include_cur_dir() {
981 self.path = &self.path[..self.path.len() - 1];
982 return Some(Component::CurDir);
985 State::Prefix if self.prefix_len() > 0 => {
986 self.back = State::Done;
987 return Some(Component::Prefix(PrefixComponent {
988 raw: unsafe { u8_slice_as_os_str(self.path) },
989 parsed: self.prefix.unwrap(),
993 self.back = State::Done;
996 State::Done => unreachable!(),
1003 #[stable(feature = "fused", since = "1.26.0")]
1004 impl FusedIterator for Components<'_> {}
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<'a> cmp::PartialEq for Components<'a> {
1008 fn eq(&self, other: &Components<'a>) -> bool {
1009 Iterator::eq(self.clone(), other.clone())
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl cmp::Eq for Components<'_> {}
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<'a> cmp::PartialOrd for Components<'a> {
1018 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1019 Iterator::partial_cmp(self.clone(), other.clone())
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 impl cmp::Ord for Components<'_> {
1025 fn cmp(&self, other: &Self) -> cmp::Ordering {
1026 Iterator::cmp(self.clone(), other.clone())
1030 /// An iterator over [`Path`] and its ancestors.
1032 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1033 /// See its documentation for more.
1038 /// use std::path::Path;
1040 /// let path = Path::new("/foo/bar");
1042 /// for ancestor in path.ancestors() {
1043 /// println!("{}", ancestor.display());
1047 /// [`ancestors`]: struct.Path.html#method.ancestors
1048 /// [`Path`]: struct.Path.html
1049 #[derive(Copy, Clone, Debug)]
1050 #[stable(feature = "path_ancestors", since = "1.28.0")]
1051 pub struct Ancestors<'a> {
1052 next: Option<&'a Path>,
1055 #[stable(feature = "path_ancestors", since = "1.28.0")]
1056 impl<'a> Iterator for Ancestors<'a> {
1057 type Item = &'a Path;
1059 fn next(&mut self) -> Option<Self::Item> {
1060 let next = self.next;
1061 self.next = next.and_then(Path::parent);
1066 #[stable(feature = "path_ancestors", since = "1.28.0")]
1067 impl FusedIterator for Ancestors<'_> {}
1069 ////////////////////////////////////////////////////////////////////////////////
1070 // Basic types and traits
1071 ////////////////////////////////////////////////////////////////////////////////
1073 /// An owned, mutable path (akin to [`String`]).
1075 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1076 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1077 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1079 /// [`String`]: ../string/struct.String.html
1080 /// [`Path`]: struct.Path.html
1081 /// [`push`]: struct.PathBuf.html#method.push
1082 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1083 /// [`Deref`]: ../ops/trait.Deref.html
1085 /// More details about the overall approach can be found in
1086 /// the [module documentation](index.html).
1090 /// You can use [`push`] to build up a `PathBuf` from
1094 /// use std::path::PathBuf;
1096 /// let mut path = PathBuf::new();
1098 /// path.push(r"C:\");
1099 /// path.push("windows");
1100 /// path.push("system32");
1102 /// path.set_extension("dll");
1105 /// However, [`push`] is best used for dynamic situations. This is a better way
1106 /// to do this when you know all of the components ahead of time:
1109 /// use std::path::PathBuf;
1111 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1114 /// We can still do better than this! Since these are all strings, we can use
1118 /// use std::path::PathBuf;
1120 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1123 /// Which method works best depends on what kind of situation you're in.
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 pub struct PathBuf {
1131 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1132 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1135 /// Allocates an empty `PathBuf`.
1140 /// use std::path::PathBuf;
1142 /// let path = PathBuf::new();
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn new() -> PathBuf {
1146 PathBuf { inner: OsString::new() }
1149 /// Creates a new `PathBuf` with a given capacity used to create the
1150 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1155 /// #![feature(path_buf_capacity)]
1156 /// use std::path::PathBuf;
1158 /// let mut path = PathBuf::with_capacity(10);
1159 /// let capacity = path.capacity();
1161 /// // This push is done without reallocating
1162 /// path.push(r"C:\");
1164 /// assert_eq!(capacity, path.capacity());
1167 /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1168 /// [`OsString`]: ../ffi/struct.OsString.html
1169 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1170 pub fn with_capacity(capacity: usize) -> PathBuf {
1172 inner: OsString::with_capacity(capacity)
1176 /// Coerces to a [`Path`] slice.
1178 /// [`Path`]: struct.Path.html
1183 /// use std::path::{Path, PathBuf};
1185 /// let p = PathBuf::from("/test");
1186 /// assert_eq!(Path::new("/test"), p.as_path());
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub fn as_path(&self) -> &Path {
1193 /// Extends `self` with `path`.
1195 /// If `path` is absolute, it replaces the current path.
1199 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1200 /// replaces everything except for the prefix (if any) of `self`.
1201 /// * if `path` has a prefix but no root, it replaces `self`.
1205 /// Pushing a relative path extends the existing path:
1208 /// use std::path::PathBuf;
1210 /// let mut path = PathBuf::from("/tmp");
1211 /// path.push("file.bk");
1212 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1215 /// Pushing an absolute path replaces the existing path:
1218 /// use std::path::PathBuf;
1220 /// let mut path = PathBuf::from("/tmp");
1221 /// path.push("/etc");
1222 /// assert_eq!(path, PathBuf::from("/etc"));
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1226 self._push(path.as_ref())
1229 fn _push(&mut self, path: &Path) {
1230 // in general, a separator is needed if the rightmost byte is not a separator
1231 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1233 // in the special case of `C:` on Windows, do *not* add a separator
1235 let comps = self.components();
1236 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1237 comps.prefix.unwrap().is_drive() {
1242 // absolute `path` replaces `self`
1243 if path.is_absolute() || path.prefix().is_some() {
1244 self.as_mut_vec().truncate(0);
1246 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1247 } else if path.has_root() {
1248 let prefix_len = self.components().prefix_remaining();
1249 self.as_mut_vec().truncate(prefix_len);
1251 // `path` is a pure relative path
1252 } else if need_sep {
1253 self.inner.push(MAIN_SEP_STR);
1256 self.inner.push(path);
1259 /// Truncates `self` to [`self.parent`].
1261 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1262 /// Otherwise, returns `true`.
1264 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1265 /// [`self.parent`]: struct.PathBuf.html#method.parent
1270 /// use std::path::{Path, PathBuf};
1272 /// let mut p = PathBuf::from("/test/test.rs");
1275 /// assert_eq!(Path::new("/test"), p);
1277 /// assert_eq!(Path::new("/"), p);
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 pub fn pop(&mut self) -> bool {
1281 match self.parent().map(|p| p.as_u8_slice().len()) {
1283 self.as_mut_vec().truncate(len);
1290 /// Updates [`self.file_name`] to `file_name`.
1292 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1295 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1296 /// `file_name`. The new path will be a sibling of the original path.
1297 /// (That is, it will have the same parent.)
1299 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1300 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1301 /// [`pop`]: struct.PathBuf.html#method.pop
1306 /// use std::path::PathBuf;
1308 /// let mut buf = PathBuf::from("/");
1309 /// assert!(buf.file_name() == None);
1310 /// buf.set_file_name("bar");
1311 /// assert!(buf == PathBuf::from("/bar"));
1312 /// assert!(buf.file_name().is_some());
1313 /// buf.set_file_name("baz.txt");
1314 /// assert!(buf == PathBuf::from("/baz.txt"));
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1318 self._set_file_name(file_name.as_ref())
1321 fn _set_file_name(&mut self, file_name: &OsStr) {
1322 if self.file_name().is_some() {
1323 let popped = self.pop();
1324 debug_assert!(popped);
1326 self.push(file_name);
1329 /// Updates [`self.extension`] to `extension`.
1331 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1332 /// returns `true` and updates the extension otherwise.
1334 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1337 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1338 /// [`self.extension`]: struct.PathBuf.html#method.extension
1339 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1344 /// use std::path::{Path, PathBuf};
1346 /// let mut p = PathBuf::from("/feel/the");
1348 /// p.set_extension("force");
1349 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1351 /// p.set_extension("dark_side");
1352 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1356 self._set_extension(extension.as_ref())
1359 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1360 if self.file_name().is_none() {
1364 let mut stem = match self.file_stem() {
1365 Some(stem) => stem.to_os_string(),
1366 None => OsString::new(),
1369 if !os_str_as_u8_slice(extension).is_empty() {
1371 stem.push(extension);
1373 self.set_file_name(&stem);
1378 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1380 /// [`OsString`]: ../ffi/struct.OsString.html
1385 /// use std::path::PathBuf;
1387 /// let p = PathBuf::from("/the/head");
1388 /// let os_str = p.into_os_string();
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub fn into_os_string(self) -> OsString {
1395 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1397 /// [`Box`]: ../../std/boxed/struct.Box.html
1398 /// [`Path`]: struct.Path.html
1399 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1400 pub fn into_boxed_path(self) -> Box<Path> {
1401 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1402 unsafe { Box::from_raw(rw) }
1405 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1407 /// [`capacity`]: ../ffi/struct.OsString.html#method.capacity
1408 /// [`OsString`]: ../ffi/struct.OsString.html
1409 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1410 pub fn capacity(&self) -> usize {
1411 self.inner.capacity()
1414 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1416 /// [`clear`]: ../ffi/struct.OsString.html#method.clear
1417 /// [`OsString`]: ../ffi/struct.OsString.html
1418 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1419 pub fn clear(&mut self) {
1423 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1425 /// [`reserve`]: ../ffi/struct.OsString.html#method.reserve
1426 /// [`OsString`]: ../ffi/struct.OsString.html
1427 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1428 pub fn reserve(&mut self, additional: usize) {
1429 self.inner.reserve(additional)
1432 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1434 /// [`reserve_exact`]: ../ffi/struct.OsString.html#method.reserve_exact
1435 /// [`OsString`]: ../ffi/struct.OsString.html
1436 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1437 pub fn reserve_exact(&mut self, additional: usize) {
1438 self.inner.reserve_exact(additional)
1441 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1443 /// [`shrink_to_fit`]: ../ffi/struct.OsString.html#method.shrink_to_fit
1444 /// [`OsString`]: ../ffi/struct.OsString.html
1445 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1446 pub fn shrink_to_fit(&mut self) {
1447 self.inner.shrink_to_fit()
1450 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1452 /// [`shrink_to`]: ../ffi/struct.OsString.html#method.shrink_to
1453 /// [`OsString`]: ../ffi/struct.OsString.html
1454 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1455 pub fn shrink_to(&mut self, min_capacity: usize) {
1456 self.inner.shrink_to(min_capacity)
1460 #[stable(feature = "box_from_path", since = "1.17.0")]
1461 impl From<&Path> for Box<Path> {
1462 fn from(path: &Path) -> Box<Path> {
1463 let boxed: Box<OsStr> = path.inner.into();
1464 let rw = Box::into_raw(boxed) as *mut Path;
1465 unsafe { Box::from_raw(rw) }
1469 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1470 impl From<Box<Path>> for PathBuf {
1471 /// Converts a `Box<Path>` into a `PathBuf`
1473 /// This conversion does not allocate or copy memory.
1474 fn from(boxed: Box<Path>) -> PathBuf {
1475 boxed.into_path_buf()
1479 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1480 impl From<PathBuf> for Box<Path> {
1481 /// Converts a `PathBuf` into a `Box<Path>`
1483 /// This conversion currently should not allocate memory,
1484 /// but this behavior is not guaranteed on all platforms or in all future versions.
1485 fn from(p: PathBuf) -> Box<Path> {
1490 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1491 impl Clone for Box<Path> {
1493 fn clone(&self) -> Self {
1494 self.to_path_buf().into_boxed_path()
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1500 fn from(s: &T) -> PathBuf {
1501 PathBuf::from(s.as_ref().to_os_string())
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl From<OsString> for PathBuf {
1507 /// Converts a `OsString` into a `PathBuf`
1509 /// This conversion does not allocate or copy memory.
1510 fn from(s: OsString) -> PathBuf {
1511 PathBuf { inner: s }
1515 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1516 impl From<PathBuf> for OsString {
1517 /// Converts a `PathBuf` into a `OsString`
1519 /// This conversion does not allocate or copy memory.
1520 fn from(path_buf : PathBuf) -> OsString {
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 impl From<String> for PathBuf {
1527 /// Converts a `String` into a `PathBuf`
1529 /// This conversion does not allocate or copy memory.
1530 fn from(s: String) -> PathBuf {
1531 PathBuf::from(OsString::from(s))
1535 #[stable(feature = "path_from_str", since = "1.32.0")]
1536 impl FromStr for PathBuf {
1537 type Err = core::convert::Infallible;
1539 fn from_str(s: &str) -> Result<Self, Self::Err> {
1540 Ok(PathBuf::from(s))
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1546 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1547 let mut buf = PathBuf::new();
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1555 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1556 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl fmt::Debug for PathBuf {
1562 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1563 fmt::Debug::fmt(&**self, formatter)
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl ops::Deref for PathBuf {
1571 fn deref(&self) -> &Path {
1572 Path::new(&self.inner)
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 impl Borrow<Path> for PathBuf {
1578 fn borrow(&self) -> &Path {
1583 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1584 impl Default for PathBuf {
1585 fn default() -> Self {
1590 #[stable(feature = "cow_from_path", since = "1.6.0")]
1591 impl<'a> From<&'a Path> for Cow<'a, Path> {
1593 fn from(s: &'a Path) -> Cow<'a, Path> {
1598 #[stable(feature = "cow_from_path", since = "1.6.0")]
1599 impl<'a> From<PathBuf> for Cow<'a, Path> {
1601 fn from(s: PathBuf) -> Cow<'a, Path> {
1606 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1607 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1609 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1610 Cow::Borrowed(p.as_path())
1614 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1615 impl<'a> From<Cow<'a, Path>> for PathBuf {
1617 fn from(p: Cow<'a, Path>) -> Self {
1622 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1623 impl From<PathBuf> for Arc<Path> {
1624 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1626 fn from(s: PathBuf) -> Arc<Path> {
1627 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1628 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1632 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1633 impl From<&Path> for Arc<Path> {
1634 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1636 fn from(s: &Path) -> Arc<Path> {
1637 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1638 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1642 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1643 impl From<PathBuf> for Rc<Path> {
1644 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1646 fn from(s: PathBuf) -> Rc<Path> {
1647 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1648 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1652 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1653 impl From<&Path> for Rc<Path> {
1654 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1656 fn from(s: &Path) -> Rc<Path> {
1657 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1658 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl ToOwned for Path {
1664 type Owned = PathBuf;
1665 fn to_owned(&self) -> PathBuf {
1668 fn clone_into(&self, target: &mut PathBuf) {
1669 self.inner.clone_into(&mut target.inner);
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl cmp::PartialEq for PathBuf {
1675 fn eq(&self, other: &PathBuf) -> bool {
1676 self.components() == other.components()
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl Hash for PathBuf {
1682 fn hash<H: Hasher>(&self, h: &mut H) {
1683 self.as_path().hash(h)
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl cmp::Eq for PathBuf {}
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl cmp::PartialOrd for PathBuf {
1692 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1693 self.components().partial_cmp(other.components())
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl cmp::Ord for PathBuf {
1699 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1700 self.components().cmp(other.components())
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 impl AsRef<OsStr> for PathBuf {
1706 fn as_ref(&self) -> &OsStr {
1711 /// A slice of a path (akin to [`str`]).
1713 /// This type supports a number of operations for inspecting a path, including
1714 /// breaking the path into its components (separated by `/` on Unix and by either
1715 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1716 /// is absolute, and so on.
1718 /// This is an *unsized* type, meaning that it must always be used behind a
1719 /// pointer like `&` or [`Box`]. For an owned version of this type,
1720 /// see [`PathBuf`].
1722 /// [`str`]: ../primitive.str.html
1723 /// [`Box`]: ../boxed/struct.Box.html
1724 /// [`PathBuf`]: struct.PathBuf.html
1726 /// More details about the overall approach can be found in
1727 /// the [module documentation](index.html).
1732 /// use std::path::Path;
1733 /// use std::ffi::OsStr;
1735 /// // Note: this example does work on Windows
1736 /// let path = Path::new("./foo/bar.txt");
1738 /// let parent = path.parent();
1739 /// assert_eq!(parent, Some(Path::new("./foo")));
1741 /// let file_stem = path.file_stem();
1742 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1744 /// let extension = path.extension();
1745 /// assert_eq!(extension, Some(OsStr::new("txt")));
1747 #[stable(feature = "rust1", since = "1.0.0")]
1752 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1755 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1756 /// See its documentation for more.
1758 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1759 /// [`Path`]: struct.Path.html
1760 #[derive(Debug, Clone, PartialEq, Eq)]
1761 #[stable(since = "1.7.0", feature = "strip_prefix")]
1762 pub struct StripPrefixError(());
1765 // The following (private!) function allows construction of a path from a u8
1766 // slice, which is only safe when it is known to follow the OsStr encoding.
1767 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1768 Path::new(u8_slice_as_os_str(s))
1770 // The following (private!) function reveals the byte encoding used for OsStr.
1771 fn as_u8_slice(&self) -> &[u8] {
1772 os_str_as_u8_slice(&self.inner)
1775 /// Directly wraps a string slice as a `Path` slice.
1777 /// This is a cost-free conversion.
1782 /// use std::path::Path;
1784 /// Path::new("foo.txt");
1787 /// You can create `Path`s from `String`s, or even other `Path`s:
1790 /// use std::path::Path;
1792 /// let string = String::from("foo.txt");
1793 /// let from_string = Path::new(&string);
1794 /// let from_path = Path::new(&from_string);
1795 /// assert_eq!(from_string, from_path);
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1799 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1802 /// Yields the underlying [`OsStr`] slice.
1804 /// [`OsStr`]: ../ffi/struct.OsStr.html
1809 /// use std::path::Path;
1811 /// let os_str = Path::new("foo.txt").as_os_str();
1812 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 pub fn as_os_str(&self) -> &OsStr {
1819 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1821 /// This conversion may entail doing a check for UTF-8 validity.
1822 /// Note that validation is performed because non-UTF-8 strings are
1823 /// perfectly valid for some OS.
1825 /// [`&str`]: ../primitive.str.html
1830 /// use std::path::Path;
1832 /// let path = Path::new("foo.txt");
1833 /// assert_eq!(path.to_str(), Some("foo.txt"));
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 pub fn to_str(&self) -> Option<&str> {
1840 /// Converts a `Path` to a [`Cow<str>`].
1842 /// Any non-Unicode sequences are replaced with
1843 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1845 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1846 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1850 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1853 /// use std::path::Path;
1855 /// let path = Path::new("foo.txt");
1856 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1859 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1860 /// have returned `"fo�.txt"`.
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1863 self.inner.to_string_lossy()
1866 /// Converts a `Path` to an owned [`PathBuf`].
1868 /// [`PathBuf`]: struct.PathBuf.html
1873 /// use std::path::Path;
1875 /// let path_buf = Path::new("foo.txt").to_path_buf();
1876 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1878 #[rustc_conversion_suggestion]
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 pub fn to_path_buf(&self) -> PathBuf {
1881 PathBuf::from(self.inner.to_os_string())
1884 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1885 /// the current directory.
1887 /// * On Unix, a path is absolute if it starts with the root, so
1888 /// `is_absolute` and [`has_root`] are equivalent.
1890 /// * On Windows, a path is absolute if it has a prefix and starts with the
1891 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1896 /// use std::path::Path;
1898 /// assert!(!Path::new("foo.txt").is_absolute());
1901 /// [`has_root`]: #method.has_root
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 #[allow(deprecated)]
1904 pub fn is_absolute(&self) -> bool {
1905 if cfg!(target_os = "redox") {
1906 // FIXME: Allow Redox prefixes
1907 self.has_root() || has_redox_scheme(self.as_u8_slice())
1909 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1913 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1915 /// See [`is_absolute`]'s documentation for more details.
1920 /// use std::path::Path;
1922 /// assert!(Path::new("foo.txt").is_relative());
1925 /// [`is_absolute`]: #method.is_absolute
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 pub fn is_relative(&self) -> bool {
1931 fn prefix(&self) -> Option<Prefix<'_>> {
1932 self.components().prefix
1935 /// Returns `true` if the `Path` has a root.
1937 /// * On Unix, a path has a root if it begins with `/`.
1939 /// * On Windows, a path has a root if it:
1940 /// * has no prefix and begins with a separator, e.g., `\windows`
1941 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1942 /// * has any non-disk prefix, e.g., `\\server\share`
1947 /// use std::path::Path;
1949 /// assert!(Path::new("/etc/passwd").has_root());
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 pub fn has_root(&self) -> bool {
1953 self.components().has_root()
1956 /// Returns the `Path` without its final component, if there is one.
1958 /// Returns [`None`] if the path terminates in a root or prefix.
1960 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1965 /// use std::path::Path;
1967 /// let path = Path::new("/foo/bar");
1968 /// let parent = path.parent().unwrap();
1969 /// assert_eq!(parent, Path::new("/foo"));
1971 /// let grand_parent = parent.parent().unwrap();
1972 /// assert_eq!(grand_parent, Path::new("/"));
1973 /// assert_eq!(grand_parent.parent(), None);
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 pub fn parent(&self) -> Option<&Path> {
1977 let mut comps = self.components();
1978 let comp = comps.next_back();
1981 Component::Normal(_) |
1983 Component::ParentDir => Some(comps.as_path()),
1989 /// Produces an iterator over `Path` and its ancestors.
1991 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1992 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1993 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1994 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2000 /// use std::path::Path;
2002 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2003 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2004 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2005 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2006 /// assert_eq!(ancestors.next(), None);
2009 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2010 /// [`parent`]: struct.Path.html#method.parent
2011 #[stable(feature = "path_ancestors", since = "1.28.0")]
2012 pub fn ancestors(&self) -> Ancestors<'_> {
2018 /// Returns the final component of the `Path`, if there is one.
2020 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2021 /// is the directory name.
2023 /// Returns [`None`] if the path terminates in `..`.
2025 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2030 /// use std::path::Path;
2031 /// use std::ffi::OsStr;
2033 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2034 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2035 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2036 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2037 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2038 /// assert_eq!(None, Path::new("/").file_name());
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 pub fn file_name(&self) -> Option<&OsStr> {
2042 self.components().next_back().and_then(|p| {
2044 Component::Normal(p) => Some(p.as_ref()),
2050 /// Returns a path that, when joined onto `base`, yields `self`.
2054 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2055 /// returns `false`), returns [`Err`].
2057 /// [`starts_with`]: #method.starts_with
2058 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2063 /// use std::path::{Path, PathBuf};
2065 /// let path = Path::new("/test/haha/foo.txt");
2067 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2068 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2069 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2070 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2071 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2072 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2073 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2075 /// let prefix = PathBuf::from("/test/");
2076 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2078 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2079 pub fn strip_prefix<P>(&self, base: P)
2080 -> Result<&Path, StripPrefixError>
2081 where P: AsRef<Path>
2083 self._strip_prefix(base.as_ref())
2086 fn _strip_prefix(&self, base: &Path)
2087 -> Result<&Path, StripPrefixError> {
2088 iter_after(self.components(), base.components())
2089 .map(|c| c.as_path())
2090 .ok_or(StripPrefixError(()))
2093 /// Determines whether `base` is a prefix of `self`.
2095 /// Only considers whole path components to match.
2100 /// use std::path::Path;
2102 /// let path = Path::new("/etc/passwd");
2104 /// assert!(path.starts_with("/etc"));
2105 /// assert!(path.starts_with("/etc/"));
2106 /// assert!(path.starts_with("/etc/passwd"));
2107 /// assert!(path.starts_with("/etc/passwd/"));
2109 /// assert!(!path.starts_with("/e"));
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2113 self._starts_with(base.as_ref())
2116 fn _starts_with(&self, base: &Path) -> bool {
2117 iter_after(self.components(), base.components()).is_some()
2120 /// Determines whether `child` is a suffix of `self`.
2122 /// Only considers whole path components to match.
2127 /// use std::path::Path;
2129 /// let path = Path::new("/etc/passwd");
2131 /// assert!(path.ends_with("passwd"));
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2135 self._ends_with(child.as_ref())
2138 fn _ends_with(&self, child: &Path) -> bool {
2139 iter_after(self.components().rev(), child.components().rev()).is_some()
2142 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2144 /// [`self.file_name`]: struct.Path.html#method.file_name
2148 /// * [`None`], if there is no file name;
2149 /// * The entire file name if there is no embedded `.`;
2150 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2151 /// * Otherwise, the portion of the file name before the final `.`
2153 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2158 /// use std::path::Path;
2160 /// let path = Path::new("foo.rs");
2162 /// assert_eq!("foo", path.file_stem().unwrap());
2164 #[stable(feature = "rust1", since = "1.0.0")]
2165 pub fn file_stem(&self) -> Option<&OsStr> {
2166 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2169 /// Extracts the extension of [`self.file_name`], if possible.
2171 /// The extension is:
2173 /// * [`None`], if there is no file name;
2174 /// * [`None`], if there is no embedded `.`;
2175 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2176 /// * Otherwise, the portion of the file name after the final `.`
2178 /// [`self.file_name`]: struct.Path.html#method.file_name
2179 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2184 /// use std::path::Path;
2186 /// let path = Path::new("foo.rs");
2188 /// assert_eq!("rs", path.extension().unwrap());
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 pub fn extension(&self) -> Option<&OsStr> {
2192 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2195 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2197 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2199 /// [`PathBuf`]: struct.PathBuf.html
2200 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2205 /// use std::path::{Path, PathBuf};
2207 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2211 self._join(path.as_ref())
2214 fn _join(&self, path: &Path) -> PathBuf {
2215 let mut buf = self.to_path_buf();
2220 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2222 /// See [`PathBuf::set_file_name`] for more details.
2224 /// [`PathBuf`]: struct.PathBuf.html
2225 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2230 /// use std::path::{Path, PathBuf};
2232 /// let path = Path::new("/tmp/foo.txt");
2233 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2235 /// let path = Path::new("/tmp");
2236 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2238 #[stable(feature = "rust1", since = "1.0.0")]
2239 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2240 self._with_file_name(file_name.as_ref())
2243 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2244 let mut buf = self.to_path_buf();
2245 buf.set_file_name(file_name);
2249 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2251 /// See [`PathBuf::set_extension`] for more details.
2253 /// [`PathBuf`]: struct.PathBuf.html
2254 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2259 /// use std::path::{Path, PathBuf};
2261 /// let path = Path::new("foo.rs");
2262 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2264 #[stable(feature = "rust1", since = "1.0.0")]
2265 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2266 self._with_extension(extension.as_ref())
2269 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2270 let mut buf = self.to_path_buf();
2271 buf.set_extension(extension);
2275 /// Produces an iterator over the [`Component`]s of the path.
2277 /// When parsing the path, there is a small amount of normalization:
2279 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2280 /// `a` and `b` as components.
2282 /// * Occurrences of `.` are normalized away, except if they are at the
2283 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2284 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2285 /// an additional [`CurDir`] component.
2287 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2289 /// Note that no other normalization takes place; in particular, `a/c`
2290 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2291 /// is a symbolic link (so its parent isn't `a`).
2296 /// use std::path::{Path, Component};
2297 /// use std::ffi::OsStr;
2299 /// let mut components = Path::new("/tmp/foo.txt").components();
2301 /// assert_eq!(components.next(), Some(Component::RootDir));
2302 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2303 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2304 /// assert_eq!(components.next(), None)
2307 /// [`Component`]: enum.Component.html
2308 /// [`CurDir`]: enum.Component.html#variant.CurDir
2309 #[stable(feature = "rust1", since = "1.0.0")]
2310 pub fn components(&self) -> Components<'_> {
2311 let prefix = parse_prefix(self.as_os_str());
2313 path: self.as_u8_slice(),
2315 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2316 has_redox_scheme(self.as_u8_slice()),
2317 front: State::Prefix,
2322 /// Produces an iterator over the path's components viewed as [`OsStr`]
2325 /// For more information about the particulars of how the path is separated
2326 /// into components, see [`components`].
2328 /// [`components`]: #method.components
2329 /// [`OsStr`]: ../ffi/struct.OsStr.html
2334 /// use std::path::{self, Path};
2335 /// use std::ffi::OsStr;
2337 /// let mut it = Path::new("/tmp/foo.txt").iter();
2338 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2339 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2340 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2341 /// assert_eq!(it.next(), None)
2343 #[stable(feature = "rust1", since = "1.0.0")]
2344 pub fn iter(&self) -> Iter<'_> {
2345 Iter { inner: self.components() }
2348 /// Returns an object that implements [`Display`] for safely printing paths
2349 /// that may contain non-Unicode data.
2351 /// [`Display`]: ../fmt/trait.Display.html
2356 /// use std::path::Path;
2358 /// let path = Path::new("/tmp/foo.rs");
2360 /// println!("{}", path.display());
2362 #[stable(feature = "rust1", since = "1.0.0")]
2363 pub fn display(&self) -> Display<'_> {
2364 Display { path: self }
2367 /// Queries the file system to get information about a file, directory, etc.
2369 /// This function will traverse symbolic links to query information about the
2370 /// destination file.
2372 /// This is an alias to [`fs::metadata`].
2374 /// [`fs::metadata`]: ../fs/fn.metadata.html
2379 /// use std::path::Path;
2381 /// let path = Path::new("/Minas/tirith");
2382 /// let metadata = path.metadata().expect("metadata call failed");
2383 /// println!("{:?}", metadata.file_type());
2385 #[stable(feature = "path_ext", since = "1.5.0")]
2386 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2390 /// Queries the metadata about a file without following symlinks.
2392 /// This is an alias to [`fs::symlink_metadata`].
2394 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2399 /// use std::path::Path;
2401 /// let path = Path::new("/Minas/tirith");
2402 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2403 /// println!("{:?}", metadata.file_type());
2405 #[stable(feature = "path_ext", since = "1.5.0")]
2406 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2407 fs::symlink_metadata(self)
2410 /// Returns the canonical, absolute form of the path with all intermediate
2411 /// components normalized and symbolic links resolved.
2413 /// This is an alias to [`fs::canonicalize`].
2415 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2420 /// use std::path::{Path, PathBuf};
2422 /// let path = Path::new("/foo/test/../test/bar.rs");
2423 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2425 #[stable(feature = "path_ext", since = "1.5.0")]
2426 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2427 fs::canonicalize(self)
2430 /// Reads a symbolic link, returning the file that the link points to.
2432 /// This is an alias to [`fs::read_link`].
2434 /// [`fs::read_link`]: ../fs/fn.read_link.html
2439 /// use std::path::Path;
2441 /// let path = Path::new("/laputa/sky_castle.rs");
2442 /// let path_link = path.read_link().expect("read_link call failed");
2444 #[stable(feature = "path_ext", since = "1.5.0")]
2445 pub fn read_link(&self) -> io::Result<PathBuf> {
2449 /// Returns an iterator over the entries within a directory.
2451 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2452 /// errors may be encountered after an iterator is initially constructed.
2454 /// This is an alias to [`fs::read_dir`].
2456 /// [`io::Result`]: ../io/type.Result.html
2457 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2458 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2463 /// use std::path::Path;
2465 /// let path = Path::new("/laputa");
2466 /// for entry in path.read_dir().expect("read_dir call failed") {
2467 /// if let Ok(entry) = entry {
2468 /// println!("{:?}", entry.path());
2472 #[stable(feature = "path_ext", since = "1.5.0")]
2473 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2477 /// Returns `true` if the path points at an existing entity.
2479 /// This function will traverse symbolic links to query information about the
2480 /// destination file. In case of broken symbolic links this will return `false`.
2482 /// If you cannot access the directory containing the file, e.g., because of a
2483 /// permission error, this will return `false`.
2488 /// use std::path::Path;
2489 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2494 /// This is a convenience function that coerces errors to false. If you want to
2495 /// check errors, call [fs::metadata].
2497 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2498 #[stable(feature = "path_ext", since = "1.5.0")]
2499 pub fn exists(&self) -> bool {
2500 fs::metadata(self).is_ok()
2503 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2505 /// This function will traverse symbolic links to query information about the
2506 /// destination file. In case of broken symbolic links this will return `false`.
2508 /// If you cannot access the directory containing the file, e.g., because of a
2509 /// permission error, this will return `false`.
2514 /// use std::path::Path;
2515 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2516 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2521 /// This is a convenience function that coerces errors to false. If you want to
2522 /// check errors, call [fs::metadata] and handle its Result. Then call
2523 /// [fs::Metadata::is_file] if it was Ok.
2525 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2526 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2527 #[stable(feature = "path_ext", since = "1.5.0")]
2528 pub fn is_file(&self) -> bool {
2529 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2532 /// Returns `true` if the path exists on disk and is pointing at a directory.
2534 /// This function will traverse symbolic links to query information about the
2535 /// destination file. In case of broken symbolic links this will return `false`.
2537 /// If you cannot access the directory containing the file, e.g., because of a
2538 /// permission error, this will return `false`.
2543 /// use std::path::Path;
2544 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2545 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2550 /// This is a convenience function that coerces errors to false. If you want to
2551 /// check errors, call [fs::metadata] and handle its Result. Then call
2552 /// [fs::Metadata::is_dir] if it was Ok.
2554 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2555 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2556 #[stable(feature = "path_ext", since = "1.5.0")]
2557 pub fn is_dir(&self) -> bool {
2558 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2561 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2564 /// [`Box`]: ../../std/boxed/struct.Box.html
2565 /// [`PathBuf`]: struct.PathBuf.html
2566 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2567 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2568 let rw = Box::into_raw(self) as *mut OsStr;
2569 let inner = unsafe { Box::from_raw(rw) };
2570 PathBuf { inner: OsString::from(inner) }
2574 #[stable(feature = "rust1", since = "1.0.0")]
2575 impl AsRef<OsStr> for Path {
2576 fn as_ref(&self) -> &OsStr {
2581 #[stable(feature = "rust1", since = "1.0.0")]
2582 impl fmt::Debug for Path {
2583 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2584 fmt::Debug::fmt(&self.inner, formatter)
2588 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2590 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2591 /// [`Display`] trait in a way that mitigates that. It is created by the
2592 /// [`display`][`Path::display`] method on [`Path`].
2597 /// use std::path::Path;
2599 /// let path = Path::new("/tmp/foo.rs");
2601 /// println!("{}", path.display());
2604 /// [`Display`]: ../../std/fmt/trait.Display.html
2605 /// [`format!`]: ../../std/macro.format.html
2606 /// [`Path`]: struct.Path.html
2607 /// [`Path::display`]: struct.Path.html#method.display
2608 #[stable(feature = "rust1", since = "1.0.0")]
2609 pub struct Display<'a> {
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 impl fmt::Debug for Display<'_> {
2615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2616 fmt::Debug::fmt(&self.path, f)
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 impl fmt::Display for Display<'_> {
2622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2623 self.path.inner.display(f)
2627 #[stable(feature = "rust1", since = "1.0.0")]
2628 impl cmp::PartialEq for Path {
2629 fn eq(&self, other: &Path) -> bool {
2630 self.components().eq(other.components())
2634 #[stable(feature = "rust1", since = "1.0.0")]
2635 impl Hash for Path {
2636 fn hash<H: Hasher>(&self, h: &mut H) {
2637 for component in self.components() {
2643 #[stable(feature = "rust1", since = "1.0.0")]
2644 impl cmp::Eq for Path {}
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 impl cmp::PartialOrd for Path {
2648 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2649 self.components().partial_cmp(other.components())
2653 #[stable(feature = "rust1", since = "1.0.0")]
2654 impl cmp::Ord for Path {
2655 fn cmp(&self, other: &Path) -> cmp::Ordering {
2656 self.components().cmp(other.components())
2660 #[stable(feature = "rust1", since = "1.0.0")]
2661 impl AsRef<Path> for Path {
2662 fn as_ref(&self) -> &Path {
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 impl AsRef<Path> for OsStr {
2669 fn as_ref(&self) -> &Path {
2674 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2675 impl AsRef<Path> for Cow<'_, OsStr> {
2676 fn as_ref(&self) -> &Path {
2681 #[stable(feature = "rust1", since = "1.0.0")]
2682 impl AsRef<Path> for OsString {
2683 fn as_ref(&self) -> &Path {
2688 #[stable(feature = "rust1", since = "1.0.0")]
2689 impl AsRef<Path> for str {
2690 fn as_ref(&self) -> &Path {
2695 #[stable(feature = "rust1", since = "1.0.0")]
2696 impl AsRef<Path> for String {
2697 fn as_ref(&self) -> &Path {
2702 #[stable(feature = "rust1", since = "1.0.0")]
2703 impl AsRef<Path> for PathBuf {
2704 fn as_ref(&self) -> &Path {
2709 #[stable(feature = "path_into_iter", since = "1.6.0")]
2710 impl<'a> IntoIterator for &'a PathBuf {
2711 type Item = &'a OsStr;
2712 type IntoIter = Iter<'a>;
2713 fn into_iter(self) -> Iter<'a> { self.iter() }
2716 #[stable(feature = "path_into_iter", since = "1.6.0")]
2717 impl<'a> IntoIterator for &'a Path {
2718 type Item = &'a OsStr;
2719 type IntoIter = Iter<'a>;
2720 fn into_iter(self) -> Iter<'a> { self.iter() }
2723 macro_rules! impl_cmp {
2724 ($lhs:ty, $rhs: ty) => {
2725 #[stable(feature = "partialeq_path", since = "1.6.0")]
2726 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2728 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2731 #[stable(feature = "partialeq_path", since = "1.6.0")]
2732 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2734 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2737 #[stable(feature = "cmp_path", since = "1.8.0")]
2738 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2740 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2741 <Path as PartialOrd>::partial_cmp(self, other)
2745 #[stable(feature = "cmp_path", since = "1.8.0")]
2746 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2748 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2749 <Path as PartialOrd>::partial_cmp(self, other)
2755 impl_cmp!(PathBuf, Path);
2756 impl_cmp!(PathBuf, &'a Path);
2757 impl_cmp!(Cow<'a, Path>, Path);
2758 impl_cmp!(Cow<'a, Path>, &'b Path);
2759 impl_cmp!(Cow<'a, Path>, PathBuf);
2761 macro_rules! impl_cmp_os_str {
2762 ($lhs:ty, $rhs: ty) => {
2763 #[stable(feature = "cmp_path", since = "1.8.0")]
2764 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2766 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2769 #[stable(feature = "cmp_path", since = "1.8.0")]
2770 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2772 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2775 #[stable(feature = "cmp_path", since = "1.8.0")]
2776 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2778 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2779 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2783 #[stable(feature = "cmp_path", since = "1.8.0")]
2784 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2786 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2787 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2793 impl_cmp_os_str!(PathBuf, OsStr);
2794 impl_cmp_os_str!(PathBuf, &'a OsStr);
2795 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2796 impl_cmp_os_str!(PathBuf, OsString);
2797 impl_cmp_os_str!(Path, OsStr);
2798 impl_cmp_os_str!(Path, &'a OsStr);
2799 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2800 impl_cmp_os_str!(Path, OsString);
2801 impl_cmp_os_str!(&'a Path, OsStr);
2802 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2803 impl_cmp_os_str!(&'a Path, OsString);
2804 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2805 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2806 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2808 #[stable(since = "1.7.0", feature = "strip_prefix")]
2809 impl fmt::Display for StripPrefixError {
2810 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2811 self.description().fmt(f)
2815 #[stable(since = "1.7.0", feature = "strip_prefix")]
2816 impl Error for StripPrefixError {
2817 fn description(&self) -> &str { "prefix not found" }
2825 use crate::sync::Arc;
2828 ($path:expr, iter: $iter:expr) => (
2830 let path = Path::new($path);
2832 // Forward iteration
2833 let comps = path.iter()
2834 .map(|p| p.to_string_lossy().into_owned())
2835 .collect::<Vec<String>>();
2836 let exp: &[&str] = &$iter;
2837 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2838 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2841 // Reverse iteration
2842 let comps = Path::new($path).iter().rev()
2843 .map(|p| p.to_string_lossy().into_owned())
2844 .collect::<Vec<String>>();
2845 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2846 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2851 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2853 let path = Path::new($path);
2855 let act_root = path.has_root();
2856 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2857 $has_root, act_root);
2859 let act_abs = path.is_absolute();
2860 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2861 $is_absolute, act_abs);
2865 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2867 let path = Path::new($path);
2869 let parent = path.parent().map(|p| p.to_str().unwrap());
2870 let exp_parent: Option<&str> = $parent;
2871 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2872 exp_parent, parent);
2874 let file = path.file_name().map(|p| p.to_str().unwrap());
2875 let exp_file: Option<&str> = $file;
2876 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2881 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2883 let path = Path::new($path);
2885 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2886 let exp_stem: Option<&str> = $file_stem;
2887 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2890 let ext = path.extension().map(|p| p.to_str().unwrap());
2891 let exp_ext: Option<&str> = $extension;
2892 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2897 ($path:expr, iter: $iter:expr,
2898 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2899 parent: $parent:expr, file_name: $file:expr,
2900 file_stem: $file_stem:expr, extension: $extension:expr) => (
2902 t!($path, iter: $iter);
2903 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2904 t!($path, parent: $parent, file_name: $file);
2905 t!($path, file_stem: $file_stem, extension: $extension);
2912 use crate::borrow::Cow;
2914 let static_path = Path::new("/home/foo");
2915 let static_cow_path: Cow<'static, Path> = static_path.into();
2916 let pathbuf = PathBuf::from("/home/foo");
2919 let path: &Path = &pathbuf;
2920 let borrowed_cow_path: Cow<'_, Path> = path.into();
2922 assert_eq!(static_cow_path, borrowed_cow_path);
2925 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2927 assert_eq!(static_cow_path, owned_cow_path);
2932 pub fn test_decompositions_unix() {
2948 file_name: Some("foo"),
2949 file_stem: Some("foo"),
2968 file_name: Some("foo"),
2969 file_stem: Some("foo"),
2978 file_name: Some("foo"),
2979 file_stem: Some("foo"),
2988 file_name: Some("foo"),
2989 file_stem: Some("foo"),
2994 iter: ["foo", "bar"],
2997 parent: Some("foo"),
2998 file_name: Some("bar"),
2999 file_stem: Some("bar"),
3004 iter: ["/", "foo", "bar"],
3007 parent: Some("/foo"),
3008 file_name: Some("bar"),
3009 file_stem: Some("bar"),
3018 file_name: Some("foo"),
3019 file_stem: Some("foo"),
3024 iter: ["/", "foo", "bar"],
3027 parent: Some("///foo"),
3028 file_name: Some("bar"),
3029 file_stem: Some("bar"),
3068 file_name: Some("foo"),
3069 file_stem: Some("foo"),
3074 iter: ["foo", ".."],
3077 parent: Some("foo"),
3088 file_name: Some("foo"),
3089 file_stem: Some("foo"),
3094 iter: ["foo", "bar"],
3097 parent: Some("foo"),
3098 file_name: Some("bar"),
3099 file_stem: Some("bar"),
3104 iter: ["foo", ".."],
3107 parent: Some("foo"),
3114 iter: ["foo", "..", "bar"],
3117 parent: Some("foo/.."),
3118 file_name: Some("bar"),
3119 file_stem: Some("bar"),
3128 file_name: Some("a"),
3129 file_stem: Some("a"),
3158 file_name: Some("b"),
3159 file_stem: Some("b"),
3168 file_name: Some("b"),
3169 file_stem: Some("b"),
3178 file_name: Some("b"),
3179 file_stem: Some("b"),
3184 iter: ["a", "b", "c"],
3187 parent: Some("a/b"),
3188 file_name: Some("c"),
3189 file_stem: Some("c"),
3198 file_name: Some(".foo"),
3199 file_stem: Some(".foo"),
3206 pub fn test_decompositions_windows() {
3222 file_name: Some("foo"),
3223 file_stem: Some("foo"),
3278 iter: ["\\", "foo"],
3282 file_name: Some("foo"),
3283 file_stem: Some("foo"),
3292 file_name: Some("foo"),
3293 file_stem: Some("foo"),
3298 iter: ["\\", "foo"],
3302 file_name: Some("foo"),
3303 file_stem: Some("foo"),
3308 iter: ["foo", "bar"],
3311 parent: Some("foo"),
3312 file_name: Some("bar"),
3313 file_stem: Some("bar"),
3318 iter: ["\\", "foo", "bar"],
3321 parent: Some("/foo"),
3322 file_name: Some("bar"),
3323 file_stem: Some("bar"),
3328 iter: ["\\", "foo"],
3332 file_name: Some("foo"),
3333 file_stem: Some("foo"),
3338 iter: ["\\", "foo", "bar"],
3341 parent: Some("///foo"),
3342 file_name: Some("bar"),
3343 file_stem: Some("bar"),
3382 file_name: Some("foo"),
3383 file_stem: Some("foo"),
3388 iter: ["foo", ".."],
3391 parent: Some("foo"),
3402 file_name: Some("foo"),
3403 file_stem: Some("foo"),
3408 iter: ["foo", "bar"],
3411 parent: Some("foo"),
3412 file_name: Some("bar"),
3413 file_stem: Some("bar"),
3418 iter: ["foo", ".."],
3421 parent: Some("foo"),
3428 iter: ["foo", "..", "bar"],
3431 parent: Some("foo/.."),
3432 file_name: Some("bar"),
3433 file_stem: Some("bar"),
3442 file_name: Some("a"),
3443 file_stem: Some("a"),
3472 file_name: Some("b"),
3473 file_stem: Some("b"),
3482 file_name: Some("b"),
3483 file_stem: Some("b"),
3492 file_name: Some("b"),
3493 file_stem: Some("b"),
3498 iter: ["a", "b", "c"],
3501 parent: Some("a/b"),
3502 file_name: Some("c"),
3503 file_stem: Some("c"),
3507 iter: ["a", "b", "c"],
3510 parent: Some("a\\b"),
3511 file_name: Some("c"),
3512 file_stem: Some("c"),
3521 file_name: Some("a"),
3522 file_stem: Some("a"),
3527 iter: ["c:", "\\", "foo.txt"],
3530 parent: Some("c:\\"),
3531 file_name: Some("foo.txt"),
3532 file_stem: Some("foo"),
3533 extension: Some("txt")
3536 t!("\\\\server\\share\\foo.txt",
3537 iter: ["\\\\server\\share", "\\", "foo.txt"],
3540 parent: Some("\\\\server\\share\\"),
3541 file_name: Some("foo.txt"),
3542 file_stem: Some("foo"),
3543 extension: Some("txt")
3546 t!("\\\\server\\share",
3547 iter: ["\\\\server\\share", "\\"],
3557 iter: ["\\", "server"],
3561 file_name: Some("server"),
3562 file_stem: Some("server"),
3566 t!("\\\\?\\bar\\foo.txt",
3567 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3570 parent: Some("\\\\?\\bar\\"),
3571 file_name: Some("foo.txt"),
3572 file_stem: Some("foo"),
3573 extension: Some("txt")
3577 iter: ["\\\\?\\bar"],
3596 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3597 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3600 parent: Some("\\\\?\\UNC\\server\\share\\"),
3601 file_name: Some("foo.txt"),
3602 file_stem: Some("foo"),
3603 extension: Some("txt")
3606 t!("\\\\?\\UNC\\server",
3607 iter: ["\\\\?\\UNC\\server"],
3617 iter: ["\\\\?\\UNC\\"],
3626 t!("\\\\?\\C:\\foo.txt",
3627 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3630 parent: Some("\\\\?\\C:\\"),
3631 file_name: Some("foo.txt"),
3632 file_stem: Some("foo"),
3633 extension: Some("txt")
3638 iter: ["\\\\?\\C:", "\\"],
3649 iter: ["\\\\?\\C:"],
3659 t!("\\\\?\\foo/bar",
3660 iter: ["\\\\?\\foo/bar"],
3671 iter: ["\\\\?\\C:/foo"],
3681 t!("\\\\.\\foo\\bar",
3682 iter: ["\\\\.\\foo", "\\", "bar"],
3685 parent: Some("\\\\.\\foo\\"),
3686 file_name: Some("bar"),
3687 file_stem: Some("bar"),
3693 iter: ["\\\\.\\foo", "\\"],
3703 t!("\\\\.\\foo/bar",
3704 iter: ["\\\\.\\foo/bar", "\\"],
3714 t!("\\\\.\\foo\\bar/baz",
3715 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3718 parent: Some("\\\\.\\foo\\bar"),
3719 file_name: Some("baz"),
3720 file_stem: Some("baz"),
3726 iter: ["\\\\.\\", "\\"],
3736 iter: ["\\\\?\\a", "\\", "b"],
3739 parent: Some("\\\\?\\a\\"),
3740 file_name: Some("b"),
3741 file_stem: Some("b"),
3747 pub fn test_stem_ext() {
3749 file_stem: Some("foo"),
3754 file_stem: Some("foo"),
3759 file_stem: Some(".foo"),
3764 file_stem: Some("foo"),
3765 extension: Some("txt")
3769 file_stem: Some("foo.bar"),
3770 extension: Some("txt")
3774 file_stem: Some("foo.bar"),
3795 pub fn test_push() {
3797 ($path:expr, $push:expr, $expected:expr) => ( {
3798 let mut actual = PathBuf::from($path);
3800 assert!(actual.to_str() == Some($expected),
3801 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3802 $push, $path, $expected, actual.to_str().unwrap());
3806 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3807 tp!("", "foo", "foo");
3808 tp!("foo", "bar", "foo/bar");
3809 tp!("foo/", "bar", "foo/bar");
3810 tp!("foo//", "bar", "foo//bar");
3811 tp!("foo/.", "bar", "foo/./bar");
3812 tp!("foo./.", "bar", "foo././bar");
3813 tp!("foo", "", "foo/");
3814 tp!("foo", ".", "foo/.");
3815 tp!("foo", "..", "foo/..");
3816 tp!("foo", "/", "/");
3817 tp!("/foo/bar", "/", "/");
3818 tp!("/foo/bar", "/baz", "/baz");
3819 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3821 tp!("", "foo", "foo");
3822 tp!("foo", "bar", r"foo\bar");
3823 tp!("foo/", "bar", r"foo/bar");
3824 tp!(r"foo\", "bar", r"foo\bar");
3825 tp!("foo//", "bar", r"foo//bar");
3826 tp!(r"foo\\", "bar", r"foo\\bar");
3827 tp!("foo/.", "bar", r"foo/.\bar");
3828 tp!("foo./.", "bar", r"foo./.\bar");
3829 tp!(r"foo\.", "bar", r"foo\.\bar");
3830 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3831 tp!("foo", "", "foo\\");
3832 tp!("foo", ".", r"foo\.");
3833 tp!("foo", "..", r"foo\..");
3834 tp!("foo", "/", "/");
3835 tp!("foo", r"\", r"\");
3836 tp!("/foo/bar", "/", "/");
3837 tp!(r"\foo\bar", r"\", r"\");
3838 tp!("/foo/bar", "/baz", "/baz");
3839 tp!("/foo/bar", r"\baz", r"\baz");
3840 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3841 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3843 tp!("c:\\", "windows", "c:\\windows");
3844 tp!("c:", "windows", "c:windows");
3846 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3847 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3848 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3849 tp!("a\\b", "\\c\\d", "\\c\\d");
3850 tp!("a\\b", ".", "a\\b\\.");
3851 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3852 tp!("a\\b", "C:a.txt", "C:a.txt");
3853 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3854 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3855 tp!("C:\\a\\b\\c", "C:d", "C:d");
3856 tp!("C:a\\b\\c", "C:d", "C:d");
3857 tp!("C:", r"a\b\c", r"C:a\b\c");
3858 tp!("C:", r"..\a", r"C:..\a");
3859 tp!("\\\\server\\share\\foo",
3861 "\\\\server\\share\\foo\\bar");
3862 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3863 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3864 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3865 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3866 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3867 tp!("\\\\?\\UNC\\server\\share\\foo",
3869 "\\\\?\\UNC\\server\\share\\foo\\bar");
3870 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3871 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3873 // Note: modified from old path API
3874 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3877 "\\\\?\\UNC\\server\\share",
3878 "\\\\?\\UNC\\server\\share");
3879 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3880 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3881 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3882 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3884 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3891 ($path:expr, $expected:expr, $output:expr) => ( {
3892 let mut actual = PathBuf::from($path);
3893 let output = actual.pop();
3894 assert!(actual.to_str() == Some($expected) && output == $output,
3895 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3896 $path, $expected, $output,
3897 actual.to_str().unwrap(), output);
3902 tp!("/", "/", false);
3903 tp!("foo", "", true);
3905 tp!("/foo", "/", true);
3906 tp!("/foo/bar", "/foo", true);
3907 tp!("foo/bar", "foo", true);
3908 tp!("foo/.", "", true);
3909 tp!("foo//bar", "foo", true);
3912 tp!("a\\b\\c", "a\\b", true);
3913 tp!("\\a", "\\", true);
3914 tp!("\\", "\\", false);
3916 tp!("C:\\a\\b", "C:\\a", true);
3917 tp!("C:\\a", "C:\\", true);
3918 tp!("C:\\", "C:\\", false);
3919 tp!("C:a\\b", "C:a", true);
3920 tp!("C:a", "C:", true);
3921 tp!("C:", "C:", false);
3922 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3923 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3924 tp!("\\\\server\\share", "\\\\server\\share", false);
3925 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3926 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3927 tp!("\\\\?\\a", "\\\\?\\a", false);
3928 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3929 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3930 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3931 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3932 "\\\\?\\UNC\\server\\share\\a",
3934 tp!("\\\\?\\UNC\\server\\share\\a",
3935 "\\\\?\\UNC\\server\\share\\",
3937 tp!("\\\\?\\UNC\\server\\share",
3938 "\\\\?\\UNC\\server\\share",
3940 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3941 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3942 tp!("\\\\.\\a", "\\\\.\\a", false);
3944 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3949 pub fn test_set_file_name() {
3951 ($path:expr, $file:expr, $expected:expr) => ( {
3952 let mut p = PathBuf::from($path);
3953 p.set_file_name($file);
3954 assert!(p.to_str() == Some($expected),
3955 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3956 $path, $file, $expected,
3957 p.to_str().unwrap());
3961 tfn!("foo", "foo", "foo");
3962 tfn!("foo", "bar", "bar");
3963 tfn!("foo", "", "");
3964 tfn!("", "foo", "foo");
3965 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3966 tfn!(".", "foo", "./foo");
3967 tfn!("foo/", "bar", "bar");
3968 tfn!("foo/.", "bar", "bar");
3969 tfn!("..", "foo", "../foo");
3970 tfn!("foo/..", "bar", "foo/../bar");
3971 tfn!("/", "foo", "/foo");
3973 tfn!(".", "foo", r".\foo");
3974 tfn!(r"foo\", "bar", r"bar");
3975 tfn!(r"foo\.", "bar", r"bar");
3976 tfn!("..", "foo", r"..\foo");
3977 tfn!(r"foo\..", "bar", r"foo\..\bar");
3978 tfn!(r"\", "foo", r"\foo");
3983 pub fn test_set_extension() {
3985 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3986 let mut p = PathBuf::from($path);
3987 let output = p.set_extension($ext);
3988 assert!(p.to_str() == Some($expected) && output == $output,
3989 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3990 $path, $ext, $expected, $output,
3991 p.to_str().unwrap(), output);
3995 tfe!("foo", "txt", "foo.txt", true);
3996 tfe!("foo.bar", "txt", "foo.txt", true);
3997 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3998 tfe!(".test", "txt", ".test.txt", true);
3999 tfe!("foo.txt", "", "foo", true);
4000 tfe!("foo", "", "foo", true);
4001 tfe!("", "foo", "", false);
4002 tfe!(".", "foo", ".", false);
4003 tfe!("foo/", "bar", "foo.bar", true);
4004 tfe!("foo/.", "bar", "foo.bar", true);
4005 tfe!("..", "foo", "..", false);
4006 tfe!("foo/..", "bar", "foo/..", false);
4007 tfe!("/", "foo", "/", false);
4011 fn test_eq_receivers() {
4012 use crate::borrow::Cow;
4014 let borrowed: &Path = Path::new("foo/bar");
4015 let mut owned: PathBuf = PathBuf::new();
4018 let borrowed_cow: Cow<'_, Path> = borrowed.into();
4019 let owned_cow: Cow<'_, Path> = owned.clone().into();
4022 ($($current:expr),+) => {
4024 assert_eq!($current, borrowed);
4025 assert_eq!($current, owned);
4026 assert_eq!($current, borrowed_cow);
4027 assert_eq!($current, owned_cow);
4032 t!(borrowed, owned, borrowed_cow, owned_cow);
4036 pub fn test_compare() {
4037 use crate::hash::{Hash, Hasher};
4038 use crate::collections::hash_map::DefaultHasher;
4040 fn hash<T: Hash>(t: T) -> u64 {
4041 let mut s = DefaultHasher::new();
4047 ($path1:expr, $path2:expr, eq: $eq:expr,
4048 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4049 relative_from: $relative_from:expr) => ({
4050 let path1 = Path::new($path1);
4051 let path2 = Path::new($path2);
4053 let eq = path1 == path2;
4054 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4055 $path1, $path2, $eq, eq);
4056 assert!($eq == (hash(path1) == hash(path2)),
4057 "{:?} == {:?}, expected {:?}, got {} and {}",
4058 $path1, $path2, $eq, hash(path1), hash(path2));
4060 let starts_with = path1.starts_with(path2);
4061 assert!(starts_with == $starts_with,
4062 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4063 $starts_with, starts_with);
4065 let ends_with = path1.ends_with(path2);
4066 assert!(ends_with == $ends_with,
4067 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4068 $ends_with, ends_with);
4070 let relative_from = path1.strip_prefix(path2)
4071 .map(|p| p.to_str().unwrap())
4073 let exp: Option<&str> = $relative_from;
4074 assert!(relative_from == exp,
4075 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4076 $path1, $path2, exp, relative_from);
4084 relative_from: Some("")
4091 relative_from: Some("foo")
4105 relative_from: Some("")
4112 relative_from: Some("")
4115 tc!("foo/bar", "foo",
4119 relative_from: Some("bar")
4122 tc!("foo/bar/baz", "foo/bar",
4126 relative_from: Some("baz")
4129 tc!("foo/bar", "foo/bar/baz",
4136 tc!("./foo/bar/", ".",
4140 relative_from: Some("foo/bar")
4144 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4145 r"c:\src\rust\cargo-test\test",
4149 relative_from: Some("Cargo.toml")
4152 tc!(r"c:\foo", r"C:\foo",
4156 relative_from: Some("")
4162 fn test_components_debug() {
4163 let path = Path::new("/tmp");
4165 let mut components = path.components();
4167 let expected = "Components([RootDir, Normal(\"tmp\")])";
4168 let actual = format!("{:?}", components);
4169 assert_eq!(expected, actual);
4171 let _ = components.next().unwrap();
4172 let expected = "Components([Normal(\"tmp\")])";
4173 let actual = format!("{:?}", components);
4174 assert_eq!(expected, actual);
4176 let _ = components.next().unwrap();
4177 let expected = "Components([])";
4178 let actual = format!("{:?}", components);
4179 assert_eq!(expected, actual);
4184 fn test_iter_debug() {
4185 let path = Path::new("/tmp");
4187 let mut iter = path.iter();
4189 let expected = "Iter([\"/\", \"tmp\"])";
4190 let actual = format!("{:?}", iter);
4191 assert_eq!(expected, actual);
4193 let _ = iter.next().unwrap();
4194 let expected = "Iter([\"tmp\"])";
4195 let actual = format!("{:?}", iter);
4196 assert_eq!(expected, actual);
4198 let _ = iter.next().unwrap();
4199 let expected = "Iter([])";
4200 let actual = format!("{:?}", iter);
4201 assert_eq!(expected, actual);
4206 let orig: &str = "some/sort/of/path";
4207 let path = Path::new(orig);
4208 let boxed: Box<Path> = Box::from(path);
4209 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4210 assert_eq!(path, &*boxed);
4211 assert_eq!(&*boxed, &*path_buf);
4212 assert_eq!(&*path_buf, path);
4216 fn test_clone_into() {
4217 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4218 let path = Path::new("short");
4219 path.clone_into(&mut path_buf);
4220 assert_eq!(path, path_buf);
4221 assert!(path_buf.into_os_string().capacity() >= 15);
4225 fn display_format_flags() {
4226 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4227 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4232 let orig = "hello/world";
4233 let path = Path::new(orig);
4234 let rc: Rc<Path> = Rc::from(path);
4235 let arc: Arc<Path> = Arc::from(path);
4237 assert_eq!(&*rc, path);
4238 assert_eq!(&*arc, path);
4240 let rc2: Rc<Path> = Rc::from(path.to_owned());
4241 let arc2: Arc<Path> = Arc::from(path.to_owned());
4243 assert_eq!(&*rc2, path);
4244 assert_eq!(&*arc2, path);