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.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")]
1127 // `PathBuf::as_mut_vec` current implementation relies
1128 // on `PathBuf` being layout-compatible with `Vec<u8>`.
1129 // When attribute privacy is implemented, `PathBuf` should be annotated as `#[repr(transparent)]`.
1130 // Anyway, `PathBuf` representation and layout are considered implementation detail, are
1131 // not documented and must not be relied upon.
1132 pub struct PathBuf {
1137 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1138 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1141 /// Allocates an empty `PathBuf`.
1146 /// use std::path::PathBuf;
1148 /// let path = PathBuf::new();
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 pub fn new() -> PathBuf {
1152 PathBuf { inner: OsString::new() }
1155 /// Creates a new `PathBuf` with a given capacity used to create the
1156 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1161 /// #![feature(path_buf_capacity)]
1162 /// use std::path::PathBuf;
1164 /// let mut path = PathBuf::with_capacity(10);
1165 /// let capacity = path.capacity();
1167 /// // This push is done without reallocating
1168 /// path.push(r"C:\");
1170 /// assert_eq!(capacity, path.capacity());
1173 /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1174 /// [`OsString`]: ../ffi/struct.OsString.html
1175 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1176 pub fn with_capacity(capacity: usize) -> PathBuf {
1178 inner: OsString::with_capacity(capacity)
1182 /// Coerces to a [`Path`] slice.
1184 /// [`Path`]: struct.Path.html
1189 /// use std::path::{Path, PathBuf};
1191 /// let p = PathBuf::from("/test");
1192 /// assert_eq!(Path::new("/test"), p.as_path());
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 pub fn as_path(&self) -> &Path {
1199 /// Extends `self` with `path`.
1201 /// If `path` is absolute, it replaces the current path.
1205 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1206 /// replaces everything except for the prefix (if any) of `self`.
1207 /// * if `path` has a prefix but no root, it replaces `self`.
1211 /// Pushing a relative path extends the existing path:
1214 /// use std::path::PathBuf;
1216 /// let mut path = PathBuf::from("/tmp");
1217 /// path.push("file.bk");
1218 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1221 /// Pushing an absolute path replaces the existing path:
1224 /// use std::path::PathBuf;
1226 /// let mut path = PathBuf::from("/tmp");
1227 /// path.push("/etc");
1228 /// assert_eq!(path, PathBuf::from("/etc"));
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1232 self._push(path.as_ref())
1235 fn _push(&mut self, path: &Path) {
1236 // in general, a separator is needed if the rightmost byte is not a separator
1237 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1239 // in the special case of `C:` on Windows, do *not* add a separator
1241 let comps = self.components();
1242 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1243 comps.prefix.unwrap().is_drive() {
1248 // absolute `path` replaces `self`
1249 if path.is_absolute() || path.prefix().is_some() {
1250 self.as_mut_vec().truncate(0);
1252 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1253 } else if path.has_root() {
1254 let prefix_len = self.components().prefix_remaining();
1255 self.as_mut_vec().truncate(prefix_len);
1257 // `path` is a pure relative path
1258 } else if need_sep {
1259 self.inner.push(MAIN_SEP_STR);
1262 self.inner.push(path);
1265 /// Truncates `self` to [`self.parent`].
1267 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1268 /// Otherwise, returns `true`.
1270 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1271 /// [`self.parent`]: struct.PathBuf.html#method.parent
1276 /// use std::path::{Path, PathBuf};
1278 /// let mut p = PathBuf::from("/test/test.rs");
1281 /// assert_eq!(Path::new("/test"), p);
1283 /// assert_eq!(Path::new("/"), p);
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 pub fn pop(&mut self) -> bool {
1287 match self.parent().map(|p| p.as_u8_slice().len()) {
1289 self.as_mut_vec().truncate(len);
1296 /// Updates [`self.file_name`] to `file_name`.
1298 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1301 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1302 /// `file_name`. The new path will be a sibling of the original path.
1303 /// (That is, it will have the same parent.)
1305 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1306 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1307 /// [`pop`]: struct.PathBuf.html#method.pop
1312 /// use std::path::PathBuf;
1314 /// let mut buf = PathBuf::from("/");
1315 /// assert!(buf.file_name() == None);
1316 /// buf.set_file_name("bar");
1317 /// assert!(buf == PathBuf::from("/bar"));
1318 /// assert!(buf.file_name().is_some());
1319 /// buf.set_file_name("baz.txt");
1320 /// assert!(buf == PathBuf::from("/baz.txt"));
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1324 self._set_file_name(file_name.as_ref())
1327 fn _set_file_name(&mut self, file_name: &OsStr) {
1328 if self.file_name().is_some() {
1329 let popped = self.pop();
1330 debug_assert!(popped);
1332 self.push(file_name);
1335 /// Updates [`self.extension`] to `extension`.
1337 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1338 /// returns `true` and updates the extension otherwise.
1340 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1343 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1344 /// [`self.extension`]: struct.PathBuf.html#method.extension
1345 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1350 /// use std::path::{Path, PathBuf};
1352 /// let mut p = PathBuf::from("/feel/the");
1354 /// p.set_extension("force");
1355 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1357 /// p.set_extension("dark_side");
1358 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1362 self._set_extension(extension.as_ref())
1365 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1366 if self.file_name().is_none() {
1370 let mut stem = match self.file_stem() {
1371 Some(stem) => stem.to_os_string(),
1372 None => OsString::new(),
1375 if !os_str_as_u8_slice(extension).is_empty() {
1377 stem.push(extension);
1379 self.set_file_name(&stem);
1384 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1386 /// [`OsString`]: ../ffi/struct.OsString.html
1391 /// use std::path::PathBuf;
1393 /// let p = PathBuf::from("/the/head");
1394 /// let os_str = p.into_os_string();
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 pub fn into_os_string(self) -> OsString {
1401 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1403 /// [`Box`]: ../../std/boxed/struct.Box.html
1404 /// [`Path`]: struct.Path.html
1405 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1406 pub fn into_boxed_path(self) -> Box<Path> {
1407 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1408 unsafe { Box::from_raw(rw) }
1411 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1413 /// [`capacity`]: ../ffi/struct.OsString.html#method.capacity
1414 /// [`OsString`]: ../ffi/struct.OsString.html
1415 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1416 pub fn capacity(&self) -> usize {
1417 self.inner.capacity()
1420 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1422 /// [`clear`]: ../ffi/struct.OsString.html#method.clear
1423 /// [`OsString`]: ../ffi/struct.OsString.html
1424 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1425 pub fn clear(&mut self) {
1429 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1431 /// [`reserve`]: ../ffi/struct.OsString.html#method.reserve
1432 /// [`OsString`]: ../ffi/struct.OsString.html
1433 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1434 pub fn reserve(&mut self, additional: usize) {
1435 self.inner.reserve(additional)
1438 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1440 /// [`reserve_exact`]: ../ffi/struct.OsString.html#method.reserve_exact
1441 /// [`OsString`]: ../ffi/struct.OsString.html
1442 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1443 pub fn reserve_exact(&mut self, additional: usize) {
1444 self.inner.reserve_exact(additional)
1447 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1449 /// [`shrink_to_fit`]: ../ffi/struct.OsString.html#method.shrink_to_fit
1450 /// [`OsString`]: ../ffi/struct.OsString.html
1451 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1452 pub fn shrink_to_fit(&mut self) {
1453 self.inner.shrink_to_fit()
1456 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1458 /// [`shrink_to`]: ../ffi/struct.OsString.html#method.shrink_to
1459 /// [`OsString`]: ../ffi/struct.OsString.html
1460 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1461 pub fn shrink_to(&mut self, min_capacity: usize) {
1462 self.inner.shrink_to(min_capacity)
1466 #[stable(feature = "box_from_path", since = "1.17.0")]
1467 impl From<&Path> for Box<Path> {
1468 fn from(path: &Path) -> Box<Path> {
1469 let boxed: Box<OsStr> = path.inner.into();
1470 let rw = Box::into_raw(boxed) as *mut Path;
1471 unsafe { Box::from_raw(rw) }
1475 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1476 impl From<Box<Path>> for PathBuf {
1477 /// Converts a `Box<Path>` into a `PathBuf`
1479 /// This conversion does not allocate or copy memory.
1480 fn from(boxed: Box<Path>) -> PathBuf {
1481 boxed.into_path_buf()
1485 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1486 impl From<PathBuf> for Box<Path> {
1487 /// Converts a `PathBuf` into a `Box<Path>`
1489 /// This conversion currently should not allocate memory,
1490 /// but this behavior is not guaranteed on all platforms or in all future versions.
1491 fn from(p: PathBuf) -> Box<Path> {
1496 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1497 impl Clone for Box<Path> {
1499 fn clone(&self) -> Self {
1500 self.to_path_buf().into_boxed_path()
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1506 fn from(s: &T) -> PathBuf {
1507 PathBuf::from(s.as_ref().to_os_string())
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl From<OsString> for PathBuf {
1513 /// Converts a `OsString` into a `PathBuf`
1515 /// This conversion does not allocate or copy memory.
1516 fn from(s: OsString) -> PathBuf {
1517 PathBuf { inner: s }
1521 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1522 impl From<PathBuf> for OsString {
1523 /// Converts a `PathBuf` into a `OsString`
1525 /// This conversion does not allocate or copy memory.
1526 fn from(path_buf : PathBuf) -> OsString {
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 impl From<String> for PathBuf {
1533 /// Converts a `String` into a `PathBuf`
1535 /// This conversion does not allocate or copy memory.
1536 fn from(s: String) -> PathBuf {
1537 PathBuf::from(OsString::from(s))
1541 #[stable(feature = "path_from_str", since = "1.32.0")]
1542 impl FromStr for PathBuf {
1543 type Err = core::convert::Infallible;
1545 fn from_str(s: &str) -> Result<Self, Self::Err> {
1546 Ok(PathBuf::from(s))
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1552 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1553 let mut buf = PathBuf::new();
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1561 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1562 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 impl fmt::Debug for PathBuf {
1568 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1569 fmt::Debug::fmt(&**self, formatter)
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 impl ops::Deref for PathBuf {
1577 fn deref(&self) -> &Path {
1578 Path::new(&self.inner)
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl Borrow<Path> for PathBuf {
1584 fn borrow(&self) -> &Path {
1589 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1590 impl Default for PathBuf {
1591 fn default() -> Self {
1596 #[stable(feature = "cow_from_path", since = "1.6.0")]
1597 impl<'a> From<&'a Path> for Cow<'a, Path> {
1599 fn from(s: &'a Path) -> Cow<'a, Path> {
1604 #[stable(feature = "cow_from_path", since = "1.6.0")]
1605 impl<'a> From<PathBuf> for Cow<'a, Path> {
1607 fn from(s: PathBuf) -> Cow<'a, Path> {
1612 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1613 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1615 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1616 Cow::Borrowed(p.as_path())
1620 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1621 impl<'a> From<Cow<'a, Path>> for PathBuf {
1623 fn from(p: Cow<'a, Path>) -> Self {
1628 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1629 impl From<PathBuf> for Arc<Path> {
1630 /// Converts a `PathBuf` into an `Arc` by moving the `PathBuf` data into a new `Arc` buffer.
1632 fn from(s: PathBuf) -> Arc<Path> {
1633 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1634 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1638 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1639 impl From<&Path> for Arc<Path> {
1640 /// Converts a `Path` into an `Arc` by copying the `Path` data into a new `Arc` buffer.
1642 fn from(s: &Path) -> Arc<Path> {
1643 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1644 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1648 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1649 impl From<PathBuf> for Rc<Path> {
1650 /// Converts a `PathBuf` into an `Rc` by moving the `PathBuf` data into a new `Rc` buffer.
1652 fn from(s: PathBuf) -> Rc<Path> {
1653 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1654 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1658 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1659 impl From<&Path> for Rc<Path> {
1660 /// Converts a `Path` into an `Rc` by copying the `Path` data into a new `Rc` buffer.
1662 fn from(s: &Path) -> Rc<Path> {
1663 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1664 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl ToOwned for Path {
1670 type Owned = PathBuf;
1671 fn to_owned(&self) -> PathBuf {
1674 fn clone_into(&self, target: &mut PathBuf) {
1675 self.inner.clone_into(&mut target.inner);
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 impl cmp::PartialEq for PathBuf {
1681 fn eq(&self, other: &PathBuf) -> bool {
1682 self.components() == other.components()
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 impl Hash for PathBuf {
1688 fn hash<H: Hasher>(&self, h: &mut H) {
1689 self.as_path().hash(h)
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 impl cmp::Eq for PathBuf {}
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl cmp::PartialOrd for PathBuf {
1698 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1699 self.components().partial_cmp(other.components())
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 impl cmp::Ord for PathBuf {
1705 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1706 self.components().cmp(other.components())
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 impl AsRef<OsStr> for PathBuf {
1712 fn as_ref(&self) -> &OsStr {
1717 /// A slice of a path (akin to [`str`]).
1719 /// This type supports a number of operations for inspecting a path, including
1720 /// breaking the path into its components (separated by `/` on Unix and by either
1721 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1722 /// is absolute, and so on.
1724 /// This is an *unsized* type, meaning that it must always be used behind a
1725 /// pointer like `&` or [`Box`]. For an owned version of this type,
1726 /// see [`PathBuf`].
1728 /// [`str`]: ../primitive.str.html
1729 /// [`Box`]: ../boxed/struct.Box.html
1730 /// [`PathBuf`]: struct.PathBuf.html
1732 /// More details about the overall approach can be found in
1733 /// the [module documentation](index.html).
1738 /// use std::path::Path;
1739 /// use std::ffi::OsStr;
1741 /// // Note: this example does work on Windows
1742 /// let path = Path::new("./foo/bar.txt");
1744 /// let parent = path.parent();
1745 /// assert_eq!(parent, Some(Path::new("./foo")));
1747 /// let file_stem = path.file_stem();
1748 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1750 /// let extension = path.extension();
1751 /// assert_eq!(extension, Some(OsStr::new("txt")));
1753 #[stable(feature = "rust1", since = "1.0.0")]
1755 // `Path::new` current implementation relies
1756 // on `Path` being layout-compatible with `OsStr`.
1757 // When attribute privacy is implemented, `Path` should be annotated as `#[repr(transparent)]`.
1758 // Anyway, `Path` representation and layout are considered implementation detail, are
1759 // not documented and must not be relied upon.
1764 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1767 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1768 /// See its documentation for more.
1770 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1771 /// [`Path`]: struct.Path.html
1772 #[derive(Debug, Clone, PartialEq, Eq)]
1773 #[stable(since = "1.7.0", feature = "strip_prefix")]
1774 pub struct StripPrefixError(());
1777 // The following (private!) function allows construction of a path from a u8
1778 // slice, which is only safe when it is known to follow the OsStr encoding.
1779 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1780 Path::new(u8_slice_as_os_str(s))
1782 // The following (private!) function reveals the byte encoding used for OsStr.
1783 fn as_u8_slice(&self) -> &[u8] {
1784 os_str_as_u8_slice(&self.inner)
1787 /// Directly wraps a string slice as a `Path` slice.
1789 /// This is a cost-free conversion.
1794 /// use std::path::Path;
1796 /// Path::new("foo.txt");
1799 /// You can create `Path`s from `String`s, or even other `Path`s:
1802 /// use std::path::Path;
1804 /// let string = String::from("foo.txt");
1805 /// let from_string = Path::new(&string);
1806 /// let from_path = Path::new(&from_string);
1807 /// assert_eq!(from_string, from_path);
1809 #[stable(feature = "rust1", since = "1.0.0")]
1810 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1811 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1814 /// Yields the underlying [`OsStr`] slice.
1816 /// [`OsStr`]: ../ffi/struct.OsStr.html
1821 /// use std::path::Path;
1823 /// let os_str = Path::new("foo.txt").as_os_str();
1824 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 pub fn as_os_str(&self) -> &OsStr {
1831 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1833 /// This conversion may entail doing a check for UTF-8 validity.
1834 /// Note that validation is performed because non-UTF-8 strings are
1835 /// perfectly valid for some OS.
1837 /// [`&str`]: ../primitive.str.html
1842 /// use std::path::Path;
1844 /// let path = Path::new("foo.txt");
1845 /// assert_eq!(path.to_str(), Some("foo.txt"));
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 pub fn to_str(&self) -> Option<&str> {
1852 /// Converts a `Path` to a [`Cow<str>`].
1854 /// Any non-Unicode sequences are replaced with
1855 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1857 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1858 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1862 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1865 /// use std::path::Path;
1867 /// let path = Path::new("foo.txt");
1868 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1871 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1872 /// have returned `"fo�.txt"`.
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 pub fn to_string_lossy(&self) -> Cow<'_, str> {
1875 self.inner.to_string_lossy()
1878 /// Converts a `Path` to an owned [`PathBuf`].
1880 /// [`PathBuf`]: struct.PathBuf.html
1885 /// use std::path::Path;
1887 /// let path_buf = Path::new("foo.txt").to_path_buf();
1888 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1890 #[rustc_conversion_suggestion]
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 pub fn to_path_buf(&self) -> PathBuf {
1893 PathBuf::from(self.inner.to_os_string())
1896 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1897 /// the current directory.
1899 /// * On Unix, a path is absolute if it starts with the root, so
1900 /// `is_absolute` and [`has_root`] are equivalent.
1902 /// * On Windows, a path is absolute if it has a prefix and starts with the
1903 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1908 /// use std::path::Path;
1910 /// assert!(!Path::new("foo.txt").is_absolute());
1913 /// [`has_root`]: #method.has_root
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 #[allow(deprecated)]
1916 pub fn is_absolute(&self) -> bool {
1917 if cfg!(target_os = "redox") {
1918 // FIXME: Allow Redox prefixes
1919 self.has_root() || has_redox_scheme(self.as_u8_slice())
1921 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1925 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1927 /// See [`is_absolute`]'s documentation for more details.
1932 /// use std::path::Path;
1934 /// assert!(Path::new("foo.txt").is_relative());
1937 /// [`is_absolute`]: #method.is_absolute
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 pub fn is_relative(&self) -> bool {
1943 fn prefix(&self) -> Option<Prefix<'_>> {
1944 self.components().prefix
1947 /// Returns `true` if the `Path` has a root.
1949 /// * On Unix, a path has a root if it begins with `/`.
1951 /// * On Windows, a path has a root if it:
1952 /// * has no prefix and begins with a separator, e.g., `\windows`
1953 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1954 /// * has any non-disk prefix, e.g., `\\server\share`
1959 /// use std::path::Path;
1961 /// assert!(Path::new("/etc/passwd").has_root());
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 pub fn has_root(&self) -> bool {
1965 self.components().has_root()
1968 /// Returns the `Path` without its final component, if there is one.
1970 /// Returns [`None`] if the path terminates in a root or prefix.
1972 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1977 /// use std::path::Path;
1979 /// let path = Path::new("/foo/bar");
1980 /// let parent = path.parent().unwrap();
1981 /// assert_eq!(parent, Path::new("/foo"));
1983 /// let grand_parent = parent.parent().unwrap();
1984 /// assert_eq!(grand_parent, Path::new("/"));
1985 /// assert_eq!(grand_parent.parent(), None);
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 pub fn parent(&self) -> Option<&Path> {
1989 let mut comps = self.components();
1990 let comp = comps.next_back();
1993 Component::Normal(_) |
1995 Component::ParentDir => Some(comps.as_path()),
2001 /// Produces an iterator over `Path` and its ancestors.
2003 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
2004 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
2005 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
2006 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
2012 /// use std::path::Path;
2014 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2015 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2016 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2017 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2018 /// assert_eq!(ancestors.next(), None);
2021 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2022 /// [`parent`]: struct.Path.html#method.parent
2023 #[stable(feature = "path_ancestors", since = "1.28.0")]
2024 pub fn ancestors(&self) -> Ancestors<'_> {
2030 /// Returns the final component of the `Path`, if there is one.
2032 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2033 /// is the directory name.
2035 /// Returns [`None`] if the path terminates in `..`.
2037 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2042 /// use std::path::Path;
2043 /// use std::ffi::OsStr;
2045 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2046 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2047 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2048 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2049 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2050 /// assert_eq!(None, Path::new("/").file_name());
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 pub fn file_name(&self) -> Option<&OsStr> {
2054 self.components().next_back().and_then(|p| {
2056 Component::Normal(p) => Some(p.as_ref()),
2062 /// Returns a path that, when joined onto `base`, yields `self`.
2066 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2067 /// returns `false`), returns [`Err`].
2069 /// [`starts_with`]: #method.starts_with
2070 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2075 /// use std::path::{Path, PathBuf};
2077 /// let path = Path::new("/test/haha/foo.txt");
2079 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2080 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2081 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2082 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2083 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2084 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2085 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2087 /// let prefix = PathBuf::from("/test/");
2088 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2090 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2091 pub fn strip_prefix<P>(&self, base: P)
2092 -> Result<&Path, StripPrefixError>
2093 where P: AsRef<Path>
2095 self._strip_prefix(base.as_ref())
2098 fn _strip_prefix(&self, base: &Path)
2099 -> Result<&Path, StripPrefixError> {
2100 iter_after(self.components(), base.components())
2101 .map(|c| c.as_path())
2102 .ok_or(StripPrefixError(()))
2105 /// Determines whether `base` is a prefix of `self`.
2107 /// Only considers whole path components to match.
2112 /// use std::path::Path;
2114 /// let path = Path::new("/etc/passwd");
2116 /// assert!(path.starts_with("/etc"));
2117 /// assert!(path.starts_with("/etc/"));
2118 /// assert!(path.starts_with("/etc/passwd"));
2119 /// assert!(path.starts_with("/etc/passwd/"));
2121 /// assert!(!path.starts_with("/e"));
2123 #[stable(feature = "rust1", since = "1.0.0")]
2124 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2125 self._starts_with(base.as_ref())
2128 fn _starts_with(&self, base: &Path) -> bool {
2129 iter_after(self.components(), base.components()).is_some()
2132 /// Determines whether `child` is a suffix of `self`.
2134 /// Only considers whole path components to match.
2139 /// use std::path::Path;
2141 /// let path = Path::new("/etc/passwd");
2143 /// assert!(path.ends_with("passwd"));
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2147 self._ends_with(child.as_ref())
2150 fn _ends_with(&self, child: &Path) -> bool {
2151 iter_after(self.components().rev(), child.components().rev()).is_some()
2154 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2156 /// [`self.file_name`]: struct.Path.html#method.file_name
2160 /// * [`None`], if there is no file name;
2161 /// * The entire file name if there is no embedded `.`;
2162 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2163 /// * Otherwise, the portion of the file name before the final `.`
2165 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2170 /// use std::path::Path;
2172 /// let path = Path::new("foo.rs");
2174 /// assert_eq!("foo", path.file_stem().unwrap());
2176 #[stable(feature = "rust1", since = "1.0.0")]
2177 pub fn file_stem(&self) -> Option<&OsStr> {
2178 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2181 /// Extracts the extension of [`self.file_name`], if possible.
2183 /// The extension is:
2185 /// * [`None`], if there is no file name;
2186 /// * [`None`], if there is no embedded `.`;
2187 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2188 /// * Otherwise, the portion of the file name after the final `.`
2190 /// [`self.file_name`]: struct.Path.html#method.file_name
2191 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2196 /// use std::path::Path;
2198 /// let path = Path::new("foo.rs");
2200 /// assert_eq!("rs", path.extension().unwrap());
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 pub fn extension(&self) -> Option<&OsStr> {
2204 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2207 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2209 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2211 /// [`PathBuf`]: struct.PathBuf.html
2212 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2217 /// use std::path::{Path, PathBuf};
2219 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2221 #[stable(feature = "rust1", since = "1.0.0")]
2223 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2224 self._join(path.as_ref())
2227 fn _join(&self, path: &Path) -> PathBuf {
2228 let mut buf = self.to_path_buf();
2233 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2235 /// See [`PathBuf::set_file_name`] for more details.
2237 /// [`PathBuf`]: struct.PathBuf.html
2238 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2243 /// use std::path::{Path, PathBuf};
2245 /// let path = Path::new("/tmp/foo.txt");
2246 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2248 /// let path = Path::new("/tmp");
2249 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2251 #[stable(feature = "rust1", since = "1.0.0")]
2252 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2253 self._with_file_name(file_name.as_ref())
2256 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2257 let mut buf = self.to_path_buf();
2258 buf.set_file_name(file_name);
2262 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2264 /// See [`PathBuf::set_extension`] for more details.
2266 /// [`PathBuf`]: struct.PathBuf.html
2267 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2272 /// use std::path::{Path, PathBuf};
2274 /// let path = Path::new("foo.rs");
2275 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2277 #[stable(feature = "rust1", since = "1.0.0")]
2278 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2279 self._with_extension(extension.as_ref())
2282 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2283 let mut buf = self.to_path_buf();
2284 buf.set_extension(extension);
2288 /// Produces an iterator over the [`Component`]s of the path.
2290 /// When parsing the path, there is a small amount of normalization:
2292 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2293 /// `a` and `b` as components.
2295 /// * Occurrences of `.` are normalized away, except if they are at the
2296 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2297 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2298 /// an additional [`CurDir`] component.
2300 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2302 /// Note that no other normalization takes place; in particular, `a/c`
2303 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2304 /// is a symbolic link (so its parent isn't `a`).
2309 /// use std::path::{Path, Component};
2310 /// use std::ffi::OsStr;
2312 /// let mut components = Path::new("/tmp/foo.txt").components();
2314 /// assert_eq!(components.next(), Some(Component::RootDir));
2315 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2316 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2317 /// assert_eq!(components.next(), None)
2320 /// [`Component`]: enum.Component.html
2321 /// [`CurDir`]: enum.Component.html#variant.CurDir
2322 #[stable(feature = "rust1", since = "1.0.0")]
2323 pub fn components(&self) -> Components<'_> {
2324 let prefix = parse_prefix(self.as_os_str());
2326 path: self.as_u8_slice(),
2328 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2329 has_redox_scheme(self.as_u8_slice()),
2330 front: State::Prefix,
2335 /// Produces an iterator over the path's components viewed as [`OsStr`]
2338 /// For more information about the particulars of how the path is separated
2339 /// into components, see [`components`].
2341 /// [`components`]: #method.components
2342 /// [`OsStr`]: ../ffi/struct.OsStr.html
2347 /// use std::path::{self, Path};
2348 /// use std::ffi::OsStr;
2350 /// let mut it = Path::new("/tmp/foo.txt").iter();
2351 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2352 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2353 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2354 /// assert_eq!(it.next(), None)
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 pub fn iter(&self) -> Iter<'_> {
2358 Iter { inner: self.components() }
2361 /// Returns an object that implements [`Display`] for safely printing paths
2362 /// that may contain non-Unicode data.
2364 /// [`Display`]: ../fmt/trait.Display.html
2369 /// use std::path::Path;
2371 /// let path = Path::new("/tmp/foo.rs");
2373 /// println!("{}", path.display());
2375 #[stable(feature = "rust1", since = "1.0.0")]
2376 pub fn display(&self) -> Display<'_> {
2377 Display { path: self }
2380 /// Queries the file system to get information about a file, directory, etc.
2382 /// This function will traverse symbolic links to query information about the
2383 /// destination file.
2385 /// This is an alias to [`fs::metadata`].
2387 /// [`fs::metadata`]: ../fs/fn.metadata.html
2392 /// use std::path::Path;
2394 /// let path = Path::new("/Minas/tirith");
2395 /// let metadata = path.metadata().expect("metadata call failed");
2396 /// println!("{:?}", metadata.file_type());
2398 #[stable(feature = "path_ext", since = "1.5.0")]
2399 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2403 /// Queries the metadata about a file without following symlinks.
2405 /// This is an alias to [`fs::symlink_metadata`].
2407 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2412 /// use std::path::Path;
2414 /// let path = Path::new("/Minas/tirith");
2415 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2416 /// println!("{:?}", metadata.file_type());
2418 #[stable(feature = "path_ext", since = "1.5.0")]
2419 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2420 fs::symlink_metadata(self)
2423 /// Returns the canonical, absolute form of the path with all intermediate
2424 /// components normalized and symbolic links resolved.
2426 /// This is an alias to [`fs::canonicalize`].
2428 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2433 /// use std::path::{Path, PathBuf};
2435 /// let path = Path::new("/foo/test/../test/bar.rs");
2436 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2438 #[stable(feature = "path_ext", since = "1.5.0")]
2439 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2440 fs::canonicalize(self)
2443 /// Reads a symbolic link, returning the file that the link points to.
2445 /// This is an alias to [`fs::read_link`].
2447 /// [`fs::read_link`]: ../fs/fn.read_link.html
2452 /// use std::path::Path;
2454 /// let path = Path::new("/laputa/sky_castle.rs");
2455 /// let path_link = path.read_link().expect("read_link call failed");
2457 #[stable(feature = "path_ext", since = "1.5.0")]
2458 pub fn read_link(&self) -> io::Result<PathBuf> {
2462 /// Returns an iterator over the entries within a directory.
2464 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2465 /// errors may be encountered after an iterator is initially constructed.
2467 /// This is an alias to [`fs::read_dir`].
2469 /// [`io::Result`]: ../io/type.Result.html
2470 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2471 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2476 /// use std::path::Path;
2478 /// let path = Path::new("/laputa");
2479 /// for entry in path.read_dir().expect("read_dir call failed") {
2480 /// if let Ok(entry) = entry {
2481 /// println!("{:?}", entry.path());
2485 #[stable(feature = "path_ext", since = "1.5.0")]
2486 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2490 /// Returns `true` if the path points at an existing entity.
2492 /// This function will traverse symbolic links to query information about the
2493 /// destination file. In case of broken symbolic links this will return `false`.
2495 /// If you cannot access the directory containing the file, e.g., because of a
2496 /// permission error, this will return `false`.
2501 /// use std::path::Path;
2502 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2507 /// This is a convenience function that coerces errors to false. If you want to
2508 /// check errors, call [fs::metadata].
2510 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2511 #[stable(feature = "path_ext", since = "1.5.0")]
2512 pub fn exists(&self) -> bool {
2513 fs::metadata(self).is_ok()
2516 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2518 /// This function will traverse symbolic links to query information about the
2519 /// destination file. In case of broken symbolic links this will return `false`.
2521 /// If you cannot access the directory containing the file, e.g., because of a
2522 /// permission error, this will return `false`.
2527 /// use std::path::Path;
2528 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2529 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2534 /// This is a convenience function that coerces errors to false. If you want to
2535 /// check errors, call [fs::metadata] and handle its Result. Then call
2536 /// [fs::Metadata::is_file] if it was Ok.
2538 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2539 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2540 #[stable(feature = "path_ext", since = "1.5.0")]
2541 pub fn is_file(&self) -> bool {
2542 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2545 /// Returns `true` if the path exists on disk and is pointing at a directory.
2547 /// This function will traverse symbolic links to query information about the
2548 /// destination file. In case of broken symbolic links this will return `false`.
2550 /// If you cannot access the directory containing the file, e.g., because of a
2551 /// permission error, this will return `false`.
2556 /// use std::path::Path;
2557 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2558 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2563 /// This is a convenience function that coerces errors to false. If you want to
2564 /// check errors, call [fs::metadata] and handle its Result. Then call
2565 /// [fs::Metadata::is_dir] if it was Ok.
2567 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2568 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2569 #[stable(feature = "path_ext", since = "1.5.0")]
2570 pub fn is_dir(&self) -> bool {
2571 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2574 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2577 /// [`Box`]: ../../std/boxed/struct.Box.html
2578 /// [`PathBuf`]: struct.PathBuf.html
2579 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2580 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2581 let rw = Box::into_raw(self) as *mut OsStr;
2582 let inner = unsafe { Box::from_raw(rw) };
2583 PathBuf { inner: OsString::from(inner) }
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 impl AsRef<OsStr> for Path {
2589 fn as_ref(&self) -> &OsStr {
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 impl fmt::Debug for Path {
2596 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2597 fmt::Debug::fmt(&self.inner, formatter)
2601 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2603 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2604 /// [`Display`] trait in a way that mitigates that. It is created by the
2605 /// [`display`][`Path::display`] method on [`Path`].
2610 /// use std::path::Path;
2612 /// let path = Path::new("/tmp/foo.rs");
2614 /// println!("{}", path.display());
2617 /// [`Display`]: ../../std/fmt/trait.Display.html
2618 /// [`format!`]: ../../std/macro.format.html
2619 /// [`Path`]: struct.Path.html
2620 /// [`Path::display`]: struct.Path.html#method.display
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 pub struct Display<'a> {
2626 #[stable(feature = "rust1", since = "1.0.0")]
2627 impl fmt::Debug for Display<'_> {
2628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2629 fmt::Debug::fmt(&self.path, f)
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl fmt::Display for Display<'_> {
2635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2636 self.path.inner.display(f)
2640 #[stable(feature = "rust1", since = "1.0.0")]
2641 impl cmp::PartialEq for Path {
2642 fn eq(&self, other: &Path) -> bool {
2643 self.components().eq(other.components())
2647 #[stable(feature = "rust1", since = "1.0.0")]
2648 impl Hash for Path {
2649 fn hash<H: Hasher>(&self, h: &mut H) {
2650 for component in self.components() {
2656 #[stable(feature = "rust1", since = "1.0.0")]
2657 impl cmp::Eq for Path {}
2659 #[stable(feature = "rust1", since = "1.0.0")]
2660 impl cmp::PartialOrd for Path {
2661 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2662 self.components().partial_cmp(other.components())
2666 #[stable(feature = "rust1", since = "1.0.0")]
2667 impl cmp::Ord for Path {
2668 fn cmp(&self, other: &Path) -> cmp::Ordering {
2669 self.components().cmp(other.components())
2673 #[stable(feature = "rust1", since = "1.0.0")]
2674 impl AsRef<Path> for Path {
2675 fn as_ref(&self) -> &Path {
2680 #[stable(feature = "rust1", since = "1.0.0")]
2681 impl AsRef<Path> for OsStr {
2682 fn as_ref(&self) -> &Path {
2687 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2688 impl AsRef<Path> for Cow<'_, OsStr> {
2689 fn as_ref(&self) -> &Path {
2694 #[stable(feature = "rust1", since = "1.0.0")]
2695 impl AsRef<Path> for OsString {
2696 fn as_ref(&self) -> &Path {
2701 #[stable(feature = "rust1", since = "1.0.0")]
2702 impl AsRef<Path> for str {
2703 fn as_ref(&self) -> &Path {
2708 #[stable(feature = "rust1", since = "1.0.0")]
2709 impl AsRef<Path> for String {
2710 fn as_ref(&self) -> &Path {
2715 #[stable(feature = "rust1", since = "1.0.0")]
2716 impl AsRef<Path> for PathBuf {
2717 fn as_ref(&self) -> &Path {
2722 #[stable(feature = "path_into_iter", since = "1.6.0")]
2723 impl<'a> IntoIterator for &'a PathBuf {
2724 type Item = &'a OsStr;
2725 type IntoIter = Iter<'a>;
2726 fn into_iter(self) -> Iter<'a> { self.iter() }
2729 #[stable(feature = "path_into_iter", since = "1.6.0")]
2730 impl<'a> IntoIterator for &'a Path {
2731 type Item = &'a OsStr;
2732 type IntoIter = Iter<'a>;
2733 fn into_iter(self) -> Iter<'a> { self.iter() }
2736 macro_rules! impl_cmp {
2737 ($lhs:ty, $rhs: ty) => {
2738 #[stable(feature = "partialeq_path", since = "1.6.0")]
2739 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2741 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2744 #[stable(feature = "partialeq_path", since = "1.6.0")]
2745 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2747 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2750 #[stable(feature = "cmp_path", since = "1.8.0")]
2751 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2753 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2754 <Path as PartialOrd>::partial_cmp(self, other)
2758 #[stable(feature = "cmp_path", since = "1.8.0")]
2759 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2761 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2762 <Path as PartialOrd>::partial_cmp(self, other)
2768 impl_cmp!(PathBuf, Path);
2769 impl_cmp!(PathBuf, &'a Path);
2770 impl_cmp!(Cow<'a, Path>, Path);
2771 impl_cmp!(Cow<'a, Path>, &'b Path);
2772 impl_cmp!(Cow<'a, Path>, PathBuf);
2774 macro_rules! impl_cmp_os_str {
2775 ($lhs:ty, $rhs: ty) => {
2776 #[stable(feature = "cmp_path", since = "1.8.0")]
2777 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2779 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2782 #[stable(feature = "cmp_path", since = "1.8.0")]
2783 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2785 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2788 #[stable(feature = "cmp_path", since = "1.8.0")]
2789 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2791 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2792 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2796 #[stable(feature = "cmp_path", since = "1.8.0")]
2797 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2799 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2800 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2806 impl_cmp_os_str!(PathBuf, OsStr);
2807 impl_cmp_os_str!(PathBuf, &'a OsStr);
2808 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2809 impl_cmp_os_str!(PathBuf, OsString);
2810 impl_cmp_os_str!(Path, OsStr);
2811 impl_cmp_os_str!(Path, &'a OsStr);
2812 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2813 impl_cmp_os_str!(Path, OsString);
2814 impl_cmp_os_str!(&'a Path, OsStr);
2815 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2816 impl_cmp_os_str!(&'a Path, OsString);
2817 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2818 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2819 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2821 #[stable(since = "1.7.0", feature = "strip_prefix")]
2822 impl fmt::Display for StripPrefixError {
2823 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2824 self.description().fmt(f)
2828 #[stable(since = "1.7.0", feature = "strip_prefix")]
2829 impl Error for StripPrefixError {
2830 fn description(&self) -> &str { "prefix not found" }
2838 use crate::sync::Arc;
2841 ($path:expr, iter: $iter:expr) => (
2843 let path = Path::new($path);
2845 // Forward iteration
2846 let comps = path.iter()
2847 .map(|p| p.to_string_lossy().into_owned())
2848 .collect::<Vec<String>>();
2849 let exp: &[&str] = &$iter;
2850 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2851 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2854 // Reverse iteration
2855 let comps = Path::new($path).iter().rev()
2856 .map(|p| p.to_string_lossy().into_owned())
2857 .collect::<Vec<String>>();
2858 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2859 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2864 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2866 let path = Path::new($path);
2868 let act_root = path.has_root();
2869 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2870 $has_root, act_root);
2872 let act_abs = path.is_absolute();
2873 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2874 $is_absolute, act_abs);
2878 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2880 let path = Path::new($path);
2882 let parent = path.parent().map(|p| p.to_str().unwrap());
2883 let exp_parent: Option<&str> = $parent;
2884 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2885 exp_parent, parent);
2887 let file = path.file_name().map(|p| p.to_str().unwrap());
2888 let exp_file: Option<&str> = $file;
2889 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2894 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2896 let path = Path::new($path);
2898 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2899 let exp_stem: Option<&str> = $file_stem;
2900 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2903 let ext = path.extension().map(|p| p.to_str().unwrap());
2904 let exp_ext: Option<&str> = $extension;
2905 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2910 ($path:expr, iter: $iter:expr,
2911 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2912 parent: $parent:expr, file_name: $file:expr,
2913 file_stem: $file_stem:expr, extension: $extension:expr) => (
2915 t!($path, iter: $iter);
2916 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2917 t!($path, parent: $parent, file_name: $file);
2918 t!($path, file_stem: $file_stem, extension: $extension);
2925 use crate::borrow::Cow;
2927 let static_path = Path::new("/home/foo");
2928 let static_cow_path: Cow<'static, Path> = static_path.into();
2929 let pathbuf = PathBuf::from("/home/foo");
2932 let path: &Path = &pathbuf;
2933 let borrowed_cow_path: Cow<'_, Path> = path.into();
2935 assert_eq!(static_cow_path, borrowed_cow_path);
2938 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2940 assert_eq!(static_cow_path, owned_cow_path);
2945 pub fn test_decompositions_unix() {
2961 file_name: Some("foo"),
2962 file_stem: Some("foo"),
2981 file_name: Some("foo"),
2982 file_stem: Some("foo"),
2991 file_name: Some("foo"),
2992 file_stem: Some("foo"),
3001 file_name: Some("foo"),
3002 file_stem: Some("foo"),
3007 iter: ["foo", "bar"],
3010 parent: Some("foo"),
3011 file_name: Some("bar"),
3012 file_stem: Some("bar"),
3017 iter: ["/", "foo", "bar"],
3020 parent: Some("/foo"),
3021 file_name: Some("bar"),
3022 file_stem: Some("bar"),
3031 file_name: Some("foo"),
3032 file_stem: Some("foo"),
3037 iter: ["/", "foo", "bar"],
3040 parent: Some("///foo"),
3041 file_name: Some("bar"),
3042 file_stem: Some("bar"),
3081 file_name: Some("foo"),
3082 file_stem: Some("foo"),
3087 iter: ["foo", ".."],
3090 parent: Some("foo"),
3101 file_name: Some("foo"),
3102 file_stem: Some("foo"),
3107 iter: ["foo", "bar"],
3110 parent: Some("foo"),
3111 file_name: Some("bar"),
3112 file_stem: Some("bar"),
3117 iter: ["foo", ".."],
3120 parent: Some("foo"),
3127 iter: ["foo", "..", "bar"],
3130 parent: Some("foo/.."),
3131 file_name: Some("bar"),
3132 file_stem: Some("bar"),
3141 file_name: Some("a"),
3142 file_stem: Some("a"),
3171 file_name: Some("b"),
3172 file_stem: Some("b"),
3181 file_name: Some("b"),
3182 file_stem: Some("b"),
3191 file_name: Some("b"),
3192 file_stem: Some("b"),
3197 iter: ["a", "b", "c"],
3200 parent: Some("a/b"),
3201 file_name: Some("c"),
3202 file_stem: Some("c"),
3211 file_name: Some(".foo"),
3212 file_stem: Some(".foo"),
3219 pub fn test_decompositions_windows() {
3235 file_name: Some("foo"),
3236 file_stem: Some("foo"),
3291 iter: ["\\", "foo"],
3295 file_name: Some("foo"),
3296 file_stem: Some("foo"),
3305 file_name: Some("foo"),
3306 file_stem: Some("foo"),
3311 iter: ["\\", "foo"],
3315 file_name: Some("foo"),
3316 file_stem: Some("foo"),
3321 iter: ["foo", "bar"],
3324 parent: Some("foo"),
3325 file_name: Some("bar"),
3326 file_stem: Some("bar"),
3331 iter: ["\\", "foo", "bar"],
3334 parent: Some("/foo"),
3335 file_name: Some("bar"),
3336 file_stem: Some("bar"),
3341 iter: ["\\", "foo"],
3345 file_name: Some("foo"),
3346 file_stem: Some("foo"),
3351 iter: ["\\", "foo", "bar"],
3354 parent: Some("///foo"),
3355 file_name: Some("bar"),
3356 file_stem: Some("bar"),
3395 file_name: Some("foo"),
3396 file_stem: Some("foo"),
3401 iter: ["foo", ".."],
3404 parent: Some("foo"),
3415 file_name: Some("foo"),
3416 file_stem: Some("foo"),
3421 iter: ["foo", "bar"],
3424 parent: Some("foo"),
3425 file_name: Some("bar"),
3426 file_stem: Some("bar"),
3431 iter: ["foo", ".."],
3434 parent: Some("foo"),
3441 iter: ["foo", "..", "bar"],
3444 parent: Some("foo/.."),
3445 file_name: Some("bar"),
3446 file_stem: Some("bar"),
3455 file_name: Some("a"),
3456 file_stem: Some("a"),
3485 file_name: Some("b"),
3486 file_stem: Some("b"),
3495 file_name: Some("b"),
3496 file_stem: Some("b"),
3505 file_name: Some("b"),
3506 file_stem: Some("b"),
3511 iter: ["a", "b", "c"],
3514 parent: Some("a/b"),
3515 file_name: Some("c"),
3516 file_stem: Some("c"),
3520 iter: ["a", "b", "c"],
3523 parent: Some("a\\b"),
3524 file_name: Some("c"),
3525 file_stem: Some("c"),
3534 file_name: Some("a"),
3535 file_stem: Some("a"),
3540 iter: ["c:", "\\", "foo.txt"],
3543 parent: Some("c:\\"),
3544 file_name: Some("foo.txt"),
3545 file_stem: Some("foo"),
3546 extension: Some("txt")
3549 t!("\\\\server\\share\\foo.txt",
3550 iter: ["\\\\server\\share", "\\", "foo.txt"],
3553 parent: Some("\\\\server\\share\\"),
3554 file_name: Some("foo.txt"),
3555 file_stem: Some("foo"),
3556 extension: Some("txt")
3559 t!("\\\\server\\share",
3560 iter: ["\\\\server\\share", "\\"],
3570 iter: ["\\", "server"],
3574 file_name: Some("server"),
3575 file_stem: Some("server"),
3579 t!("\\\\?\\bar\\foo.txt",
3580 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3583 parent: Some("\\\\?\\bar\\"),
3584 file_name: Some("foo.txt"),
3585 file_stem: Some("foo"),
3586 extension: Some("txt")
3590 iter: ["\\\\?\\bar"],
3609 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3610 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3613 parent: Some("\\\\?\\UNC\\server\\share\\"),
3614 file_name: Some("foo.txt"),
3615 file_stem: Some("foo"),
3616 extension: Some("txt")
3619 t!("\\\\?\\UNC\\server",
3620 iter: ["\\\\?\\UNC\\server"],
3630 iter: ["\\\\?\\UNC\\"],
3639 t!("\\\\?\\C:\\foo.txt",
3640 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3643 parent: Some("\\\\?\\C:\\"),
3644 file_name: Some("foo.txt"),
3645 file_stem: Some("foo"),
3646 extension: Some("txt")
3651 iter: ["\\\\?\\C:", "\\"],
3662 iter: ["\\\\?\\C:"],
3672 t!("\\\\?\\foo/bar",
3673 iter: ["\\\\?\\foo/bar"],
3684 iter: ["\\\\?\\C:/foo"],
3694 t!("\\\\.\\foo\\bar",
3695 iter: ["\\\\.\\foo", "\\", "bar"],
3698 parent: Some("\\\\.\\foo\\"),
3699 file_name: Some("bar"),
3700 file_stem: Some("bar"),
3706 iter: ["\\\\.\\foo", "\\"],
3716 t!("\\\\.\\foo/bar",
3717 iter: ["\\\\.\\foo/bar", "\\"],
3727 t!("\\\\.\\foo\\bar/baz",
3728 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3731 parent: Some("\\\\.\\foo\\bar"),
3732 file_name: Some("baz"),
3733 file_stem: Some("baz"),
3739 iter: ["\\\\.\\", "\\"],
3749 iter: ["\\\\?\\a", "\\", "b"],
3752 parent: Some("\\\\?\\a\\"),
3753 file_name: Some("b"),
3754 file_stem: Some("b"),
3760 pub fn test_stem_ext() {
3762 file_stem: Some("foo"),
3767 file_stem: Some("foo"),
3772 file_stem: Some(".foo"),
3777 file_stem: Some("foo"),
3778 extension: Some("txt")
3782 file_stem: Some("foo.bar"),
3783 extension: Some("txt")
3787 file_stem: Some("foo.bar"),
3808 pub fn test_push() {
3810 ($path:expr, $push:expr, $expected:expr) => ( {
3811 let mut actual = PathBuf::from($path);
3813 assert!(actual.to_str() == Some($expected),
3814 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3815 $push, $path, $expected, actual.to_str().unwrap());
3819 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3820 tp!("", "foo", "foo");
3821 tp!("foo", "bar", "foo/bar");
3822 tp!("foo/", "bar", "foo/bar");
3823 tp!("foo//", "bar", "foo//bar");
3824 tp!("foo/.", "bar", "foo/./bar");
3825 tp!("foo./.", "bar", "foo././bar");
3826 tp!("foo", "", "foo/");
3827 tp!("foo", ".", "foo/.");
3828 tp!("foo", "..", "foo/..");
3829 tp!("foo", "/", "/");
3830 tp!("/foo/bar", "/", "/");
3831 tp!("/foo/bar", "/baz", "/baz");
3832 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3834 tp!("", "foo", "foo");
3835 tp!("foo", "bar", r"foo\bar");
3836 tp!("foo/", "bar", r"foo/bar");
3837 tp!(r"foo\", "bar", r"foo\bar");
3838 tp!("foo//", "bar", r"foo//bar");
3839 tp!(r"foo\\", "bar", r"foo\\bar");
3840 tp!("foo/.", "bar", r"foo/.\bar");
3841 tp!("foo./.", "bar", r"foo./.\bar");
3842 tp!(r"foo\.", "bar", r"foo\.\bar");
3843 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3844 tp!("foo", "", "foo\\");
3845 tp!("foo", ".", r"foo\.");
3846 tp!("foo", "..", r"foo\..");
3847 tp!("foo", "/", "/");
3848 tp!("foo", r"\", r"\");
3849 tp!("/foo/bar", "/", "/");
3850 tp!(r"\foo\bar", r"\", r"\");
3851 tp!("/foo/bar", "/baz", "/baz");
3852 tp!("/foo/bar", r"\baz", r"\baz");
3853 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3854 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3856 tp!("c:\\", "windows", "c:\\windows");
3857 tp!("c:", "windows", "c:windows");
3859 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3860 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3861 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3862 tp!("a\\b", "\\c\\d", "\\c\\d");
3863 tp!("a\\b", ".", "a\\b\\.");
3864 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3865 tp!("a\\b", "C:a.txt", "C:a.txt");
3866 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3867 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3868 tp!("C:\\a\\b\\c", "C:d", "C:d");
3869 tp!("C:a\\b\\c", "C:d", "C:d");
3870 tp!("C:", r"a\b\c", r"C:a\b\c");
3871 tp!("C:", r"..\a", r"C:..\a");
3872 tp!("\\\\server\\share\\foo",
3874 "\\\\server\\share\\foo\\bar");
3875 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3876 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3877 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3878 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3879 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3880 tp!("\\\\?\\UNC\\server\\share\\foo",
3882 "\\\\?\\UNC\\server\\share\\foo\\bar");
3883 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3884 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3886 // Note: modified from old path API
3887 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3890 "\\\\?\\UNC\\server\\share",
3891 "\\\\?\\UNC\\server\\share");
3892 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3893 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3894 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3895 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3897 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3904 ($path:expr, $expected:expr, $output:expr) => ( {
3905 let mut actual = PathBuf::from($path);
3906 let output = actual.pop();
3907 assert!(actual.to_str() == Some($expected) && output == $output,
3908 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3909 $path, $expected, $output,
3910 actual.to_str().unwrap(), output);
3915 tp!("/", "/", false);
3916 tp!("foo", "", true);
3918 tp!("/foo", "/", true);
3919 tp!("/foo/bar", "/foo", true);
3920 tp!("foo/bar", "foo", true);
3921 tp!("foo/.", "", true);
3922 tp!("foo//bar", "foo", true);
3925 tp!("a\\b\\c", "a\\b", true);
3926 tp!("\\a", "\\", true);
3927 tp!("\\", "\\", false);
3929 tp!("C:\\a\\b", "C:\\a", true);
3930 tp!("C:\\a", "C:\\", true);
3931 tp!("C:\\", "C:\\", false);
3932 tp!("C:a\\b", "C:a", true);
3933 tp!("C:a", "C:", true);
3934 tp!("C:", "C:", false);
3935 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3936 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3937 tp!("\\\\server\\share", "\\\\server\\share", false);
3938 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3939 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3940 tp!("\\\\?\\a", "\\\\?\\a", false);
3941 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3942 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3943 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3944 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3945 "\\\\?\\UNC\\server\\share\\a",
3947 tp!("\\\\?\\UNC\\server\\share\\a",
3948 "\\\\?\\UNC\\server\\share\\",
3950 tp!("\\\\?\\UNC\\server\\share",
3951 "\\\\?\\UNC\\server\\share",
3953 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3954 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3955 tp!("\\\\.\\a", "\\\\.\\a", false);
3957 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3962 pub fn test_set_file_name() {
3964 ($path:expr, $file:expr, $expected:expr) => ( {
3965 let mut p = PathBuf::from($path);
3966 p.set_file_name($file);
3967 assert!(p.to_str() == Some($expected),
3968 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3969 $path, $file, $expected,
3970 p.to_str().unwrap());
3974 tfn!("foo", "foo", "foo");
3975 tfn!("foo", "bar", "bar");
3976 tfn!("foo", "", "");
3977 tfn!("", "foo", "foo");
3978 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3979 tfn!(".", "foo", "./foo");
3980 tfn!("foo/", "bar", "bar");
3981 tfn!("foo/.", "bar", "bar");
3982 tfn!("..", "foo", "../foo");
3983 tfn!("foo/..", "bar", "foo/../bar");
3984 tfn!("/", "foo", "/foo");
3986 tfn!(".", "foo", r".\foo");
3987 tfn!(r"foo\", "bar", r"bar");
3988 tfn!(r"foo\.", "bar", r"bar");
3989 tfn!("..", "foo", r"..\foo");
3990 tfn!(r"foo\..", "bar", r"foo\..\bar");
3991 tfn!(r"\", "foo", r"\foo");
3996 pub fn test_set_extension() {
3998 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3999 let mut p = PathBuf::from($path);
4000 let output = p.set_extension($ext);
4001 assert!(p.to_str() == Some($expected) && output == $output,
4002 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
4003 $path, $ext, $expected, $output,
4004 p.to_str().unwrap(), output);
4008 tfe!("foo", "txt", "foo.txt", true);
4009 tfe!("foo.bar", "txt", "foo.txt", true);
4010 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
4011 tfe!(".test", "txt", ".test.txt", true);
4012 tfe!("foo.txt", "", "foo", true);
4013 tfe!("foo", "", "foo", true);
4014 tfe!("", "foo", "", false);
4015 tfe!(".", "foo", ".", false);
4016 tfe!("foo/", "bar", "foo.bar", true);
4017 tfe!("foo/.", "bar", "foo.bar", true);
4018 tfe!("..", "foo", "..", false);
4019 tfe!("foo/..", "bar", "foo/..", false);
4020 tfe!("/", "foo", "/", false);
4024 fn test_eq_receivers() {
4025 use crate::borrow::Cow;
4027 let borrowed: &Path = Path::new("foo/bar");
4028 let mut owned: PathBuf = PathBuf::new();
4031 let borrowed_cow: Cow<'_, Path> = borrowed.into();
4032 let owned_cow: Cow<'_, Path> = owned.clone().into();
4035 ($($current:expr),+) => {
4037 assert_eq!($current, borrowed);
4038 assert_eq!($current, owned);
4039 assert_eq!($current, borrowed_cow);
4040 assert_eq!($current, owned_cow);
4045 t!(borrowed, owned, borrowed_cow, owned_cow);
4049 pub fn test_compare() {
4050 use crate::hash::{Hash, Hasher};
4051 use crate::collections::hash_map::DefaultHasher;
4053 fn hash<T: Hash>(t: T) -> u64 {
4054 let mut s = DefaultHasher::new();
4060 ($path1:expr, $path2:expr, eq: $eq:expr,
4061 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4062 relative_from: $relative_from:expr) => ({
4063 let path1 = Path::new($path1);
4064 let path2 = Path::new($path2);
4066 let eq = path1 == path2;
4067 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4068 $path1, $path2, $eq, eq);
4069 assert!($eq == (hash(path1) == hash(path2)),
4070 "{:?} == {:?}, expected {:?}, got {} and {}",
4071 $path1, $path2, $eq, hash(path1), hash(path2));
4073 let starts_with = path1.starts_with(path2);
4074 assert!(starts_with == $starts_with,
4075 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4076 $starts_with, starts_with);
4078 let ends_with = path1.ends_with(path2);
4079 assert!(ends_with == $ends_with,
4080 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4081 $ends_with, ends_with);
4083 let relative_from = path1.strip_prefix(path2)
4084 .map(|p| p.to_str().unwrap())
4086 let exp: Option<&str> = $relative_from;
4087 assert!(relative_from == exp,
4088 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4089 $path1, $path2, exp, relative_from);
4097 relative_from: Some("")
4104 relative_from: Some("foo")
4118 relative_from: Some("")
4125 relative_from: Some("")
4128 tc!("foo/bar", "foo",
4132 relative_from: Some("bar")
4135 tc!("foo/bar/baz", "foo/bar",
4139 relative_from: Some("baz")
4142 tc!("foo/bar", "foo/bar/baz",
4149 tc!("./foo/bar/", ".",
4153 relative_from: Some("foo/bar")
4157 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4158 r"c:\src\rust\cargo-test\test",
4162 relative_from: Some("Cargo.toml")
4165 tc!(r"c:\foo", r"C:\foo",
4169 relative_from: Some("")
4175 fn test_components_debug() {
4176 let path = Path::new("/tmp");
4178 let mut components = path.components();
4180 let expected = "Components([RootDir, Normal(\"tmp\")])";
4181 let actual = format!("{:?}", components);
4182 assert_eq!(expected, actual);
4184 let _ = components.next().unwrap();
4185 let expected = "Components([Normal(\"tmp\")])";
4186 let actual = format!("{:?}", components);
4187 assert_eq!(expected, actual);
4189 let _ = components.next().unwrap();
4190 let expected = "Components([])";
4191 let actual = format!("{:?}", components);
4192 assert_eq!(expected, actual);
4197 fn test_iter_debug() {
4198 let path = Path::new("/tmp");
4200 let mut iter = path.iter();
4202 let expected = "Iter([\"/\", \"tmp\"])";
4203 let actual = format!("{:?}", iter);
4204 assert_eq!(expected, actual);
4206 let _ = iter.next().unwrap();
4207 let expected = "Iter([\"tmp\"])";
4208 let actual = format!("{:?}", iter);
4209 assert_eq!(expected, actual);
4211 let _ = iter.next().unwrap();
4212 let expected = "Iter([])";
4213 let actual = format!("{:?}", iter);
4214 assert_eq!(expected, actual);
4219 let orig: &str = "some/sort/of/path";
4220 let path = Path::new(orig);
4221 let boxed: Box<Path> = Box::from(path);
4222 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4223 assert_eq!(path, &*boxed);
4224 assert_eq!(&*boxed, &*path_buf);
4225 assert_eq!(&*path_buf, path);
4229 fn test_clone_into() {
4230 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4231 let path = Path::new("short");
4232 path.clone_into(&mut path_buf);
4233 assert_eq!(path, path_buf);
4234 assert!(path_buf.into_os_string().capacity() >= 15);
4238 fn display_format_flags() {
4239 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4240 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4245 let orig = "hello/world";
4246 let path = Path::new(orig);
4247 let rc: Rc<Path> = Rc::from(path);
4248 let arc: Arc<Path> = Arc::from(path);
4250 assert_eq!(&*rc, path);
4251 assert_eq!(&*arc, path);
4253 let rc2: Rc<Path> = Rc::from(path.to_owned());
4254 let arc2: Arc<Path> = Arc::from(path.to_owned());
4256 assert_eq!(&*rc2, path);
4257 assert_eq!(&*arc2, path);