1 //! Cross-platform path manipulation.
3 //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
4 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
5 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
6 //! on strings according to the local platform's path syntax.
8 //! Paths can be parsed into [`Component`]s by iterating over the structure
9 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
10 //! correspond to the substrings between path separators (`/` or `\`). You can
11 //! reconstruct an equivalent path from components with the [`push`] method on
12 //! [`PathBuf`]; note that the paths may differ syntactically by the
13 //! normalization described in the documentation for the [`components`] method.
17 //! Path manipulation includes both parsing components from slices and building
20 //! To parse a path, you can create a [`Path`] slice from a [`str`]
21 //! slice and start asking questions:
24 //! use std::path::Path;
25 //! use std::ffi::OsStr;
27 //! let path = Path::new("/tmp/foo/bar.txt");
29 //! let parent = path.parent();
30 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
32 //! let file_stem = path.file_stem();
33 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
35 //! let extension = path.extension();
36 //! assert_eq!(extension, Some(OsStr::new("txt")));
39 //! To build or modify paths, use [`PathBuf`]:
42 //! use std::path::PathBuf;
44 //! // This way works...
45 //! let mut path = PathBuf::from("c:\\");
47 //! path.push("windows");
48 //! path.push("system32");
50 //! path.set_extension("dll");
52 //! // ... but push is best used if you don't know everything up
53 //! // front. If you do, this way is better:
54 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
57 //! [`Component`]: ../../std/path/enum.Component.html
58 //! [`components`]: ../../std/path/struct.Path.html#method.components
59 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
60 //! [`Path`]: ../../std/path/struct.Path.html
61 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
62 //! [`String`]: ../../std/string/struct.String.html
64 //! [`str`]: ../../std/primitive.str.html
65 //! [`OsString`]: ../../std/ffi/struct.OsString.html
66 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
68 #![stable(feature = "rust1", since = "1.0.0")]
70 use crate::borrow::{Borrow, Cow};
72 use crate::error::Error;
75 use crate::hash::{Hash, Hasher};
77 use crate::iter::{self, FusedIterator};
78 use crate::ops::{self, Deref};
80 use crate::str::FromStr;
83 use crate::ffi::{OsStr, OsString};
85 use crate::sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
87 ////////////////////////////////////////////////////////////////////////////////
89 ////////////////////////////////////////////////////////////////////////////////
91 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
92 // taking advantage of the fact that OsStr always encodes ASCII characters
93 // as-is. Eventually, this transmutation should be replaced by direct uses of
94 // OsStr APIs for parsing, but it will take a while for those to become
97 ////////////////////////////////////////////////////////////////////////////////
99 ////////////////////////////////////////////////////////////////////////////////
101 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
103 /// Windows uses a variety of path prefix styles, including references to drive
104 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
105 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
106 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
107 /// no normalization is performed.
112 /// use std::path::{Component, Path, Prefix};
113 /// use std::path::Prefix::*;
114 /// use std::ffi::OsStr;
116 /// fn get_path_prefix(s: &str) -> Prefix {
117 /// let path = Path::new(s);
118 /// match path.components().next().unwrap() {
119 /// Component::Prefix(prefix_component) => prefix_component.kind(),
124 /// # if cfg!(windows) {
125 /// assert_eq!(Verbatim(OsStr::new("pictures")),
126 /// get_path_prefix(r"\\?\pictures\kittens"));
127 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
128 /// get_path_prefix(r"\\?\UNC\server\share"));
129 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
130 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
131 /// get_path_prefix(r"\\.\BrainInterface"));
132 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
133 /// get_path_prefix(r"\\server\share"));
134 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
137 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub enum Prefix<'a> {
140 /// Verbatim prefix, e.g., `\\?\cat_pics`.
142 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
144 #[stable(feature = "rust1", since = "1.0.0")]
145 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
147 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
148 /// e.g., `\\?\UNC\server\share`.
150 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
151 /// server's hostname and a share name.
152 #[stable(feature = "rust1", since = "1.0.0")]
154 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
155 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
158 /// Verbatim disk prefix, e.g., `\\?\C:\`.
160 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
161 /// drive letter and `:\`.
162 #[stable(feature = "rust1", since = "1.0.0")]
163 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
165 /// Device namespace prefix, e.g., `\\.\COM42`.
167 /// Device namespace prefixes consist of `\\.\` immediately followed by the
169 #[stable(feature = "rust1", since = "1.0.0")]
170 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
172 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
173 /// `\\server\share`.
175 /// UNC prefixes consist of the server's hostname and a share name.
176 #[stable(feature = "rust1", since = "1.0.0")]
178 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
179 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
182 /// Prefix `C:` for the given disk drive.
183 #[stable(feature = "rust1", since = "1.0.0")]
184 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
187 impl<'a> Prefix<'a> {
189 fn len(&self) -> usize {
191 fn os_str_len(s: &OsStr) -> usize {
192 os_str_as_u8_slice(s).len()
195 Verbatim(x) => 4 + os_str_len(x),
196 VerbatimUNC(x, y) => {
198 if os_str_len(y) > 0 {
204 VerbatimDisk(_) => 6,
207 if os_str_len(y) > 0 {
213 DeviceNS(x) => 4 + os_str_len(x),
219 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
224 /// use std::path::Prefix::*;
225 /// use std::ffi::OsStr;
227 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
228 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
229 /// assert!(VerbatimDisk(b'C').is_verbatim());
230 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
231 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
232 /// assert!(!Disk(b'C').is_verbatim());
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub fn is_verbatim(&self) -> bool {
239 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
245 fn is_drive(&self) -> bool {
247 Prefix::Disk(_) => true,
253 fn has_implicit_root(&self) -> bool {
258 ////////////////////////////////////////////////////////////////////////////////
259 // Exposed parsing helpers
260 ////////////////////////////////////////////////////////////////////////////////
262 /// Determines whether the character is one of the permitted path
263 /// separators for the current platform.
270 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
271 /// assert!(!path::is_separator('❤'));
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub fn is_separator(c: char) -> bool {
275 c.is_ascii() && is_sep_byte(c as u8)
278 /// The primary separator of path components for the current platform.
280 /// For example, `/` on Unix and `\` on Windows.
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
284 ////////////////////////////////////////////////////////////////////////////////
286 ////////////////////////////////////////////////////////////////////////////////
288 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
289 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
290 // `iter` after having exhausted `prefix`.
291 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
292 where I: Iterator<Item = Component<'a>> + Clone,
293 J: Iterator<Item = Component<'b>>,
296 let mut iter_next = iter.clone();
297 match (iter_next.next(), prefix.next()) {
298 (Some(ref x), Some(ref y)) if x == y => (),
299 (Some(_), Some(_)) => return None,
300 (Some(_), None) => return Some(iter),
301 (None, None) => return Some(iter),
302 (None, Some(_)) => return None,
308 // See note at the top of this module to understand why these are used:
309 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
310 unsafe { &*(s as *const OsStr as *const [u8]) }
312 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
313 &*(s as *const [u8] as *const OsStr)
316 // Detect scheme on Redox
317 fn has_redox_scheme(s: &[u8]) -> bool {
318 cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
321 ////////////////////////////////////////////////////////////////////////////////
322 // Cross-platform, iterator-independent parsing
323 ////////////////////////////////////////////////////////////////////////////////
325 /// Says whether the first byte after the prefix is a separator.
326 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
327 let path = if let Some(p) = prefix {
332 !path.is_empty() && is_sep_byte(path[0])
335 // basic workhorse for splitting stem and extension
336 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
338 if os_str_as_u8_slice(file) == b".." {
339 return (Some(file), None);
342 // The unsafety here stems from converting between &OsStr and &[u8]
343 // and back. This is safe to do because (1) we only look at ASCII
344 // contents of the encoding and (2) new &OsStr values are produced
345 // only from ASCII-bounded slices of existing &OsStr values.
347 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
348 let after = iter.next();
349 let before = iter.next();
350 if before == Some(b"") {
353 (before.map(|s| u8_slice_as_os_str(s)),
354 after.map(|s| u8_slice_as_os_str(s)))
359 ////////////////////////////////////////////////////////////////////////////////
360 // The core iterators
361 ////////////////////////////////////////////////////////////////////////////////
363 /// Component parsing works by a double-ended state machine; the cursors at the
364 /// front and back of the path each keep track of what parts of the path have
365 /// been consumed so far.
367 /// Going front to back, a path is made up of a prefix, a starting
368 /// directory component, and a body (of normal components)
369 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
372 StartDir = 1, // / or . or nothing
373 Body = 2, // foo/bar/baz
377 /// A structure wrapping a Windows path prefix as well as its unparsed string
380 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
381 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
382 /// returned by [`as_os_str`].
384 /// Instances of this `struct` can be obtained by matching against the
385 /// [`Prefix` variant] on [`Component`].
387 /// Does not occur on Unix.
392 /// # if cfg!(windows) {
393 /// use std::path::{Component, Path, Prefix};
394 /// use std::ffi::OsStr;
396 /// let path = Path::new(r"c:\you\later\");
397 /// match path.components().next().unwrap() {
398 /// Component::Prefix(prefix_component) => {
399 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
400 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
402 /// _ => unreachable!(),
407 /// [`as_os_str`]: #method.as_os_str
408 /// [`Component`]: enum.Component.html
409 /// [`kind`]: #method.kind
410 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
411 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
412 /// [`Prefix`]: enum.Prefix.html
413 #[stable(feature = "rust1", since = "1.0.0")]
414 #[derive(Copy, Clone, Eq, Debug)]
415 pub struct PrefixComponent<'a> {
416 /// The prefix as an unparsed `OsStr` slice.
419 /// The parsed prefix data.
423 impl<'a> PrefixComponent<'a> {
424 /// Returns the parsed prefix data.
426 /// See [`Prefix`]'s documentation for more information on the different
427 /// kinds of prefixes.
429 /// [`Prefix`]: enum.Prefix.html
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn kind(&self) -> Prefix<'a> {
435 /// Returns the raw [`OsStr`] slice for this prefix.
437 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn as_os_str(&self) -> &'a OsStr {
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
446 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
447 cmp::PartialEq::eq(&self.parsed, &other.parsed)
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
453 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
454 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl cmp::Ord for PrefixComponent<'_> {
460 fn cmp(&self, other: &Self) -> cmp::Ordering {
461 cmp::Ord::cmp(&self.parsed, &other.parsed)
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl Hash for PrefixComponent<'_> {
467 fn hash<H: Hasher>(&self, h: &mut H) {
472 /// A single component of a path.
474 /// A `Component` roughly corresponds to a substring between path separators
477 /// This `enum` is created by iterating over [`Components`], which in turn is
478 /// created by the [`components`][`Path::components`] method on [`Path`].
483 /// use std::path::{Component, Path};
485 /// let path = Path::new("/tmp/foo/bar.txt");
486 /// let components = path.components().collect::<Vec<_>>();
487 /// assert_eq!(&components, &[
488 /// Component::RootDir,
489 /// Component::Normal("tmp".as_ref()),
490 /// Component::Normal("foo".as_ref()),
491 /// Component::Normal("bar.txt".as_ref()),
495 /// [`Components`]: struct.Components.html
496 /// [`Path`]: struct.Path.html
497 /// [`Path::components`]: struct.Path.html#method.components
498 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub enum Component<'a> {
501 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
503 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
506 /// Does not occur on Unix.
508 /// [`Prefix`]: enum.Prefix.html
509 #[stable(feature = "rust1", since = "1.0.0")]
511 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
514 /// The root directory component, appears after any prefix and before anything else.
516 /// It represents a separator that designates that a path starts from root.
517 #[stable(feature = "rust1", since = "1.0.0")]
520 /// A reference to the current directory, i.e., `.`.
521 #[stable(feature = "rust1", since = "1.0.0")]
524 /// A reference to the parent directory, i.e., `..`.
525 #[stable(feature = "rust1", since = "1.0.0")]
528 /// A normal component, e.g., `a` and `b` in `a/b`.
530 /// This variant is the most common one, it represents references to files
532 #[stable(feature = "rust1", since = "1.0.0")]
533 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
536 impl<'a> Component<'a> {
537 /// Extracts the underlying [`OsStr`] slice.
542 /// use std::path::Path;
544 /// let path = Path::new("./tmp/foo/bar.txt");
545 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
546 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
549 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn as_os_str(self) -> &'a OsStr {
553 Component::Prefix(p) => p.as_os_str(),
554 Component::RootDir => OsStr::new(MAIN_SEP_STR),
555 Component::CurDir => OsStr::new("."),
556 Component::ParentDir => OsStr::new(".."),
557 Component::Normal(path) => path,
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl AsRef<OsStr> for Component<'_> {
564 fn as_ref(&self) -> &OsStr {
569 #[stable(feature = "path_component_asref", since = "1.25.0")]
570 impl AsRef<Path> for Component<'_> {
571 fn as_ref(&self) -> &Path {
572 self.as_os_str().as_ref()
576 /// An iterator over the [`Component`]s of a [`Path`].
578 /// This `struct` is created by the [`components`] method on [`Path`].
579 /// See its documentation for more.
584 /// use std::path::Path;
586 /// let path = Path::new("/tmp/foo/bar.txt");
588 /// for component in path.components() {
589 /// println!("{:?}", component);
593 /// [`Component`]: enum.Component.html
594 /// [`components`]: struct.Path.html#method.components
595 /// [`Path`]: struct.Path.html
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub struct Components<'a> {
599 // The path left to parse components from
602 // The prefix as it was originally parsed, if any
603 prefix: Option<Prefix<'a>>,
605 // true if path *physically* has a root separator; for most Windows
606 // prefixes, it may have a "logical" rootseparator for the purposes of
607 // normalization, e.g., \\server\share == \\server\share\.
608 has_physical_root: bool,
610 // The iterator is double-ended, and these two states keep track of what has
611 // been produced from either end
616 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
618 /// This `struct` is created by the [`iter`] method on [`Path`].
619 /// See its documentation for more.
621 /// [`Component`]: enum.Component.html
622 /// [`iter`]: struct.Path.html#method.iter
623 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
624 /// [`Path`]: struct.Path.html
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub struct Iter<'a> {
628 inner: Components<'a>,
631 #[stable(feature = "path_components_debug", since = "1.13.0")]
632 impl fmt::Debug for Components<'_> {
633 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
634 struct DebugHelper<'a>(&'a Path);
636 impl fmt::Debug for DebugHelper<'_> {
637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
639 .entries(self.0.components())
644 f.debug_tuple("Components")
645 .field(&DebugHelper(self.as_path()))
650 impl<'a> Components<'a> {
651 // how long is the prefix, if any?
653 fn prefix_len(&self) -> usize {
654 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
658 fn prefix_verbatim(&self) -> bool {
659 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
662 /// how much of the prefix is left from the point of view of iteration?
664 fn prefix_remaining(&self) -> usize {
665 if self.front == State::Prefix {
672 // Given the iteration so far, how much of the pre-State::Body path is left?
674 fn len_before_body(&self) -> usize {
675 let root = if self.front <= State::StartDir && self.has_physical_root {
680 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
685 self.prefix_remaining() + root + cur_dir
688 // is the iteration complete?
690 fn finished(&self) -> bool {
691 self.front == State::Done || self.back == State::Done || self.front > self.back
695 fn is_sep_byte(&self, b: u8) -> bool {
696 if self.prefix_verbatim() {
703 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
708 /// use std::path::Path;
710 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
711 /// components.next();
712 /// components.next();
714 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub fn as_path(&self) -> &'a Path {
718 let mut comps = self.clone();
719 if comps.front == State::Body {
722 if comps.back == State::Body {
725 unsafe { Path::from_u8_slice(comps.path) }
728 /// Is the *original* path rooted?
729 fn has_root(&self) -> bool {
730 if self.has_physical_root {
733 if let Some(p) = self.prefix {
734 if p.has_implicit_root() {
741 /// Should the normalized path include a leading . ?
742 fn include_cur_dir(&self) -> bool {
746 let mut iter = self.path[self.prefix_len()..].iter();
747 match (iter.next(), iter.next()) {
748 (Some(&b'.'), None) => true,
749 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
754 // parse a given byte sequence into the corresponding path component
755 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
757 b"." if self.prefix_verbatim() => Some(Component::CurDir),
758 b"." => None, // . components are normalized away, except at
759 // the beginning of a path, which is treated
760 // separately via `include_cur_dir`
761 b".." => Some(Component::ParentDir),
763 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
767 // parse a component from the left, saying how many bytes to consume to
768 // remove the component
769 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
770 debug_assert!(self.front == State::Body);
771 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
772 None => (0, self.path),
773 Some(i) => (1, &self.path[..i]),
775 (comp.len() + extra, self.parse_single_component(comp))
778 // parse a component from the right, saying how many bytes to consume to
779 // remove the component
780 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
781 debug_assert!(self.back == State::Body);
782 let start = self.len_before_body();
783 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
784 None => (0, &self.path[start..]),
785 Some(i) => (1, &self.path[start + i + 1..]),
787 (comp.len() + extra, self.parse_single_component(comp))
790 // trim away repeated separators (i.e., empty components) on the left
791 fn trim_left(&mut self) {
792 while !self.path.is_empty() {
793 let (size, comp) = self.parse_next_component();
797 self.path = &self.path[size..];
802 // trim away repeated separators (i.e., empty components) on the right
803 fn trim_right(&mut self) {
804 while self.path.len() > self.len_before_body() {
805 let (size, comp) = self.parse_next_component_back();
809 self.path = &self.path[..self.path.len() - size];
815 #[stable(feature = "rust1", since = "1.0.0")]
816 impl AsRef<Path> for Components<'_> {
817 fn as_ref(&self) -> &Path {
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl AsRef<OsStr> for Components<'_> {
824 fn as_ref(&self) -> &OsStr {
825 self.as_path().as_os_str()
829 #[stable(feature = "path_iter_debug", since = "1.13.0")]
830 impl fmt::Debug for Iter<'_> {
831 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
832 struct DebugHelper<'a>(&'a Path);
834 impl fmt::Debug for DebugHelper<'_> {
835 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837 .entries(self.0.iter())
842 f.debug_tuple("Iter")
843 .field(&DebugHelper(self.as_path()))
849 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
854 /// use std::path::Path;
856 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
860 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
862 #[stable(feature = "rust1", since = "1.0.0")]
863 pub fn as_path(&self) -> &'a Path {
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl AsRef<Path> for Iter<'_> {
870 fn as_ref(&self) -> &Path {
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl AsRef<OsStr> for Iter<'_> {
877 fn as_ref(&self) -> &OsStr {
878 self.as_path().as_os_str()
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<'a> Iterator for Iter<'a> {
884 type Item = &'a OsStr;
886 fn next(&mut self) -> Option<&'a OsStr> {
887 self.inner.next().map(Component::as_os_str)
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<'a> DoubleEndedIterator for Iter<'a> {
893 fn next_back(&mut self) -> Option<&'a OsStr> {
894 self.inner.next_back().map(Component::as_os_str)
898 #[stable(feature = "fused", since = "1.26.0")]
899 impl FusedIterator for Iter<'_> {}
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> Iterator for Components<'a> {
903 type Item = Component<'a>;
905 fn next(&mut self) -> Option<Component<'a>> {
906 while !self.finished() {
908 State::Prefix if self.prefix_len() > 0 => {
909 self.front = State::StartDir;
910 debug_assert!(self.prefix_len() <= self.path.len());
911 let raw = &self.path[..self.prefix_len()];
912 self.path = &self.path[self.prefix_len()..];
913 return Some(Component::Prefix(PrefixComponent {
914 raw: unsafe { u8_slice_as_os_str(raw) },
915 parsed: self.prefix.unwrap(),
919 self.front = State::StartDir;
922 self.front = State::Body;
923 if self.has_physical_root {
924 debug_assert!(!self.path.is_empty());
925 self.path = &self.path[1..];
926 return Some(Component::RootDir);
927 } else if let Some(p) = self.prefix {
928 if p.has_implicit_root() && !p.is_verbatim() {
929 return Some(Component::RootDir);
931 } else if self.include_cur_dir() {
932 debug_assert!(!self.path.is_empty());
933 self.path = &self.path[1..];
934 return Some(Component::CurDir);
937 State::Body if !self.path.is_empty() => {
938 let (size, comp) = self.parse_next_component();
939 self.path = &self.path[size..];
945 self.front = State::Done;
947 State::Done => unreachable!(),
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl<'a> DoubleEndedIterator for Components<'a> {
956 fn next_back(&mut self) -> Option<Component<'a>> {
957 while !self.finished() {
959 State::Body if self.path.len() > self.len_before_body() => {
960 let (size, comp) = self.parse_next_component_back();
961 self.path = &self.path[..self.path.len() - size];
967 self.back = State::StartDir;
970 self.back = State::Prefix;
971 if self.has_physical_root {
972 self.path = &self.path[..self.path.len() - 1];
973 return Some(Component::RootDir);
974 } else if let Some(p) = self.prefix {
975 if p.has_implicit_root() && !p.is_verbatim() {
976 return Some(Component::RootDir);
978 } else if self.include_cur_dir() {
979 self.path = &self.path[..self.path.len() - 1];
980 return Some(Component::CurDir);
983 State::Prefix if self.prefix_len() > 0 => {
984 self.back = State::Done;
985 return Some(Component::Prefix(PrefixComponent {
986 raw: unsafe { u8_slice_as_os_str(self.path) },
987 parsed: self.prefix.unwrap(),
991 self.back = State::Done;
994 State::Done => unreachable!(),
1001 #[stable(feature = "fused", since = "1.26.0")]
1002 impl FusedIterator for Components<'_> {}
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<'a> cmp::PartialEq for Components<'a> {
1006 fn eq(&self, other: &Components<'a>) -> bool {
1007 Iterator::eq(self.clone(), other.clone())
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl cmp::Eq for Components<'_> {}
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<'a> cmp::PartialOrd for Components<'a> {
1016 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1017 Iterator::partial_cmp(self.clone(), other.clone())
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl cmp::Ord for Components<'_> {
1023 fn cmp(&self, other: &Self) -> cmp::Ordering {
1024 Iterator::cmp(self.clone(), other.clone())
1028 /// An iterator over [`Path`] and its ancestors.
1030 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1031 /// See its documentation for more.
1036 /// use std::path::Path;
1038 /// let path = Path::new("/foo/bar");
1040 /// for ancestor in path.ancestors() {
1041 /// println!("{}", ancestor.display());
1045 /// [`ancestors`]: struct.Path.html#method.ancestors
1046 /// [`Path`]: struct.Path.html
1047 #[derive(Copy, Clone, Debug)]
1048 #[stable(feature = "path_ancestors", since = "1.28.0")]
1049 pub struct Ancestors<'a> {
1050 next: Option<&'a Path>,
1053 #[stable(feature = "path_ancestors", since = "1.28.0")]
1054 impl<'a> Iterator for Ancestors<'a> {
1055 type Item = &'a Path;
1057 fn next(&mut self) -> Option<Self::Item> {
1058 let next = self.next;
1059 self.next = next.and_then(Path::parent);
1064 #[stable(feature = "path_ancestors", since = "1.28.0")]
1065 impl FusedIterator for Ancestors<'_> {}
1067 ////////////////////////////////////////////////////////////////////////////////
1068 // Basic types and traits
1069 ////////////////////////////////////////////////////////////////////////////////
1071 /// An owned, mutable path (akin to [`String`]).
1073 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1074 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1075 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1077 /// [`String`]: ../string/struct.String.html
1078 /// [`Path`]: struct.Path.html
1079 /// [`push`]: struct.PathBuf.html#method.push
1080 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1081 /// [`Deref`]: ../ops/trait.Deref.html
1083 /// More details about the overall approach can be found in
1084 /// the [module documentation](index.html).
1088 /// You can use [`push`] to build up a `PathBuf` from
1092 /// use std::path::PathBuf;
1094 /// let mut path = PathBuf::new();
1096 /// path.push(r"C:\");
1097 /// path.push("windows");
1098 /// path.push("system32");
1100 /// path.set_extension("dll");
1103 /// However, [`push`] is best used for dynamic situations. This is a better way
1104 /// to do this when you know all of the components ahead of time:
1107 /// use std::path::PathBuf;
1109 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1112 /// We can still do better than this! Since these are all strings, we can use
1116 /// use std::path::PathBuf;
1118 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1121 /// Which method works best depends on what kind of situation you're in.
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 pub struct PathBuf {
1129 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1130 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1133 /// Allocates an empty `PathBuf`.
1138 /// use std::path::PathBuf;
1140 /// let path = PathBuf::new();
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 pub fn new() -> PathBuf {
1144 PathBuf { inner: OsString::new() }
1147 /// Creates a new `PathBuf` with a given capacity used to create the
1148 /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`].
1153 /// #![feature(path_buf_capacity)]
1154 /// use std::path::PathBuf;
1156 /// let mut path = PathBuf::with_capacity(10);
1157 /// let capacity = path.capacity();
1159 /// // This push is done without reallocating
1160 /// path.push(r"C:\");
1162 /// assert_eq!(capacity, path.capacity());
1165 /// [`with_capacity`]: ../ffi/struct.OsString.html#method.with_capacity
1166 /// [`OsString`]: ../ffi/struct.OsString.html
1167 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1168 pub fn with_capacity(capacity: usize) -> PathBuf {
1170 inner: OsString::with_capacity(capacity)
1174 /// Coerces to a [`Path`] slice.
1176 /// [`Path`]: struct.Path.html
1181 /// use std::path::{Path, PathBuf};
1183 /// let p = PathBuf::from("/test");
1184 /// assert_eq!(Path::new("/test"), p.as_path());
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 pub fn as_path(&self) -> &Path {
1191 /// Extends `self` with `path`.
1193 /// If `path` is absolute, it replaces the current path.
1197 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1198 /// replaces everything except for the prefix (if any) of `self`.
1199 /// * if `path` has a prefix but no root, it replaces `self`.
1203 /// Pushing a relative path extends the existing path:
1206 /// use std::path::PathBuf;
1208 /// let mut path = PathBuf::from("/tmp");
1209 /// path.push("file.bk");
1210 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1213 /// Pushing an absolute path replaces the existing path:
1216 /// use std::path::PathBuf;
1218 /// let mut path = PathBuf::from("/tmp");
1219 /// path.push("/etc");
1220 /// assert_eq!(path, PathBuf::from("/etc"));
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1224 self._push(path.as_ref())
1227 fn _push(&mut self, path: &Path) {
1228 // in general, a separator is needed if the rightmost byte is not a separator
1229 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1231 // in the special case of `C:` on Windows, do *not* add a separator
1233 let comps = self.components();
1234 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1235 comps.prefix.unwrap().is_drive() {
1240 // absolute `path` replaces `self`
1241 if path.is_absolute() || path.prefix().is_some() {
1242 self.as_mut_vec().truncate(0);
1244 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1245 } else if path.has_root() {
1246 let prefix_len = self.components().prefix_remaining();
1247 self.as_mut_vec().truncate(prefix_len);
1249 // `path` is a pure relative path
1250 } else if need_sep {
1251 self.inner.push(MAIN_SEP_STR);
1254 self.inner.push(path);
1257 /// Truncates `self` to [`self.parent`].
1259 /// Returns `false` and does nothing if [`self.parent`] is [`None`].
1260 /// Otherwise, returns `true`.
1262 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1263 /// [`self.parent`]: struct.PathBuf.html#method.parent
1268 /// use std::path::{Path, PathBuf};
1270 /// let mut p = PathBuf::from("/test/test.rs");
1273 /// assert_eq!(Path::new("/test"), p);
1275 /// assert_eq!(Path::new("/"), p);
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 pub fn pop(&mut self) -> bool {
1279 match self.parent().map(|p| p.as_u8_slice().len()) {
1281 self.as_mut_vec().truncate(len);
1288 /// Updates [`self.file_name`] to `file_name`.
1290 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1293 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1294 /// `file_name`. The new path will be a sibling of the original path.
1295 /// (That is, it will have the same parent.)
1297 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1298 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1299 /// [`pop`]: struct.PathBuf.html#method.pop
1304 /// use std::path::PathBuf;
1306 /// let mut buf = PathBuf::from("/");
1307 /// assert!(buf.file_name() == None);
1308 /// buf.set_file_name("bar");
1309 /// assert!(buf == PathBuf::from("/bar"));
1310 /// assert!(buf.file_name().is_some());
1311 /// buf.set_file_name("baz.txt");
1312 /// assert!(buf == PathBuf::from("/baz.txt"));
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1316 self._set_file_name(file_name.as_ref())
1319 fn _set_file_name(&mut self, file_name: &OsStr) {
1320 if self.file_name().is_some() {
1321 let popped = self.pop();
1322 debug_assert!(popped);
1324 self.push(file_name);
1327 /// Updates [`self.extension`] to `extension`.
1329 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1330 /// returns `true` and updates the extension otherwise.
1332 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1335 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1336 /// [`self.extension`]: struct.PathBuf.html#method.extension
1337 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1342 /// use std::path::{Path, PathBuf};
1344 /// let mut p = PathBuf::from("/feel/the");
1346 /// p.set_extension("force");
1347 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1349 /// p.set_extension("dark_side");
1350 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1354 self._set_extension(extension.as_ref())
1357 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1358 if self.file_name().is_none() {
1362 let mut stem = match self.file_stem() {
1363 Some(stem) => stem.to_os_string(),
1364 None => OsString::new(),
1367 if !os_str_as_u8_slice(extension).is_empty() {
1369 stem.push(extension);
1371 self.set_file_name(&stem);
1376 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1378 /// [`OsString`]: ../ffi/struct.OsString.html
1383 /// use std::path::PathBuf;
1385 /// let p = PathBuf::from("/the/head");
1386 /// let os_str = p.into_os_string();
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 pub fn into_os_string(self) -> OsString {
1393 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1395 /// [`Box`]: ../../std/boxed/struct.Box.html
1396 /// [`Path`]: struct.Path.html
1397 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1398 pub fn into_boxed_path(self) -> Box<Path> {
1399 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1400 unsafe { Box::from_raw(rw) }
1403 /// Invokes [`capacity`] on the underlying instance of [`OsString`].
1405 /// [`capacity`]: ../ffi/struct.OsString.html#method.capacity
1406 /// [`OsString`]: ../ffi/struct.OsString.html
1407 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1408 pub fn capacity(&self) -> usize {
1409 self.inner.capacity()
1412 /// Invokes [`clear`] on the underlying instance of [`OsString`].
1414 /// [`clear`]: ../ffi/struct.OsString.html#method.clear
1415 /// [`OsString`]: ../ffi/struct.OsString.html
1416 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1417 pub fn clear(&mut self) {
1421 /// Invokes [`reserve`] on the underlying instance of [`OsString`].
1423 /// [`reserve`]: ../ffi/struct.OsString.html#method.reserve
1424 /// [`OsString`]: ../ffi/struct.OsString.html
1425 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1426 pub fn reserve(&mut self, additional: usize) {
1427 self.inner.reserve(additional)
1430 /// Invokes [`reserve_exact`] on the underlying instance of [`OsString`].
1432 /// [`reserve_exact`]: ../ffi/struct.OsString.html#method.reserve_exact
1433 /// [`OsString`]: ../ffi/struct.OsString.html
1434 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1435 pub fn reserve_exact(&mut self, additional: usize) {
1436 self.inner.reserve_exact(additional)
1439 /// Invokes [`shrink_to_fit`] on the underlying instance of [`OsString`].
1441 /// [`shrink_to_fit`]: ../ffi/struct.OsString.html#method.shrink_to_fit
1442 /// [`OsString`]: ../ffi/struct.OsString.html
1443 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1444 pub fn shrink_to_fit(&mut self) {
1445 self.inner.shrink_to_fit()
1448 /// Invokes [`shrink_to`] on the underlying instance of [`OsString`].
1450 /// [`shrink_to`]: ../ffi/struct.OsString.html#method.shrink_to
1451 /// [`OsString`]: ../ffi/struct.OsString.html
1452 #[unstable(feature = "path_buf_capacity", issue = "58234")]
1453 pub fn shrink_to(&mut self, min_capacity: usize) {
1454 self.inner.shrink_to(min_capacity)
1458 #[stable(feature = "box_from_path", since = "1.17.0")]
1459 impl From<&Path> for Box<Path> {
1460 fn from(path: &Path) -> Box<Path> {
1461 let boxed: Box<OsStr> = path.inner.into();
1462 let rw = Box::into_raw(boxed) as *mut Path;
1463 unsafe { Box::from_raw(rw) }
1467 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1468 impl From<Box<Path>> for PathBuf {
1469 /// Converts a `Box<Path>` into a `PathBuf`
1471 /// This conversion does not allocate or copy memory.
1472 fn from(boxed: Box<Path>) -> PathBuf {
1473 boxed.into_path_buf()
1477 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1478 impl From<PathBuf> for Box<Path> {
1479 /// Converts a `PathBuf` into a `Box<Path>`
1481 /// This conversion currently should not allocate memory,
1482 /// but this behavior is not guaranteed on all platforms or in all future versions.
1483 fn from(p: PathBuf) -> Box<Path> {
1488 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1489 impl Clone for Box<Path> {
1491 fn clone(&self) -> Self {
1492 self.to_path_buf().into_boxed_path()
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1498 fn from(s: &T) -> PathBuf {
1499 PathBuf::from(s.as_ref().to_os_string())
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl From<OsString> for PathBuf {
1505 /// Converts a `OsString` into a `PathBuf`
1507 /// This conversion does not allocate or copy memory.
1508 fn from(s: OsString) -> PathBuf {
1509 PathBuf { inner: s }
1513 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1514 impl From<PathBuf> for OsString {
1515 /// Converts a `PathBuf` into a `OsString`
1517 /// This conversion does not allocate or copy memory.
1518 fn from(path_buf : PathBuf) -> OsString {
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 impl From<String> for PathBuf {
1525 /// Converts a `String` into a `PathBuf`
1527 /// This conversion does not allocate or copy memory.
1528 fn from(s: String) -> PathBuf {
1529 PathBuf::from(OsString::from(s))
1533 #[stable(feature = "path_from_str", since = "1.32.0")]
1534 impl FromStr for PathBuf {
1535 type Err = core::convert::Infallible;
1537 fn from_str(s: &str) -> Result<Self, Self::Err> {
1538 Ok(PathBuf::from(s))
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1544 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1545 let mut buf = PathBuf::new();
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1553 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1555 self.push(p.as_ref())
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl fmt::Debug for PathBuf {
1562 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1563 fmt::Debug::fmt(&**self, formatter)
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl ops::Deref for PathBuf {
1571 fn deref(&self) -> &Path {
1572 Path::new(&self.inner)
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 impl Borrow<Path> for PathBuf {
1578 fn borrow(&self) -> &Path {
1583 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1584 impl Default for PathBuf {
1585 fn default() -> Self {
1590 #[stable(feature = "cow_from_path", since = "1.6.0")]
1591 impl<'a> From<&'a Path> for Cow<'a, Path> {
1593 fn from(s: &'a Path) -> Cow<'a, Path> {
1598 #[stable(feature = "cow_from_path", since = "1.6.0")]
1599 impl<'a> From<PathBuf> for Cow<'a, Path> {
1601 fn from(s: PathBuf) -> Cow<'a, Path> {
1606 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1607 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1609 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1610 Cow::Borrowed(p.as_path())
1614 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1615 impl<'a> From<Cow<'a, Path>> for PathBuf {
1617 fn from(p: Cow<'a, Path>) -> Self {
1622 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1623 impl From<PathBuf> for Arc<Path> {
1624 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1626 fn from(s: PathBuf) -> Arc<Path> {
1627 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1628 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1632 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1633 impl From<&Path> for Arc<Path> {
1634 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1636 fn from(s: &Path) -> Arc<Path> {
1637 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1638 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1642 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1643 impl From<PathBuf> for Rc<Path> {
1644 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1646 fn from(s: PathBuf) -> Rc<Path> {
1647 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1648 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1652 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1653 impl From<&Path> for Rc<Path> {
1654 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1656 fn from(s: &Path) -> Rc<Path> {
1657 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1658 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl ToOwned for Path {
1664 type Owned = PathBuf;
1665 fn to_owned(&self) -> PathBuf {
1668 fn clone_into(&self, target: &mut PathBuf) {
1669 self.inner.clone_into(&mut target.inner);
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl cmp::PartialEq for PathBuf {
1675 fn eq(&self, other: &PathBuf) -> bool {
1676 self.components() == other.components()
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl Hash for PathBuf {
1682 fn hash<H: Hasher>(&self, h: &mut H) {
1683 self.as_path().hash(h)
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl cmp::Eq for PathBuf {}
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl cmp::PartialOrd for PathBuf {
1692 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1693 self.components().partial_cmp(other.components())
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl cmp::Ord for PathBuf {
1699 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1700 self.components().cmp(other.components())
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 impl AsRef<OsStr> for PathBuf {
1706 fn as_ref(&self) -> &OsStr {
1711 /// A slice of a path (akin to [`str`]).
1713 /// This type supports a number of operations for inspecting a path, including
1714 /// breaking the path into its components (separated by `/` on Unix and by either
1715 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1716 /// is absolute, and so on.
1718 /// This is an *unsized* type, meaning that it must always be used behind a
1719 /// pointer like `&` or [`Box`]. For an owned version of this type,
1720 /// see [`PathBuf`].
1722 /// [`str`]: ../primitive.str.html
1723 /// [`Box`]: ../boxed/struct.Box.html
1724 /// [`PathBuf`]: struct.PathBuf.html
1726 /// More details about the overall approach can be found in
1727 /// the [module documentation](index.html).
1732 /// use std::path::Path;
1733 /// use std::ffi::OsStr;
1735 /// // Note: this example does work on Windows
1736 /// let path = Path::new("./foo/bar.txt");
1738 /// let parent = path.parent();
1739 /// assert_eq!(parent, Some(Path::new("./foo")));
1741 /// let file_stem = path.file_stem();
1742 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1744 /// let extension = path.extension();
1745 /// assert_eq!(extension, Some(OsStr::new("txt")));
1747 #[stable(feature = "rust1", since = "1.0.0")]
1752 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1755 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1756 /// See its documentation for more.
1758 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1759 /// [`Path`]: struct.Path.html
1760 #[derive(Debug, Clone, PartialEq, Eq)]
1761 #[stable(since = "1.7.0", feature = "strip_prefix")]
1762 pub struct StripPrefixError(());
1765 // The following (private!) function allows construction of a path from a u8
1766 // slice, which is only safe when it is known to follow the OsStr encoding.
1767 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1768 Path::new(u8_slice_as_os_str(s))
1770 // The following (private!) function reveals the byte encoding used for OsStr.
1771 fn as_u8_slice(&self) -> &[u8] {
1772 os_str_as_u8_slice(&self.inner)
1775 /// Directly wraps a string slice as a `Path` slice.
1777 /// This is a cost-free conversion.
1782 /// use std::path::Path;
1784 /// Path::new("foo.txt");
1787 /// You can create `Path`s from `String`s, or even other `Path`s:
1790 /// use std::path::Path;
1792 /// let string = String::from("foo.txt");
1793 /// let from_string = Path::new(&string);
1794 /// let from_path = Path::new(&from_string);
1795 /// assert_eq!(from_string, from_path);
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1799 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1802 /// Yields the underlying [`OsStr`] slice.
1804 /// [`OsStr`]: ../ffi/struct.OsStr.html
1809 /// use std::path::Path;
1811 /// let os_str = Path::new("foo.txt").as_os_str();
1812 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 pub fn as_os_str(&self) -> &OsStr {
1819 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1821 /// This conversion may entail doing a check for UTF-8 validity.
1823 /// [`&str`]: ../primitive.str.html
1828 /// use std::path::Path;
1830 /// let path = Path::new("foo.txt");
1831 /// assert_eq!(path.to_str(), Some("foo.txt"));
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 pub fn to_str(&self) -> Option<&str> {
1838 /// Converts a `Path` to a [`Cow<str>`].
1840 /// Any non-Unicode sequences are replaced with
1841 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1843 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1844 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1848 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1851 /// use std::path::Path;
1853 /// let path = Path::new("foo.txt");
1854 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1857 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1858 /// have returned `"fo�.txt"`.
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 pub fn to_string_lossy(&self) -> Cow<str> {
1861 self.inner.to_string_lossy()
1864 /// Converts a `Path` to an owned [`PathBuf`].
1866 /// [`PathBuf`]: struct.PathBuf.html
1871 /// use std::path::Path;
1873 /// let path_buf = Path::new("foo.txt").to_path_buf();
1874 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1876 #[rustc_conversion_suggestion]
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 pub fn to_path_buf(&self) -> PathBuf {
1879 PathBuf::from(self.inner.to_os_string())
1882 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1883 /// the current directory.
1885 /// * On Unix, a path is absolute if it starts with the root, so
1886 /// `is_absolute` and [`has_root`] are equivalent.
1888 /// * On Windows, a path is absolute if it has a prefix and starts with the
1889 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1894 /// use std::path::Path;
1896 /// assert!(!Path::new("foo.txt").is_absolute());
1899 /// [`has_root`]: #method.has_root
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 #[allow(deprecated)]
1902 pub fn is_absolute(&self) -> bool {
1903 if cfg!(target_os = "redox") {
1904 // FIXME: Allow Redox prefixes
1905 self.has_root() || has_redox_scheme(self.as_u8_slice())
1907 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1911 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1913 /// See [`is_absolute`]'s documentation for more details.
1918 /// use std::path::Path;
1920 /// assert!(Path::new("foo.txt").is_relative());
1923 /// [`is_absolute`]: #method.is_absolute
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 pub fn is_relative(&self) -> bool {
1929 fn prefix(&self) -> Option<Prefix> {
1930 self.components().prefix
1933 /// Returns `true` if the `Path` has a root.
1935 /// * On Unix, a path has a root if it begins with `/`.
1937 /// * On Windows, a path has a root if it:
1938 /// * has no prefix and begins with a separator, e.g., `\windows`
1939 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1940 /// * has any non-disk prefix, e.g., `\\server\share`
1945 /// use std::path::Path;
1947 /// assert!(Path::new("/etc/passwd").has_root());
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 pub fn has_root(&self) -> bool {
1951 self.components().has_root()
1954 /// Returns the `Path` without its final component, if there is one.
1956 /// Returns [`None`] if the path terminates in a root or prefix.
1958 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1963 /// use std::path::Path;
1965 /// let path = Path::new("/foo/bar");
1966 /// let parent = path.parent().unwrap();
1967 /// assert_eq!(parent, Path::new("/foo"));
1969 /// let grand_parent = parent.parent().unwrap();
1970 /// assert_eq!(grand_parent, Path::new("/"));
1971 /// assert_eq!(grand_parent.parent(), None);
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 pub fn parent(&self) -> Option<&Path> {
1975 let mut comps = self.components();
1976 let comp = comps.next_back();
1979 Component::Normal(_) |
1981 Component::ParentDir => Some(comps.as_path()),
1987 /// Produces an iterator over `Path` and its ancestors.
1989 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1990 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1991 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1992 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1998 /// use std::path::Path;
2000 /// let mut ancestors = Path::new("/foo/bar").ancestors();
2001 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
2002 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
2003 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
2004 /// assert_eq!(ancestors.next(), None);
2007 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2008 /// [`parent`]: struct.Path.html#method.parent
2009 #[stable(feature = "path_ancestors", since = "1.28.0")]
2010 pub fn ancestors(&self) -> Ancestors {
2016 /// Returns the final component of the `Path`, if there is one.
2018 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
2019 /// is the directory name.
2021 /// Returns [`None`] if the path terminates in `..`.
2023 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2028 /// use std::path::Path;
2029 /// use std::ffi::OsStr;
2031 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
2032 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
2033 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
2034 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
2035 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
2036 /// assert_eq!(None, Path::new("/").file_name());
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 pub fn file_name(&self) -> Option<&OsStr> {
2040 self.components().next_back().and_then(|p| {
2042 Component::Normal(p) => Some(p.as_ref()),
2048 /// Returns a path that, when joined onto `base`, yields `self`.
2052 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
2053 /// returns `false`), returns [`Err`].
2055 /// [`starts_with`]: #method.starts_with
2056 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
2061 /// use std::path::{Path, PathBuf};
2063 /// let path = Path::new("/test/haha/foo.txt");
2065 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
2066 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
2067 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
2068 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2069 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2070 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2071 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2073 /// let prefix = PathBuf::from("/test/");
2074 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2076 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2077 pub fn strip_prefix<P>(&self, base: P)
2078 -> Result<&Path, StripPrefixError>
2079 where P: AsRef<Path>
2081 self._strip_prefix(base.as_ref())
2084 fn _strip_prefix(&self, base: &Path)
2085 -> Result<&Path, StripPrefixError> {
2086 iter_after(self.components(), base.components())
2087 .map(|c| c.as_path())
2088 .ok_or(StripPrefixError(()))
2091 /// Determines whether `base` is a prefix of `self`.
2093 /// Only considers whole path components to match.
2098 /// use std::path::Path;
2100 /// let path = Path::new("/etc/passwd");
2102 /// assert!(path.starts_with("/etc"));
2103 /// assert!(path.starts_with("/etc/"));
2104 /// assert!(path.starts_with("/etc/passwd"));
2105 /// assert!(path.starts_with("/etc/passwd/"));
2107 /// assert!(!path.starts_with("/e"));
2109 #[stable(feature = "rust1", since = "1.0.0")]
2110 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2111 self._starts_with(base.as_ref())
2114 fn _starts_with(&self, base: &Path) -> bool {
2115 iter_after(self.components(), base.components()).is_some()
2118 /// Determines whether `child` is a suffix of `self`.
2120 /// Only considers whole path components to match.
2125 /// use std::path::Path;
2127 /// let path = Path::new("/etc/passwd");
2129 /// assert!(path.ends_with("passwd"));
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2133 self._ends_with(child.as_ref())
2136 fn _ends_with(&self, child: &Path) -> bool {
2137 iter_after(self.components().rev(), child.components().rev()).is_some()
2140 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2142 /// [`self.file_name`]: struct.Path.html#method.file_name
2146 /// * [`None`], if there is no file name;
2147 /// * The entire file name if there is no embedded `.`;
2148 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2149 /// * Otherwise, the portion of the file name before the final `.`
2151 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2156 /// use std::path::Path;
2158 /// let path = Path::new("foo.rs");
2160 /// assert_eq!("foo", path.file_stem().unwrap());
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 pub fn file_stem(&self) -> Option<&OsStr> {
2164 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2167 /// Extracts the extension of [`self.file_name`], if possible.
2169 /// The extension is:
2171 /// * [`None`], if there is no file name;
2172 /// * [`None`], if there is no embedded `.`;
2173 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2174 /// * Otherwise, the portion of the file name after the final `.`
2176 /// [`self.file_name`]: struct.Path.html#method.file_name
2177 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2182 /// use std::path::Path;
2184 /// let path = Path::new("foo.rs");
2186 /// assert_eq!("rs", path.extension().unwrap());
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 pub fn extension(&self) -> Option<&OsStr> {
2190 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2193 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2195 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2197 /// [`PathBuf`]: struct.PathBuf.html
2198 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2203 /// use std::path::{Path, PathBuf};
2205 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2209 self._join(path.as_ref())
2212 fn _join(&self, path: &Path) -> PathBuf {
2213 let mut buf = self.to_path_buf();
2218 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2220 /// See [`PathBuf::set_file_name`] for more details.
2222 /// [`PathBuf`]: struct.PathBuf.html
2223 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2228 /// use std::path::{Path, PathBuf};
2230 /// let path = Path::new("/tmp/foo.txt");
2231 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2233 /// let path = Path::new("/tmp");
2234 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2238 self._with_file_name(file_name.as_ref())
2241 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2242 let mut buf = self.to_path_buf();
2243 buf.set_file_name(file_name);
2247 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2249 /// See [`PathBuf::set_extension`] for more details.
2251 /// [`PathBuf`]: struct.PathBuf.html
2252 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2257 /// use std::path::{Path, PathBuf};
2259 /// let path = Path::new("foo.rs");
2260 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2262 #[stable(feature = "rust1", since = "1.0.0")]
2263 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2264 self._with_extension(extension.as_ref())
2267 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2268 let mut buf = self.to_path_buf();
2269 buf.set_extension(extension);
2273 /// Produces an iterator over the [`Component`]s of the path.
2275 /// When parsing the path, there is a small amount of normalization:
2277 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2278 /// `a` and `b` as components.
2280 /// * Occurrences of `.` are normalized away, except if they are at the
2281 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2282 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2283 /// an additional [`CurDir`] component.
2285 /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
2287 /// Note that no other normalization takes place; in particular, `a/c`
2288 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2289 /// is a symbolic link (so its parent isn't `a`).
2294 /// use std::path::{Path, Component};
2295 /// use std::ffi::OsStr;
2297 /// let mut components = Path::new("/tmp/foo.txt").components();
2299 /// assert_eq!(components.next(), Some(Component::RootDir));
2300 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2301 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2302 /// assert_eq!(components.next(), None)
2305 /// [`Component`]: enum.Component.html
2306 /// [`CurDir`]: enum.Component.html#variant.CurDir
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 pub fn components(&self) -> Components {
2309 let prefix = parse_prefix(self.as_os_str());
2311 path: self.as_u8_slice(),
2313 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2314 has_redox_scheme(self.as_u8_slice()),
2315 front: State::Prefix,
2320 /// Produces an iterator over the path's components viewed as [`OsStr`]
2323 /// For more information about the particulars of how the path is separated
2324 /// into components, see [`components`].
2326 /// [`components`]: #method.components
2327 /// [`OsStr`]: ../ffi/struct.OsStr.html
2332 /// use std::path::{self, Path};
2333 /// use std::ffi::OsStr;
2335 /// let mut it = Path::new("/tmp/foo.txt").iter();
2336 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2337 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2338 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2339 /// assert_eq!(it.next(), None)
2341 #[stable(feature = "rust1", since = "1.0.0")]
2342 pub fn iter(&self) -> Iter {
2343 Iter { inner: self.components() }
2346 /// Returns an object that implements [`Display`] for safely printing paths
2347 /// that may contain non-Unicode data.
2349 /// [`Display`]: ../fmt/trait.Display.html
2354 /// use std::path::Path;
2356 /// let path = Path::new("/tmp/foo.rs");
2358 /// println!("{}", path.display());
2360 #[stable(feature = "rust1", since = "1.0.0")]
2361 pub fn display(&self) -> Display {
2362 Display { path: self }
2365 /// Queries the file system to get information about a file, directory, etc.
2367 /// This function will traverse symbolic links to query information about the
2368 /// destination file.
2370 /// This is an alias to [`fs::metadata`].
2372 /// [`fs::metadata`]: ../fs/fn.metadata.html
2377 /// use std::path::Path;
2379 /// let path = Path::new("/Minas/tirith");
2380 /// let metadata = path.metadata().expect("metadata call failed");
2381 /// println!("{:?}", metadata.file_type());
2383 #[stable(feature = "path_ext", since = "1.5.0")]
2384 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2388 /// Queries the metadata about a file without following symlinks.
2390 /// This is an alias to [`fs::symlink_metadata`].
2392 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2397 /// use std::path::Path;
2399 /// let path = Path::new("/Minas/tirith");
2400 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2401 /// println!("{:?}", metadata.file_type());
2403 #[stable(feature = "path_ext", since = "1.5.0")]
2404 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2405 fs::symlink_metadata(self)
2408 /// Returns the canonical, absolute form of the path with all intermediate
2409 /// components normalized and symbolic links resolved.
2411 /// This is an alias to [`fs::canonicalize`].
2413 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2418 /// use std::path::{Path, PathBuf};
2420 /// let path = Path::new("/foo/test/../test/bar.rs");
2421 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2423 #[stable(feature = "path_ext", since = "1.5.0")]
2424 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2425 fs::canonicalize(self)
2428 /// Reads a symbolic link, returning the file that the link points to.
2430 /// This is an alias to [`fs::read_link`].
2432 /// [`fs::read_link`]: ../fs/fn.read_link.html
2437 /// use std::path::Path;
2439 /// let path = Path::new("/laputa/sky_castle.rs");
2440 /// let path_link = path.read_link().expect("read_link call failed");
2442 #[stable(feature = "path_ext", since = "1.5.0")]
2443 pub fn read_link(&self) -> io::Result<PathBuf> {
2447 /// Returns an iterator over the entries within a directory.
2449 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2450 /// errors may be encountered after an iterator is initially constructed.
2452 /// This is an alias to [`fs::read_dir`].
2454 /// [`io::Result`]: ../io/type.Result.html
2455 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2456 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2461 /// use std::path::Path;
2463 /// let path = Path::new("/laputa");
2464 /// for entry in path.read_dir().expect("read_dir call failed") {
2465 /// if let Ok(entry) = entry {
2466 /// println!("{:?}", entry.path());
2470 #[stable(feature = "path_ext", since = "1.5.0")]
2471 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2475 /// Returns `true` if the path points at an existing entity.
2477 /// This function will traverse symbolic links to query information about the
2478 /// destination file. In case of broken symbolic links this will return `false`.
2480 /// If you cannot access the directory containing the file, e.g., because of a
2481 /// permission error, this will return `false`.
2486 /// use std::path::Path;
2487 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2492 /// This is a convenience function that coerces errors to false. If you want to
2493 /// check errors, call [fs::metadata].
2495 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2496 #[stable(feature = "path_ext", since = "1.5.0")]
2497 pub fn exists(&self) -> bool {
2498 fs::metadata(self).is_ok()
2501 /// Returns `true` if the path exists on disk and is pointing at a regular file.
2503 /// This function will traverse symbolic links to query information about the
2504 /// destination file. In case of broken symbolic links this will return `false`.
2506 /// If you cannot access the directory containing the file, e.g., because of a
2507 /// permission error, this will return `false`.
2512 /// use std::path::Path;
2513 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2514 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2519 /// This is a convenience function that coerces errors to false. If you want to
2520 /// check errors, call [fs::metadata] and handle its Result. Then call
2521 /// [fs::Metadata::is_file] if it was Ok.
2523 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2524 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2525 #[stable(feature = "path_ext", since = "1.5.0")]
2526 pub fn is_file(&self) -> bool {
2527 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2530 /// Returns `true` if the path exists on disk and is pointing at a directory.
2532 /// This function will traverse symbolic links to query information about the
2533 /// destination file. In case of broken symbolic links this will return `false`.
2535 /// If you cannot access the directory containing the file, e.g., because of a
2536 /// permission error, this will return `false`.
2541 /// use std::path::Path;
2542 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2543 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2548 /// This is a convenience function that coerces errors to false. If you want to
2549 /// check errors, call [fs::metadata] and handle its Result. Then call
2550 /// [fs::Metadata::is_dir] if it was Ok.
2552 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2553 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2554 #[stable(feature = "path_ext", since = "1.5.0")]
2555 pub fn is_dir(&self) -> bool {
2556 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2559 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2562 /// [`Box`]: ../../std/boxed/struct.Box.html
2563 /// [`PathBuf`]: struct.PathBuf.html
2564 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2565 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2566 let rw = Box::into_raw(self) as *mut OsStr;
2567 let inner = unsafe { Box::from_raw(rw) };
2568 PathBuf { inner: OsString::from(inner) }
2572 #[stable(feature = "rust1", since = "1.0.0")]
2573 impl AsRef<OsStr> for Path {
2574 fn as_ref(&self) -> &OsStr {
2579 #[stable(feature = "rust1", since = "1.0.0")]
2580 impl fmt::Debug for Path {
2581 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2582 fmt::Debug::fmt(&self.inner, formatter)
2586 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2588 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2589 /// [`Display`] trait in a way that mitigates that. It is created by the
2590 /// [`display`][`Path::display`] method on [`Path`].
2595 /// use std::path::Path;
2597 /// let path = Path::new("/tmp/foo.rs");
2599 /// println!("{}", path.display());
2602 /// [`Display`]: ../../std/fmt/trait.Display.html
2603 /// [`format!`]: ../../std/macro.format.html
2604 /// [`Path`]: struct.Path.html
2605 /// [`Path::display`]: struct.Path.html#method.display
2606 #[stable(feature = "rust1", since = "1.0.0")]
2607 pub struct Display<'a> {
2611 #[stable(feature = "rust1", since = "1.0.0")]
2612 impl fmt::Debug for Display<'_> {
2613 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2614 fmt::Debug::fmt(&self.path, f)
2618 #[stable(feature = "rust1", since = "1.0.0")]
2619 impl fmt::Display for Display<'_> {
2620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2621 self.path.inner.display(f)
2625 #[stable(feature = "rust1", since = "1.0.0")]
2626 impl cmp::PartialEq for Path {
2627 fn eq(&self, other: &Path) -> bool {
2628 self.components().eq(other.components())
2632 #[stable(feature = "rust1", since = "1.0.0")]
2633 impl Hash for Path {
2634 fn hash<H: Hasher>(&self, h: &mut H) {
2635 for component in self.components() {
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 impl cmp::Eq for Path {}
2644 #[stable(feature = "rust1", since = "1.0.0")]
2645 impl cmp::PartialOrd for Path {
2646 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2647 self.components().partial_cmp(other.components())
2651 #[stable(feature = "rust1", since = "1.0.0")]
2652 impl cmp::Ord for Path {
2653 fn cmp(&self, other: &Path) -> cmp::Ordering {
2654 self.components().cmp(other.components())
2658 #[stable(feature = "rust1", since = "1.0.0")]
2659 impl AsRef<Path> for Path {
2660 fn as_ref(&self) -> &Path {
2665 #[stable(feature = "rust1", since = "1.0.0")]
2666 impl AsRef<Path> for OsStr {
2667 fn as_ref(&self) -> &Path {
2672 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2673 impl AsRef<Path> for Cow<'_, OsStr> {
2674 fn as_ref(&self) -> &Path {
2679 #[stable(feature = "rust1", since = "1.0.0")]
2680 impl AsRef<Path> for OsString {
2681 fn as_ref(&self) -> &Path {
2686 #[stable(feature = "rust1", since = "1.0.0")]
2687 impl AsRef<Path> for str {
2688 fn as_ref(&self) -> &Path {
2693 #[stable(feature = "rust1", since = "1.0.0")]
2694 impl AsRef<Path> for String {
2695 fn as_ref(&self) -> &Path {
2700 #[stable(feature = "rust1", since = "1.0.0")]
2701 impl AsRef<Path> for PathBuf {
2702 fn as_ref(&self) -> &Path {
2707 #[stable(feature = "path_into_iter", since = "1.6.0")]
2708 impl<'a> IntoIterator for &'a PathBuf {
2709 type Item = &'a OsStr;
2710 type IntoIter = Iter<'a>;
2711 fn into_iter(self) -> Iter<'a> { self.iter() }
2714 #[stable(feature = "path_into_iter", since = "1.6.0")]
2715 impl<'a> IntoIterator for &'a Path {
2716 type Item = &'a OsStr;
2717 type IntoIter = Iter<'a>;
2718 fn into_iter(self) -> Iter<'a> { self.iter() }
2721 macro_rules! impl_cmp {
2722 ($lhs:ty, $rhs: ty) => {
2723 #[stable(feature = "partialeq_path", since = "1.6.0")]
2724 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2726 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2729 #[stable(feature = "partialeq_path", since = "1.6.0")]
2730 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2732 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2735 #[stable(feature = "cmp_path", since = "1.8.0")]
2736 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2738 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2739 <Path as PartialOrd>::partial_cmp(self, other)
2743 #[stable(feature = "cmp_path", since = "1.8.0")]
2744 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2746 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2747 <Path as PartialOrd>::partial_cmp(self, other)
2753 impl_cmp!(PathBuf, Path);
2754 impl_cmp!(PathBuf, &'a Path);
2755 impl_cmp!(Cow<'a, Path>, Path);
2756 impl_cmp!(Cow<'a, Path>, &'b Path);
2757 impl_cmp!(Cow<'a, Path>, PathBuf);
2759 macro_rules! impl_cmp_os_str {
2760 ($lhs:ty, $rhs: ty) => {
2761 #[stable(feature = "cmp_path", since = "1.8.0")]
2762 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2764 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2767 #[stable(feature = "cmp_path", since = "1.8.0")]
2768 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2770 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2773 #[stable(feature = "cmp_path", since = "1.8.0")]
2774 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2776 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2777 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2781 #[stable(feature = "cmp_path", since = "1.8.0")]
2782 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2784 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2785 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2791 impl_cmp_os_str!(PathBuf, OsStr);
2792 impl_cmp_os_str!(PathBuf, &'a OsStr);
2793 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2794 impl_cmp_os_str!(PathBuf, OsString);
2795 impl_cmp_os_str!(Path, OsStr);
2796 impl_cmp_os_str!(Path, &'a OsStr);
2797 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2798 impl_cmp_os_str!(Path, OsString);
2799 impl_cmp_os_str!(&'a Path, OsStr);
2800 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2801 impl_cmp_os_str!(&'a Path, OsString);
2802 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2803 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2804 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2806 #[stable(since = "1.7.0", feature = "strip_prefix")]
2807 impl fmt::Display for StripPrefixError {
2808 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2809 self.description().fmt(f)
2813 #[stable(since = "1.7.0", feature = "strip_prefix")]
2814 impl Error for StripPrefixError {
2815 fn description(&self) -> &str { "prefix not found" }
2823 use crate::sync::Arc;
2826 ($path:expr, iter: $iter:expr) => (
2828 let path = Path::new($path);
2830 // Forward iteration
2831 let comps = path.iter()
2832 .map(|p| p.to_string_lossy().into_owned())
2833 .collect::<Vec<String>>();
2834 let exp: &[&str] = &$iter;
2835 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2836 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2839 // Reverse iteration
2840 let comps = Path::new($path).iter().rev()
2841 .map(|p| p.to_string_lossy().into_owned())
2842 .collect::<Vec<String>>();
2843 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2844 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2849 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2851 let path = Path::new($path);
2853 let act_root = path.has_root();
2854 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2855 $has_root, act_root);
2857 let act_abs = path.is_absolute();
2858 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2859 $is_absolute, act_abs);
2863 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2865 let path = Path::new($path);
2867 let parent = path.parent().map(|p| p.to_str().unwrap());
2868 let exp_parent: Option<&str> = $parent;
2869 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2870 exp_parent, parent);
2872 let file = path.file_name().map(|p| p.to_str().unwrap());
2873 let exp_file: Option<&str> = $file;
2874 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2879 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2881 let path = Path::new($path);
2883 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2884 let exp_stem: Option<&str> = $file_stem;
2885 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2888 let ext = path.extension().map(|p| p.to_str().unwrap());
2889 let exp_ext: Option<&str> = $extension;
2890 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2895 ($path:expr, iter: $iter:expr,
2896 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2897 parent: $parent:expr, file_name: $file:expr,
2898 file_stem: $file_stem:expr, extension: $extension:expr) => (
2900 t!($path, iter: $iter);
2901 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2902 t!($path, parent: $parent, file_name: $file);
2903 t!($path, file_stem: $file_stem, extension: $extension);
2910 use crate::borrow::Cow;
2912 let static_path = Path::new("/home/foo");
2913 let static_cow_path: Cow<'static, Path> = static_path.into();
2914 let pathbuf = PathBuf::from("/home/foo");
2917 let path: &Path = &pathbuf;
2918 let borrowed_cow_path: Cow<Path> = path.into();
2920 assert_eq!(static_cow_path, borrowed_cow_path);
2923 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2925 assert_eq!(static_cow_path, owned_cow_path);
2930 pub fn test_decompositions_unix() {
2946 file_name: Some("foo"),
2947 file_stem: Some("foo"),
2966 file_name: Some("foo"),
2967 file_stem: Some("foo"),
2976 file_name: Some("foo"),
2977 file_stem: Some("foo"),
2986 file_name: Some("foo"),
2987 file_stem: Some("foo"),
2992 iter: ["foo", "bar"],
2995 parent: Some("foo"),
2996 file_name: Some("bar"),
2997 file_stem: Some("bar"),
3002 iter: ["/", "foo", "bar"],
3005 parent: Some("/foo"),
3006 file_name: Some("bar"),
3007 file_stem: Some("bar"),
3016 file_name: Some("foo"),
3017 file_stem: Some("foo"),
3022 iter: ["/", "foo", "bar"],
3025 parent: Some("///foo"),
3026 file_name: Some("bar"),
3027 file_stem: Some("bar"),
3066 file_name: Some("foo"),
3067 file_stem: Some("foo"),
3072 iter: ["foo", ".."],
3075 parent: Some("foo"),
3086 file_name: Some("foo"),
3087 file_stem: Some("foo"),
3092 iter: ["foo", "bar"],
3095 parent: Some("foo"),
3096 file_name: Some("bar"),
3097 file_stem: Some("bar"),
3102 iter: ["foo", ".."],
3105 parent: Some("foo"),
3112 iter: ["foo", "..", "bar"],
3115 parent: Some("foo/.."),
3116 file_name: Some("bar"),
3117 file_stem: Some("bar"),
3126 file_name: Some("a"),
3127 file_stem: Some("a"),
3156 file_name: Some("b"),
3157 file_stem: Some("b"),
3166 file_name: Some("b"),
3167 file_stem: Some("b"),
3176 file_name: Some("b"),
3177 file_stem: Some("b"),
3182 iter: ["a", "b", "c"],
3185 parent: Some("a/b"),
3186 file_name: Some("c"),
3187 file_stem: Some("c"),
3196 file_name: Some(".foo"),
3197 file_stem: Some(".foo"),
3204 pub fn test_decompositions_windows() {
3220 file_name: Some("foo"),
3221 file_stem: Some("foo"),
3276 iter: ["\\", "foo"],
3280 file_name: Some("foo"),
3281 file_stem: Some("foo"),
3290 file_name: Some("foo"),
3291 file_stem: Some("foo"),
3296 iter: ["\\", "foo"],
3300 file_name: Some("foo"),
3301 file_stem: Some("foo"),
3306 iter: ["foo", "bar"],
3309 parent: Some("foo"),
3310 file_name: Some("bar"),
3311 file_stem: Some("bar"),
3316 iter: ["\\", "foo", "bar"],
3319 parent: Some("/foo"),
3320 file_name: Some("bar"),
3321 file_stem: Some("bar"),
3326 iter: ["\\", "foo"],
3330 file_name: Some("foo"),
3331 file_stem: Some("foo"),
3336 iter: ["\\", "foo", "bar"],
3339 parent: Some("///foo"),
3340 file_name: Some("bar"),
3341 file_stem: Some("bar"),
3380 file_name: Some("foo"),
3381 file_stem: Some("foo"),
3386 iter: ["foo", ".."],
3389 parent: Some("foo"),
3400 file_name: Some("foo"),
3401 file_stem: Some("foo"),
3406 iter: ["foo", "bar"],
3409 parent: Some("foo"),
3410 file_name: Some("bar"),
3411 file_stem: Some("bar"),
3416 iter: ["foo", ".."],
3419 parent: Some("foo"),
3426 iter: ["foo", "..", "bar"],
3429 parent: Some("foo/.."),
3430 file_name: Some("bar"),
3431 file_stem: Some("bar"),
3440 file_name: Some("a"),
3441 file_stem: Some("a"),
3470 file_name: Some("b"),
3471 file_stem: Some("b"),
3480 file_name: Some("b"),
3481 file_stem: Some("b"),
3490 file_name: Some("b"),
3491 file_stem: Some("b"),
3496 iter: ["a", "b", "c"],
3499 parent: Some("a/b"),
3500 file_name: Some("c"),
3501 file_stem: Some("c"),
3505 iter: ["a", "b", "c"],
3508 parent: Some("a\\b"),
3509 file_name: Some("c"),
3510 file_stem: Some("c"),
3519 file_name: Some("a"),
3520 file_stem: Some("a"),
3525 iter: ["c:", "\\", "foo.txt"],
3528 parent: Some("c:\\"),
3529 file_name: Some("foo.txt"),
3530 file_stem: Some("foo"),
3531 extension: Some("txt")
3534 t!("\\\\server\\share\\foo.txt",
3535 iter: ["\\\\server\\share", "\\", "foo.txt"],
3538 parent: Some("\\\\server\\share\\"),
3539 file_name: Some("foo.txt"),
3540 file_stem: Some("foo"),
3541 extension: Some("txt")
3544 t!("\\\\server\\share",
3545 iter: ["\\\\server\\share", "\\"],
3555 iter: ["\\", "server"],
3559 file_name: Some("server"),
3560 file_stem: Some("server"),
3564 t!("\\\\?\\bar\\foo.txt",
3565 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3568 parent: Some("\\\\?\\bar\\"),
3569 file_name: Some("foo.txt"),
3570 file_stem: Some("foo"),
3571 extension: Some("txt")
3575 iter: ["\\\\?\\bar"],
3594 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3595 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3598 parent: Some("\\\\?\\UNC\\server\\share\\"),
3599 file_name: Some("foo.txt"),
3600 file_stem: Some("foo"),
3601 extension: Some("txt")
3604 t!("\\\\?\\UNC\\server",
3605 iter: ["\\\\?\\UNC\\server"],
3615 iter: ["\\\\?\\UNC\\"],
3624 t!("\\\\?\\C:\\foo.txt",
3625 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3628 parent: Some("\\\\?\\C:\\"),
3629 file_name: Some("foo.txt"),
3630 file_stem: Some("foo"),
3631 extension: Some("txt")
3636 iter: ["\\\\?\\C:", "\\"],
3647 iter: ["\\\\?\\C:"],
3657 t!("\\\\?\\foo/bar",
3658 iter: ["\\\\?\\foo/bar"],
3669 iter: ["\\\\?\\C:/foo"],
3679 t!("\\\\.\\foo\\bar",
3680 iter: ["\\\\.\\foo", "\\", "bar"],
3683 parent: Some("\\\\.\\foo\\"),
3684 file_name: Some("bar"),
3685 file_stem: Some("bar"),
3691 iter: ["\\\\.\\foo", "\\"],
3701 t!("\\\\.\\foo/bar",
3702 iter: ["\\\\.\\foo/bar", "\\"],
3712 t!("\\\\.\\foo\\bar/baz",
3713 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3716 parent: Some("\\\\.\\foo\\bar"),
3717 file_name: Some("baz"),
3718 file_stem: Some("baz"),
3724 iter: ["\\\\.\\", "\\"],
3734 iter: ["\\\\?\\a", "\\", "b"],
3737 parent: Some("\\\\?\\a\\"),
3738 file_name: Some("b"),
3739 file_stem: Some("b"),
3745 pub fn test_stem_ext() {
3747 file_stem: Some("foo"),
3752 file_stem: Some("foo"),
3757 file_stem: Some(".foo"),
3762 file_stem: Some("foo"),
3763 extension: Some("txt")
3767 file_stem: Some("foo.bar"),
3768 extension: Some("txt")
3772 file_stem: Some("foo.bar"),
3793 pub fn test_push() {
3795 ($path:expr, $push:expr, $expected:expr) => ( {
3796 let mut actual = PathBuf::from($path);
3798 assert!(actual.to_str() == Some($expected),
3799 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3800 $push, $path, $expected, actual.to_str().unwrap());
3804 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3805 tp!("", "foo", "foo");
3806 tp!("foo", "bar", "foo/bar");
3807 tp!("foo/", "bar", "foo/bar");
3808 tp!("foo//", "bar", "foo//bar");
3809 tp!("foo/.", "bar", "foo/./bar");
3810 tp!("foo./.", "bar", "foo././bar");
3811 tp!("foo", "", "foo/");
3812 tp!("foo", ".", "foo/.");
3813 tp!("foo", "..", "foo/..");
3814 tp!("foo", "/", "/");
3815 tp!("/foo/bar", "/", "/");
3816 tp!("/foo/bar", "/baz", "/baz");
3817 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3819 tp!("", "foo", "foo");
3820 tp!("foo", "bar", r"foo\bar");
3821 tp!("foo/", "bar", r"foo/bar");
3822 tp!(r"foo\", "bar", r"foo\bar");
3823 tp!("foo//", "bar", r"foo//bar");
3824 tp!(r"foo\\", "bar", r"foo\\bar");
3825 tp!("foo/.", "bar", r"foo/.\bar");
3826 tp!("foo./.", "bar", r"foo./.\bar");
3827 tp!(r"foo\.", "bar", r"foo\.\bar");
3828 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3829 tp!("foo", "", "foo\\");
3830 tp!("foo", ".", r"foo\.");
3831 tp!("foo", "..", r"foo\..");
3832 tp!("foo", "/", "/");
3833 tp!("foo", r"\", r"\");
3834 tp!("/foo/bar", "/", "/");
3835 tp!(r"\foo\bar", r"\", r"\");
3836 tp!("/foo/bar", "/baz", "/baz");
3837 tp!("/foo/bar", r"\baz", r"\baz");
3838 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3839 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3841 tp!("c:\\", "windows", "c:\\windows");
3842 tp!("c:", "windows", "c:windows");
3844 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3845 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3846 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3847 tp!("a\\b", "\\c\\d", "\\c\\d");
3848 tp!("a\\b", ".", "a\\b\\.");
3849 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3850 tp!("a\\b", "C:a.txt", "C:a.txt");
3851 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3852 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3853 tp!("C:\\a\\b\\c", "C:d", "C:d");
3854 tp!("C:a\\b\\c", "C:d", "C:d");
3855 tp!("C:", r"a\b\c", r"C:a\b\c");
3856 tp!("C:", r"..\a", r"C:..\a");
3857 tp!("\\\\server\\share\\foo",
3859 "\\\\server\\share\\foo\\bar");
3860 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3861 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3862 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3863 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3864 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3865 tp!("\\\\?\\UNC\\server\\share\\foo",
3867 "\\\\?\\UNC\\server\\share\\foo\\bar");
3868 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3869 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3871 // Note: modified from old path API
3872 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3875 "\\\\?\\UNC\\server\\share",
3876 "\\\\?\\UNC\\server\\share");
3877 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3878 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3879 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3880 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3882 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3889 ($path:expr, $expected:expr, $output:expr) => ( {
3890 let mut actual = PathBuf::from($path);
3891 let output = actual.pop();
3892 assert!(actual.to_str() == Some($expected) && output == $output,
3893 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3894 $path, $expected, $output,
3895 actual.to_str().unwrap(), output);
3900 tp!("/", "/", false);
3901 tp!("foo", "", true);
3903 tp!("/foo", "/", true);
3904 tp!("/foo/bar", "/foo", true);
3905 tp!("foo/bar", "foo", true);
3906 tp!("foo/.", "", true);
3907 tp!("foo//bar", "foo", true);
3910 tp!("a\\b\\c", "a\\b", true);
3911 tp!("\\a", "\\", true);
3912 tp!("\\", "\\", false);
3914 tp!("C:\\a\\b", "C:\\a", true);
3915 tp!("C:\\a", "C:\\", true);
3916 tp!("C:\\", "C:\\", false);
3917 tp!("C:a\\b", "C:a", true);
3918 tp!("C:a", "C:", true);
3919 tp!("C:", "C:", false);
3920 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3921 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3922 tp!("\\\\server\\share", "\\\\server\\share", false);
3923 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3924 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3925 tp!("\\\\?\\a", "\\\\?\\a", false);
3926 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3927 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3928 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3929 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3930 "\\\\?\\UNC\\server\\share\\a",
3932 tp!("\\\\?\\UNC\\server\\share\\a",
3933 "\\\\?\\UNC\\server\\share\\",
3935 tp!("\\\\?\\UNC\\server\\share",
3936 "\\\\?\\UNC\\server\\share",
3938 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3939 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3940 tp!("\\\\.\\a", "\\\\.\\a", false);
3942 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3947 pub fn test_set_file_name() {
3949 ($path:expr, $file:expr, $expected:expr) => ( {
3950 let mut p = PathBuf::from($path);
3951 p.set_file_name($file);
3952 assert!(p.to_str() == Some($expected),
3953 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3954 $path, $file, $expected,
3955 p.to_str().unwrap());
3959 tfn!("foo", "foo", "foo");
3960 tfn!("foo", "bar", "bar");
3961 tfn!("foo", "", "");
3962 tfn!("", "foo", "foo");
3963 if cfg!(unix) || cfg!(all(target_env = "sgx", target_vendor = "fortanix")) {
3964 tfn!(".", "foo", "./foo");
3965 tfn!("foo/", "bar", "bar");
3966 tfn!("foo/.", "bar", "bar");
3967 tfn!("..", "foo", "../foo");
3968 tfn!("foo/..", "bar", "foo/../bar");
3969 tfn!("/", "foo", "/foo");
3971 tfn!(".", "foo", r".\foo");
3972 tfn!(r"foo\", "bar", r"bar");
3973 tfn!(r"foo\.", "bar", r"bar");
3974 tfn!("..", "foo", r"..\foo");
3975 tfn!(r"foo\..", "bar", r"foo\..\bar");
3976 tfn!(r"\", "foo", r"\foo");
3981 pub fn test_set_extension() {
3983 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3984 let mut p = PathBuf::from($path);
3985 let output = p.set_extension($ext);
3986 assert!(p.to_str() == Some($expected) && output == $output,
3987 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3988 $path, $ext, $expected, $output,
3989 p.to_str().unwrap(), output);
3993 tfe!("foo", "txt", "foo.txt", true);
3994 tfe!("foo.bar", "txt", "foo.txt", true);
3995 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3996 tfe!(".test", "txt", ".test.txt", true);
3997 tfe!("foo.txt", "", "foo", true);
3998 tfe!("foo", "", "foo", true);
3999 tfe!("", "foo", "", false);
4000 tfe!(".", "foo", ".", false);
4001 tfe!("foo/", "bar", "foo.bar", true);
4002 tfe!("foo/.", "bar", "foo.bar", true);
4003 tfe!("..", "foo", "..", false);
4004 tfe!("foo/..", "bar", "foo/..", false);
4005 tfe!("/", "foo", "/", false);
4009 fn test_eq_receivers() {
4010 use crate::borrow::Cow;
4012 let borrowed: &Path = Path::new("foo/bar");
4013 let mut owned: PathBuf = PathBuf::new();
4016 let borrowed_cow: Cow<Path> = borrowed.into();
4017 let owned_cow: Cow<Path> = owned.clone().into();
4020 ($($current:expr),+) => {
4022 assert_eq!($current, borrowed);
4023 assert_eq!($current, owned);
4024 assert_eq!($current, borrowed_cow);
4025 assert_eq!($current, owned_cow);
4030 t!(borrowed, owned, borrowed_cow, owned_cow);
4034 pub fn test_compare() {
4035 use crate::hash::{Hash, Hasher};
4036 use crate::collections::hash_map::DefaultHasher;
4038 fn hash<T: Hash>(t: T) -> u64 {
4039 let mut s = DefaultHasher::new();
4045 ($path1:expr, $path2:expr, eq: $eq:expr,
4046 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
4047 relative_from: $relative_from:expr) => ({
4048 let path1 = Path::new($path1);
4049 let path2 = Path::new($path2);
4051 let eq = path1 == path2;
4052 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
4053 $path1, $path2, $eq, eq);
4054 assert!($eq == (hash(path1) == hash(path2)),
4055 "{:?} == {:?}, expected {:?}, got {} and {}",
4056 $path1, $path2, $eq, hash(path1), hash(path2));
4058 let starts_with = path1.starts_with(path2);
4059 assert!(starts_with == $starts_with,
4060 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4061 $starts_with, starts_with);
4063 let ends_with = path1.ends_with(path2);
4064 assert!(ends_with == $ends_with,
4065 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
4066 $ends_with, ends_with);
4068 let relative_from = path1.strip_prefix(path2)
4069 .map(|p| p.to_str().unwrap())
4071 let exp: Option<&str> = $relative_from;
4072 assert!(relative_from == exp,
4073 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4074 $path1, $path2, exp, relative_from);
4082 relative_from: Some("")
4089 relative_from: Some("foo")
4103 relative_from: Some("")
4110 relative_from: Some("")
4113 tc!("foo/bar", "foo",
4117 relative_from: Some("bar")
4120 tc!("foo/bar/baz", "foo/bar",
4124 relative_from: Some("baz")
4127 tc!("foo/bar", "foo/bar/baz",
4134 tc!("./foo/bar/", ".",
4138 relative_from: Some("foo/bar")
4142 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4143 r"c:\src\rust\cargo-test\test",
4147 relative_from: Some("Cargo.toml")
4150 tc!(r"c:\foo", r"C:\foo",
4154 relative_from: Some("")
4160 fn test_components_debug() {
4161 let path = Path::new("/tmp");
4163 let mut components = path.components();
4165 let expected = "Components([RootDir, Normal(\"tmp\")])";
4166 let actual = format!("{:?}", components);
4167 assert_eq!(expected, actual);
4169 let _ = components.next().unwrap();
4170 let expected = "Components([Normal(\"tmp\")])";
4171 let actual = format!("{:?}", components);
4172 assert_eq!(expected, actual);
4174 let _ = components.next().unwrap();
4175 let expected = "Components([])";
4176 let actual = format!("{:?}", components);
4177 assert_eq!(expected, actual);
4182 fn test_iter_debug() {
4183 let path = Path::new("/tmp");
4185 let mut iter = path.iter();
4187 let expected = "Iter([\"/\", \"tmp\"])";
4188 let actual = format!("{:?}", iter);
4189 assert_eq!(expected, actual);
4191 let _ = iter.next().unwrap();
4192 let expected = "Iter([\"tmp\"])";
4193 let actual = format!("{:?}", iter);
4194 assert_eq!(expected, actual);
4196 let _ = iter.next().unwrap();
4197 let expected = "Iter([])";
4198 let actual = format!("{:?}", iter);
4199 assert_eq!(expected, actual);
4204 let orig: &str = "some/sort/of/path";
4205 let path = Path::new(orig);
4206 let boxed: Box<Path> = Box::from(path);
4207 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4208 assert_eq!(path, &*boxed);
4209 assert_eq!(&*boxed, &*path_buf);
4210 assert_eq!(&*path_buf, path);
4214 fn test_clone_into() {
4215 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4216 let path = Path::new("short");
4217 path.clone_into(&mut path_buf);
4218 assert_eq!(path, path_buf);
4219 assert!(path_buf.into_os_string().capacity() >= 15);
4223 fn display_format_flags() {
4224 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4225 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4230 let orig = "hello/world";
4231 let path = Path::new(orig);
4232 let rc: Rc<Path> = Rc::from(path);
4233 let arc: Arc<Path> = Arc::from(path);
4235 assert_eq!(&*rc, path);
4236 assert_eq!(&*arc, path);
4238 let rc2: Rc<Path> = Rc::from(path.to_owned());
4239 let arc2: Arc<Path> = Arc::from(path.to_owned());
4241 assert_eq!(&*rc2, path);
4242 assert_eq!(&*arc2, path);