1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Cross-platform path manipulation.
13 //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
14 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
15 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
16 //! on strings according to the local platform's path syntax.
18 //! Paths can be parsed into [`Component`]s by iterating over the structure
19 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
20 //! correspond to the substrings between path separators (`/` or `\`). You can
21 //! reconstruct an equivalent path from components with the [`push`] method on
22 //! [`PathBuf`]; note that the paths may differ syntactically by the
23 //! normalization described in the documentation for the [`components`] method.
27 //! Path manipulation includes both parsing components from slices and building
30 //! To parse a path, you can create a [`Path`] slice from a [`str`]
31 //! slice and start asking questions:
34 //! use std::path::Path;
35 //! use std::ffi::OsStr;
37 //! let path = Path::new("/tmp/foo/bar.txt");
39 //! let parent = path.parent();
40 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
42 //! let file_stem = path.file_stem();
43 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
45 //! let extension = path.extension();
46 //! assert_eq!(extension, Some(OsStr::new("txt")));
49 //! To build or modify paths, use [`PathBuf`]:
52 //! use std::path::PathBuf;
54 //! // This way works...
55 //! let mut path = PathBuf::from("c:\\");
57 //! path.push("windows");
58 //! path.push("system32");
60 //! path.set_extension("dll");
62 //! // ... but push is best used if you don't know everything up
63 //! // front. If you do, this way is better:
64 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
67 //! [`Component`]: ../../std/path/enum.Component.html
68 //! [`components`]: ../../std/path/struct.Path.html#method.components
69 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
70 //! [`Path`]: ../../std/path/struct.Path.html
71 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
72 //! [`String`]: ../../std/string/struct.String.html
74 //! [`str`]: ../../std/primitive.str.html
75 //! [`OsString`]: ../../std/ffi/struct.OsString.html
76 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
78 #![stable(feature = "rust1", since = "1.0.0")]
80 use borrow::{Borrow, Cow};
85 use hash::{Hash, Hasher};
87 use iter::{self, FusedIterator};
88 use ops::{self, Deref};
92 use ffi::{OsStr, OsString};
94 use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
96 ////////////////////////////////////////////////////////////////////////////////
98 ////////////////////////////////////////////////////////////////////////////////
100 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
101 // taking advantage of the fact that OsStr always encodes ASCII characters
102 // as-is. Eventually, this transmutation should be replaced by direct uses of
103 // OsStr APIs for parsing, but it will take a while for those to become
106 ////////////////////////////////////////////////////////////////////////////////
108 ////////////////////////////////////////////////////////////////////////////////
110 /// Windows path prefixes, e.g. `C:` or `\\server\share`.
112 /// Windows uses a variety of path prefix styles, including references to drive
113 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
114 /// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
115 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
116 /// no normalization is performed.
121 /// use std::path::{Component, Path, Prefix};
122 /// use std::path::Prefix::*;
123 /// use std::ffi::OsStr;
125 /// fn get_path_prefix(s: &str) -> Prefix {
126 /// let path = Path::new(s);
127 /// match path.components().next().unwrap() {
128 /// Component::Prefix(prefix_component) => prefix_component.kind(),
133 /// # if cfg!(windows) {
134 /// assert_eq!(Verbatim(OsStr::new("pictures")),
135 /// get_path_prefix(r"\\?\pictures\kittens"));
136 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
137 /// get_path_prefix(r"\\?\UNC\server\share"));
138 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
139 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
140 /// get_path_prefix(r"\\.\BrainInterface"));
141 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
142 /// get_path_prefix(r"\\server\share"));
143 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
146 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub enum Prefix<'a> {
149 /// Verbatim prefix, e.g. `\\?\cat_pics`.
151 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
153 #[stable(feature = "rust1", since = "1.0.0")]
154 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
156 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
157 /// e.g. `\\?\UNC\server\share`.
159 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
160 /// server's hostname and a share name.
161 #[stable(feature = "rust1", since = "1.0.0")]
163 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
164 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
167 /// Verbatim disk prefix, e.g. `\\?\C:\`.
169 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
170 /// drive letter and `:\`.
171 #[stable(feature = "rust1", since = "1.0.0")]
172 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
174 /// Device namespace prefix, e.g. `\\.\COM42`.
176 /// Device namespace prefixes consist of `\\.\` immediately followed by the
178 #[stable(feature = "rust1", since = "1.0.0")]
179 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
181 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
182 /// `\\server\share`.
184 /// UNC prefixes consist of the server's hostname and a share name.
185 #[stable(feature = "rust1", since = "1.0.0")]
187 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
188 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
191 /// Prefix `C:` for the given disk drive.
192 #[stable(feature = "rust1", since = "1.0.0")]
193 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
196 impl<'a> Prefix<'a> {
198 fn len(&self) -> usize {
200 fn os_str_len(s: &OsStr) -> usize {
201 os_str_as_u8_slice(s).len()
204 Verbatim(x) => 4 + os_str_len(x),
205 VerbatimUNC(x, y) => {
207 if os_str_len(y) > 0 {
213 VerbatimDisk(_) => 6,
216 if os_str_len(y) > 0 {
222 DeviceNS(x) => 4 + os_str_len(x),
228 /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
233 /// use std::path::Prefix::*;
234 /// use std::ffi::OsStr;
236 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
237 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
238 /// assert!(VerbatimDisk(b'C').is_verbatim());
239 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
240 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
241 /// assert!(!Disk(b'C').is_verbatim());
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn is_verbatim(&self) -> bool {
248 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
254 fn is_drive(&self) -> bool {
256 Prefix::Disk(_) => true,
262 fn has_implicit_root(&self) -> bool {
267 ////////////////////////////////////////////////////////////////////////////////
268 // Exposed parsing helpers
269 ////////////////////////////////////////////////////////////////////////////////
271 /// Determines whether the character is one of the permitted path
272 /// separators for the current platform.
279 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
280 /// assert!(!path::is_separator('❤'));
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn is_separator(c: char) -> bool {
284 c.is_ascii() && is_sep_byte(c as u8)
287 /// The primary separator of path components for the current platform.
289 /// For example, `/` on Unix and `\` on Windows.
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
293 ////////////////////////////////////////////////////////////////////////////////
295 ////////////////////////////////////////////////////////////////////////////////
297 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
298 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
299 // `iter` after having exhausted `prefix`.
300 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
301 where I: Iterator<Item = A> + Clone,
302 J: Iterator<Item = A>,
306 let mut iter_next = iter.clone();
307 match (iter_next.next(), prefix.next()) {
308 (Some(ref x), Some(ref y)) if x == y => (),
309 (Some(_), Some(_)) => return None,
310 (Some(_), None) => return Some(iter),
311 (None, None) => return Some(iter),
312 (None, Some(_)) => return None,
318 // See note at the top of this module to understand why these are used:
319 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
320 unsafe { &*(s as *const OsStr as *const [u8]) }
322 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
323 &*(s as *const [u8] as *const OsStr)
326 // Detect scheme on Redox
327 fn has_redox_scheme(s: &[u8]) -> bool {
328 cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
331 ////////////////////////////////////////////////////////////////////////////////
332 // Cross-platform, iterator-independent parsing
333 ////////////////////////////////////////////////////////////////////////////////
335 /// Says whether the first byte after the prefix is a separator.
336 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
337 let path = if let Some(p) = prefix {
342 !path.is_empty() && is_sep_byte(path[0])
345 // basic workhorse for splitting stem and extension
346 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
348 if os_str_as_u8_slice(file) == b".." {
349 return (Some(file), None);
352 // The unsafety here stems from converting between &OsStr and &[u8]
353 // and back. This is safe to do because (1) we only look at ASCII
354 // contents of the encoding and (2) new &OsStr values are produced
355 // only from ASCII-bounded slices of existing &OsStr values.
357 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
358 let after = iter.next();
359 let before = iter.next();
360 if before == Some(b"") {
363 (before.map(|s| u8_slice_as_os_str(s)),
364 after.map(|s| u8_slice_as_os_str(s)))
369 ////////////////////////////////////////////////////////////////////////////////
370 // The core iterators
371 ////////////////////////////////////////////////////////////////////////////////
373 /// Component parsing works by a double-ended state machine; the cursors at the
374 /// front and back of the path each keep track of what parts of the path have
375 /// been consumed so far.
377 /// Going front to back, a path is made up of a prefix, a starting
378 /// directory component, and a body (of normal components)
379 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
382 StartDir = 1, // / or . or nothing
383 Body = 2, // foo/bar/baz
387 /// A structure wrapping a Windows path prefix as well as its unparsed string
390 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
391 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
392 /// returned by [`as_os_str`].
394 /// Instances of this `struct` can be obtained by matching against the
395 /// [`Prefix` variant] on [`Component`].
397 /// Does not occur on Unix.
402 /// # if cfg!(windows) {
403 /// use std::path::{Component, Path, Prefix};
404 /// use std::ffi::OsStr;
406 /// let path = Path::new(r"c:\you\later\");
407 /// match path.components().next().unwrap() {
408 /// Component::Prefix(prefix_component) => {
409 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
410 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
412 /// _ => unreachable!(),
417 /// [`as_os_str`]: #method.as_os_str
418 /// [`Component`]: enum.Component.html
419 /// [`kind`]: #method.kind
420 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
421 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
422 /// [`Prefix`]: enum.Prefix.html
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[derive(Copy, Clone, Eq, Debug)]
425 pub struct PrefixComponent<'a> {
426 /// The prefix as an unparsed `OsStr` slice.
429 /// The parsed prefix data.
433 impl<'a> PrefixComponent<'a> {
434 /// Returns the parsed prefix data.
436 /// See [`Prefix`]'s documentation for more information on the different
437 /// kinds of prefixes.
439 /// [`Prefix`]: enum.Prefix.html
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn kind(&self) -> Prefix<'a> {
445 /// Returns the raw [`OsStr`] slice for this prefix.
447 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn as_os_str(&self) -> &'a OsStr {
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
456 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
457 cmp::PartialEq::eq(&self.parsed, &other.parsed)
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
463 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
464 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
468 #[stable(feature = "rust1", since = "1.0.0")]
469 impl<'a> cmp::Ord for PrefixComponent<'a> {
470 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
471 cmp::Ord::cmp(&self.parsed, &other.parsed)
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl<'a> Hash for PrefixComponent<'a> {
477 fn hash<H: Hasher>(&self, h: &mut H) {
482 /// A single component of a path.
484 /// A `Component` roughly corresponds to a substring between path separators
487 /// This `enum` is created by iterating over [`Components`], which in turn is
488 /// created by the [`components`][`Path::components`] method on [`Path`].
493 /// use std::path::{Component, Path};
495 /// let path = Path::new("/tmp/foo/bar.txt");
496 /// let components = path.components().collect::<Vec<_>>();
497 /// assert_eq!(&components, &[
498 /// Component::RootDir,
499 /// Component::Normal("tmp".as_ref()),
500 /// Component::Normal("foo".as_ref()),
501 /// Component::Normal("bar.txt".as_ref()),
505 /// [`Components`]: struct.Components.html
506 /// [`Path`]: struct.Path.html
507 /// [`Path::components`]: struct.Path.html#method.components
508 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub enum Component<'a> {
511 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
513 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
516 /// Does not occur on Unix.
518 /// [`Prefix`]: enum.Prefix.html
519 #[stable(feature = "rust1", since = "1.0.0")]
521 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
524 /// The root directory component, appears after any prefix and before anything else.
526 /// It represents a separator that designates that a path starts from root.
527 #[stable(feature = "rust1", since = "1.0.0")]
530 /// A reference to the current directory, i.e. `.`.
531 #[stable(feature = "rust1", since = "1.0.0")]
534 /// A reference to the parent directory, i.e. `..`.
535 #[stable(feature = "rust1", since = "1.0.0")]
538 /// A normal component, e.g. `a` and `b` in `a/b`.
540 /// This variant is the most common one, it represents references to files
542 #[stable(feature = "rust1", since = "1.0.0")]
543 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
546 impl<'a> Component<'a> {
547 /// Extracts the underlying [`OsStr`] slice.
552 /// use std::path::Path;
554 /// let path = Path::new("./tmp/foo/bar.txt");
555 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
556 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
559 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
560 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn as_os_str(self) -> &'a OsStr {
563 Component::Prefix(p) => p.as_os_str(),
564 Component::RootDir => OsStr::new(MAIN_SEP_STR),
565 Component::CurDir => OsStr::new("."),
566 Component::ParentDir => OsStr::new(".."),
567 Component::Normal(path) => path,
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<'a> AsRef<OsStr> for Component<'a> {
574 fn as_ref(&self) -> &OsStr {
579 #[stable(feature = "path_component_asref", since = "1.25.0")]
580 impl<'a> AsRef<Path> for Component<'a> {
581 fn as_ref(&self) -> &Path {
582 self.as_os_str().as_ref()
586 /// An iterator over the [`Component`]s of a [`Path`].
588 /// This `struct` is created by the [`components`] method on [`Path`].
589 /// See its documentation for more.
594 /// use std::path::Path;
596 /// let path = Path::new("/tmp/foo/bar.txt");
598 /// for component in path.components() {
599 /// println!("{:?}", component);
603 /// [`Component`]: enum.Component.html
604 /// [`components`]: struct.Path.html#method.components
605 /// [`Path`]: struct.Path.html
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub struct Components<'a> {
609 // The path left to parse components from
612 // The prefix as it was originally parsed, if any
613 prefix: Option<Prefix<'a>>,
615 // true if path *physically* has a root separator; for most Windows
616 // prefixes, it may have a "logical" rootseparator for the purposes of
617 // normalization, e.g. \\server\share == \\server\share\.
618 has_physical_root: bool,
620 // The iterator is double-ended, and these two states keep track of what has
621 // been produced from either end
626 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
628 /// This `struct` is created by the [`iter`] method on [`Path`].
629 /// See its documentation for more.
631 /// [`Component`]: enum.Component.html
632 /// [`iter`]: struct.Path.html#method.iter
633 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
634 /// [`Path`]: struct.Path.html
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub struct Iter<'a> {
638 inner: Components<'a>,
641 #[stable(feature = "path_components_debug", since = "1.13.0")]
642 impl<'a> fmt::Debug for Components<'a> {
643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
644 struct DebugHelper<'a>(&'a Path);
646 impl<'a> fmt::Debug for DebugHelper<'a> {
647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
649 .entries(self.0.components())
654 f.debug_tuple("Components")
655 .field(&DebugHelper(self.as_path()))
660 impl<'a> Components<'a> {
661 // how long is the prefix, if any?
663 fn prefix_len(&self) -> usize {
664 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
668 fn prefix_verbatim(&self) -> bool {
669 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
672 /// how much of the prefix is left from the point of view of iteration?
674 fn prefix_remaining(&self) -> usize {
675 if self.front == State::Prefix {
682 // Given the iteration so far, how much of the pre-State::Body path is left?
684 fn len_before_body(&self) -> usize {
685 let root = if self.front <= State::StartDir && self.has_physical_root {
690 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
695 self.prefix_remaining() + root + cur_dir
698 // is the iteration complete?
700 fn finished(&self) -> bool {
701 self.front == State::Done || self.back == State::Done || self.front > self.back
705 fn is_sep_byte(&self, b: u8) -> bool {
706 if self.prefix_verbatim() {
713 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
718 /// use std::path::Path;
720 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
721 /// components.next();
722 /// components.next();
724 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn as_path(&self) -> &'a Path {
728 let mut comps = self.clone();
729 if comps.front == State::Body {
732 if comps.back == State::Body {
735 unsafe { Path::from_u8_slice(comps.path) }
738 /// Is the *original* path rooted?
739 fn has_root(&self) -> bool {
740 if self.has_physical_root {
743 if let Some(p) = self.prefix {
744 if p.has_implicit_root() {
751 /// Should the normalized path include a leading . ?
752 fn include_cur_dir(&self) -> bool {
756 let mut iter = self.path[self.prefix_len()..].iter();
757 match (iter.next(), iter.next()) {
758 (Some(&b'.'), None) => true,
759 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
764 // parse a given byte sequence into the corresponding path component
765 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
767 b"." if self.prefix_verbatim() => Some(Component::CurDir),
768 b"." => None, // . components are normalized away, except at
769 // the beginning of a path, which is treated
770 // separately via `include_cur_dir`
771 b".." => Some(Component::ParentDir),
773 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
777 // parse a component from the left, saying how many bytes to consume to
778 // remove the component
779 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
780 debug_assert!(self.front == State::Body);
781 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
782 None => (0, self.path),
783 Some(i) => (1, &self.path[..i]),
785 (comp.len() + extra, self.parse_single_component(comp))
788 // parse a component from the right, saying how many bytes to consume to
789 // remove the component
790 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
791 debug_assert!(self.back == State::Body);
792 let start = self.len_before_body();
793 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
794 None => (0, &self.path[start..]),
795 Some(i) => (1, &self.path[start + i + 1..]),
797 (comp.len() + extra, self.parse_single_component(comp))
800 // trim away repeated separators (i.e. empty components) on the left
801 fn trim_left(&mut self) {
802 while !self.path.is_empty() {
803 let (size, comp) = self.parse_next_component();
807 self.path = &self.path[size..];
812 // trim away repeated separators (i.e. empty components) on the right
813 fn trim_right(&mut self) {
814 while self.path.len() > self.len_before_body() {
815 let (size, comp) = self.parse_next_component_back();
819 self.path = &self.path[..self.path.len() - size];
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<'a> AsRef<Path> for Components<'a> {
827 fn as_ref(&self) -> &Path {
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<'a> AsRef<OsStr> for Components<'a> {
834 fn as_ref(&self) -> &OsStr {
835 self.as_path().as_os_str()
839 #[stable(feature = "path_iter_debug", since = "1.13.0")]
840 impl<'a> fmt::Debug for Iter<'a> {
841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842 struct DebugHelper<'a>(&'a Path);
844 impl<'a> fmt::Debug for DebugHelper<'a> {
845 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847 .entries(self.0.iter())
852 f.debug_tuple("Iter")
853 .field(&DebugHelper(self.as_path()))
859 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
864 /// use std::path::Path;
866 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
870 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn as_path(&self) -> &'a Path {
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<'a> AsRef<Path> for Iter<'a> {
880 fn as_ref(&self) -> &Path {
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a> AsRef<OsStr> for Iter<'a> {
887 fn as_ref(&self) -> &OsStr {
888 self.as_path().as_os_str()
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<'a> Iterator for Iter<'a> {
894 type Item = &'a OsStr;
896 fn next(&mut self) -> Option<&'a OsStr> {
897 self.inner.next().map(Component::as_os_str)
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> DoubleEndedIterator for Iter<'a> {
903 fn next_back(&mut self) -> Option<&'a OsStr> {
904 self.inner.next_back().map(Component::as_os_str)
908 #[stable(feature = "fused", since = "1.25.0")]
909 impl<'a> FusedIterator for Iter<'a> {}
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<'a> Iterator for Components<'a> {
913 type Item = Component<'a>;
915 fn next(&mut self) -> Option<Component<'a>> {
916 while !self.finished() {
918 State::Prefix if self.prefix_len() > 0 => {
919 self.front = State::StartDir;
920 debug_assert!(self.prefix_len() <= self.path.len());
921 let raw = &self.path[..self.prefix_len()];
922 self.path = &self.path[self.prefix_len()..];
923 return Some(Component::Prefix(PrefixComponent {
924 raw: unsafe { u8_slice_as_os_str(raw) },
925 parsed: self.prefix.unwrap(),
929 self.front = State::StartDir;
932 self.front = State::Body;
933 if self.has_physical_root {
934 debug_assert!(!self.path.is_empty());
935 self.path = &self.path[1..];
936 return Some(Component::RootDir);
937 } else if let Some(p) = self.prefix {
938 if p.has_implicit_root() && !p.is_verbatim() {
939 return Some(Component::RootDir);
941 } else if self.include_cur_dir() {
942 debug_assert!(!self.path.is_empty());
943 self.path = &self.path[1..];
944 return Some(Component::CurDir);
947 State::Body if !self.path.is_empty() => {
948 let (size, comp) = self.parse_next_component();
949 self.path = &self.path[size..];
955 self.front = State::Done;
957 State::Done => unreachable!(),
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl<'a> DoubleEndedIterator for Components<'a> {
966 fn next_back(&mut self) -> Option<Component<'a>> {
967 while !self.finished() {
969 State::Body if self.path.len() > self.len_before_body() => {
970 let (size, comp) = self.parse_next_component_back();
971 self.path = &self.path[..self.path.len() - size];
977 self.back = State::StartDir;
980 self.back = State::Prefix;
981 if self.has_physical_root {
982 self.path = &self.path[..self.path.len() - 1];
983 return Some(Component::RootDir);
984 } else if let Some(p) = self.prefix {
985 if p.has_implicit_root() && !p.is_verbatim() {
986 return Some(Component::RootDir);
988 } else if self.include_cur_dir() {
989 self.path = &self.path[..self.path.len() - 1];
990 return Some(Component::CurDir);
993 State::Prefix if self.prefix_len() > 0 => {
994 self.back = State::Done;
995 return Some(Component::Prefix(PrefixComponent {
996 raw: unsafe { u8_slice_as_os_str(self.path) },
997 parsed: self.prefix.unwrap(),
1001 self.back = State::Done;
1004 State::Done => unreachable!(),
1011 #[stable(feature = "fused", since = "1.25.0")]
1012 impl<'a> FusedIterator for Components<'a> {}
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<'a> cmp::PartialEq for Components<'a> {
1016 fn eq(&self, other: &Components<'a>) -> bool {
1017 Iterator::eq(self.clone(), other.clone())
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl<'a> cmp::Eq for Components<'a> {}
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<'a> cmp::PartialOrd for Components<'a> {
1026 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1027 Iterator::partial_cmp(self.clone(), other.clone())
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl<'a> cmp::Ord for Components<'a> {
1033 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
1034 Iterator::cmp(self.clone(), other.clone())
1038 /// An iterator over [`Path`] and its ancestors.
1040 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1041 /// See its documentation for more.
1046 /// #![feature(path_ancestors)]
1048 /// use std::path::Path;
1050 /// let path = Path::new("/foo/bar");
1052 /// for ancestor in path.ancestors() {
1053 /// println!("{}", ancestor.display());
1057 /// [`ancestors`]: struct.Path.html#method.ancestors
1058 /// [`Path`]: struct.Path.html
1059 #[derive(Copy, Clone, Debug)]
1060 #[unstable(feature = "path_ancestors", issue = "48581")]
1061 pub struct Ancestors<'a> {
1062 next: Option<&'a Path>,
1065 #[unstable(feature = "path_ancestors", issue = "48581")]
1066 impl<'a> Iterator for Ancestors<'a> {
1067 type Item = &'a Path;
1069 fn next(&mut self) -> Option<Self::Item> {
1070 let next = self.next;
1071 self.next = match next {
1072 Some(path) => path.parent(),
1079 #[unstable(feature = "fused", issue = "35602")]
1080 impl<'a> FusedIterator for Ancestors<'a> {}
1082 ////////////////////////////////////////////////////////////////////////////////
1083 // Basic types and traits
1084 ////////////////////////////////////////////////////////////////////////////////
1086 /// An owned, mutable path (akin to [`String`]).
1088 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1089 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1090 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1092 /// [`String`]: ../string/struct.String.html
1093 /// [`Path`]: struct.Path.html
1094 /// [`push`]: struct.PathBuf.html#method.push
1095 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1096 /// [`Deref`]: ../ops/trait.Deref.html
1098 /// More details about the overall approach can be found in
1099 /// the [module documentation](index.html).
1103 /// You can use [`push`] to build up a `PathBuf` from
1107 /// use std::path::PathBuf;
1109 /// let mut path = PathBuf::new();
1111 /// path.push(r"C:\");
1112 /// path.push("windows");
1113 /// path.push("system32");
1115 /// path.set_extension("dll");
1118 /// However, [`push`] is best used for dynamic situations. This is a better way
1119 /// to do this when you know all of the components ahead of time:
1122 /// use std::path::PathBuf;
1124 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1127 /// We can still do better than this! Since these are all strings, we can use
1131 /// use std::path::PathBuf;
1133 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1136 /// Which method works best depends on what kind of situation you're in.
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 pub struct PathBuf {
1144 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1145 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1148 /// Allocates an empty `PathBuf`.
1153 /// use std::path::PathBuf;
1155 /// let path = PathBuf::new();
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 pub fn new() -> PathBuf {
1159 PathBuf { inner: OsString::new() }
1162 /// Coerces to a [`Path`] slice.
1164 /// [`Path`]: struct.Path.html
1169 /// use std::path::{Path, PathBuf};
1171 /// let p = PathBuf::from("/test");
1172 /// assert_eq!(Path::new("/test"), p.as_path());
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 pub fn as_path(&self) -> &Path {
1179 /// Extends `self` with `path`.
1181 /// If `path` is absolute, it replaces the current path.
1185 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1186 /// replaces everything except for the prefix (if any) of `self`.
1187 /// * if `path` has a prefix but no root, it replaces `self`.
1191 /// Pushing a relative path extends the existing path:
1194 /// use std::path::PathBuf;
1196 /// let mut path = PathBuf::from("/tmp");
1197 /// path.push("file.bk");
1198 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1201 /// Pushing an absolute path replaces the existing path:
1204 /// use std::path::PathBuf;
1206 /// let mut path = PathBuf::from("/tmp");
1207 /// path.push("/etc");
1208 /// assert_eq!(path, PathBuf::from("/etc"));
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1212 self._push(path.as_ref())
1215 fn _push(&mut self, path: &Path) {
1216 // in general, a separator is needed if the rightmost byte is not a separator
1217 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1219 // in the special case of `C:` on Windows, do *not* add a separator
1221 let comps = self.components();
1222 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1223 comps.prefix.unwrap().is_drive() {
1228 // absolute `path` replaces `self`
1229 if path.is_absolute() || path.prefix().is_some() {
1230 self.as_mut_vec().truncate(0);
1232 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1233 } else if path.has_root() {
1234 let prefix_len = self.components().prefix_remaining();
1235 self.as_mut_vec().truncate(prefix_len);
1237 // `path` is a pure relative path
1238 } else if need_sep {
1239 self.inner.push(MAIN_SEP_STR);
1242 self.inner.push(path);
1245 /// Truncates `self` to [`self.parent`].
1247 /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1248 /// Otherwise, returns `true`.
1250 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1251 /// [`self.parent`]: struct.PathBuf.html#method.parent
1252 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1257 /// use std::path::{Path, PathBuf};
1259 /// let mut p = PathBuf::from("/test/test.rs");
1262 /// assert_eq!(Path::new("/test"), p);
1264 /// assert_eq!(Path::new("/"), p);
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 pub fn pop(&mut self) -> bool {
1268 match self.parent().map(|p| p.as_u8_slice().len()) {
1270 self.as_mut_vec().truncate(len);
1277 /// Updates [`self.file_name`] to `file_name`.
1279 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1282 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1283 /// `file_name`. The new path will be a sibling of the original path.
1284 /// (That is, it will have the same parent.)
1286 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1287 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1288 /// [`pop`]: struct.PathBuf.html#method.pop
1293 /// use std::path::PathBuf;
1295 /// let mut buf = PathBuf::from("/");
1296 /// assert!(buf.file_name() == None);
1297 /// buf.set_file_name("bar");
1298 /// assert!(buf == PathBuf::from("/bar"));
1299 /// assert!(buf.file_name().is_some());
1300 /// buf.set_file_name("baz.txt");
1301 /// assert!(buf == PathBuf::from("/baz.txt"));
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1305 self._set_file_name(file_name.as_ref())
1308 fn _set_file_name(&mut self, file_name: &OsStr) {
1309 if self.file_name().is_some() {
1310 let popped = self.pop();
1311 debug_assert!(popped);
1313 self.push(file_name);
1316 /// Updates [`self.extension`] to `extension`.
1318 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1319 /// returns `true` and updates the extension otherwise.
1321 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1324 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1325 /// [`self.extension`]: struct.PathBuf.html#method.extension
1326 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1331 /// use std::path::{Path, PathBuf};
1333 /// let mut p = PathBuf::from("/feel/the");
1335 /// p.set_extension("force");
1336 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1338 /// p.set_extension("dark_side");
1339 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1343 self._set_extension(extension.as_ref())
1346 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1347 if self.file_name().is_none() {
1351 let mut stem = match self.file_stem() {
1352 Some(stem) => stem.to_os_string(),
1353 None => OsString::new(),
1356 if !os_str_as_u8_slice(extension).is_empty() {
1358 stem.push(extension);
1360 self.set_file_name(&stem);
1365 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1367 /// [`OsString`]: ../ffi/struct.OsString.html
1372 /// use std::path::PathBuf;
1374 /// let p = PathBuf::from("/the/head");
1375 /// let os_str = p.into_os_string();
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 pub fn into_os_string(self) -> OsString {
1382 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1384 /// [`Box`]: ../../std/boxed/struct.Box.html
1385 /// [`Path`]: struct.Path.html
1386 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1387 pub fn into_boxed_path(self) -> Box<Path> {
1388 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1389 unsafe { Box::from_raw(rw) }
1393 #[stable(feature = "box_from_path", since = "1.17.0")]
1394 impl<'a> From<&'a Path> for Box<Path> {
1395 fn from(path: &'a Path) -> Box<Path> {
1396 let boxed: Box<OsStr> = path.inner.into();
1397 let rw = Box::into_raw(boxed) as *mut Path;
1398 unsafe { Box::from_raw(rw) }
1402 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1403 impl From<Box<Path>> for PathBuf {
1404 fn from(boxed: Box<Path>) -> PathBuf {
1405 boxed.into_path_buf()
1409 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1410 impl From<PathBuf> for Box<Path> {
1411 fn from(p: PathBuf) -> Box<Path> {
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1418 fn from(s: &'a T) -> PathBuf {
1419 PathBuf::from(s.as_ref().to_os_string())
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl From<OsString> for PathBuf {
1425 fn from(s: OsString) -> PathBuf {
1426 PathBuf { inner: s }
1430 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1431 impl From<PathBuf> for OsString {
1432 fn from(path_buf : PathBuf) -> OsString {
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl From<String> for PathBuf {
1439 fn from(s: String) -> PathBuf {
1440 PathBuf::from(OsString::from(s))
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1446 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1447 let mut buf = PathBuf::new();
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1455 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1457 self.push(p.as_ref())
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 impl fmt::Debug for PathBuf {
1464 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1465 fmt::Debug::fmt(&**self, formatter)
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl ops::Deref for PathBuf {
1473 fn deref(&self) -> &Path {
1474 Path::new(&self.inner)
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl Borrow<Path> for PathBuf {
1480 fn borrow(&self) -> &Path {
1485 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1486 impl Default for PathBuf {
1487 fn default() -> Self {
1492 #[stable(feature = "cow_from_path", since = "1.6.0")]
1493 impl<'a> From<&'a Path> for Cow<'a, Path> {
1495 fn from(s: &'a Path) -> Cow<'a, Path> {
1500 #[stable(feature = "cow_from_path", since = "1.6.0")]
1501 impl<'a> From<PathBuf> for Cow<'a, Path> {
1503 fn from(s: PathBuf) -> Cow<'a, Path> {
1508 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1509 impl From<PathBuf> for Arc<Path> {
1511 fn from(s: PathBuf) -> Arc<Path> {
1512 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1513 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1517 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1518 impl<'a> From<&'a Path> for Arc<Path> {
1520 fn from(s: &Path) -> Arc<Path> {
1521 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1522 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1526 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1527 impl From<PathBuf> for Rc<Path> {
1529 fn from(s: PathBuf) -> Rc<Path> {
1530 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1531 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1535 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1536 impl<'a> From<&'a Path> for Rc<Path> {
1538 fn from(s: &Path) -> Rc<Path> {
1539 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1540 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl ToOwned for Path {
1546 type Owned = PathBuf;
1547 fn to_owned(&self) -> PathBuf {
1550 fn clone_into(&self, target: &mut PathBuf) {
1551 self.inner.clone_into(&mut target.inner);
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 impl cmp::PartialEq for PathBuf {
1557 fn eq(&self, other: &PathBuf) -> bool {
1558 self.components() == other.components()
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl Hash for PathBuf {
1564 fn hash<H: Hasher>(&self, h: &mut H) {
1565 self.as_path().hash(h)
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl cmp::Eq for PathBuf {}
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl cmp::PartialOrd for PathBuf {
1574 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1575 self.components().partial_cmp(other.components())
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl cmp::Ord for PathBuf {
1581 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1582 self.components().cmp(other.components())
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 impl AsRef<OsStr> for PathBuf {
1588 fn as_ref(&self) -> &OsStr {
1593 /// A slice of a path (akin to [`str`]).
1595 /// This type supports a number of operations for inspecting a path, including
1596 /// breaking the path into its components (separated by `/` on Unix and by either
1597 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1598 /// is absolute, and so on.
1600 /// This is an *unsized* type, meaning that it must always be used behind a
1601 /// pointer like `&` or [`Box`]. For an owned version of this type,
1602 /// see [`PathBuf`].
1604 /// [`str`]: ../primitive.str.html
1605 /// [`Box`]: ../boxed/struct.Box.html
1606 /// [`PathBuf`]: struct.PathBuf.html
1608 /// More details about the overall approach can be found in
1609 /// the [module documentation](index.html).
1614 /// use std::path::Path;
1615 /// use std::ffi::OsStr;
1617 /// // Note: this example does work on Windows
1618 /// let path = Path::new("./foo/bar.txt");
1620 /// let parent = path.parent();
1621 /// assert_eq!(parent, Some(Path::new("./foo")));
1623 /// let file_stem = path.file_stem();
1624 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1626 /// let extension = path.extension();
1627 /// assert_eq!(extension, Some(OsStr::new("txt")));
1629 #[stable(feature = "rust1", since = "1.0.0")]
1634 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1637 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1638 /// See its documentation for more.
1640 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1641 /// [`Path`]: struct.Path.html
1642 #[derive(Debug, Clone, PartialEq, Eq)]
1643 #[stable(since = "1.7.0", feature = "strip_prefix")]
1644 pub struct StripPrefixError(());
1647 // The following (private!) function allows construction of a path from a u8
1648 // slice, which is only safe when it is known to follow the OsStr encoding.
1649 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1650 Path::new(u8_slice_as_os_str(s))
1652 // The following (private!) function reveals the byte encoding used for OsStr.
1653 fn as_u8_slice(&self) -> &[u8] {
1654 os_str_as_u8_slice(&self.inner)
1657 /// Directly wraps a string slice as a `Path` slice.
1659 /// This is a cost-free conversion.
1664 /// use std::path::Path;
1666 /// Path::new("foo.txt");
1669 /// You can create `Path`s from `String`s, or even other `Path`s:
1672 /// use std::path::Path;
1674 /// let string = String::from("foo.txt");
1675 /// let from_string = Path::new(&string);
1676 /// let from_path = Path::new(&from_string);
1677 /// assert_eq!(from_string, from_path);
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1681 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1684 /// Yields the underlying [`OsStr`] slice.
1686 /// [`OsStr`]: ../ffi/struct.OsStr.html
1691 /// use std::path::Path;
1693 /// let os_str = Path::new("foo.txt").as_os_str();
1694 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 pub fn as_os_str(&self) -> &OsStr {
1701 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1703 /// This conversion may entail doing a check for UTF-8 validity.
1705 /// [`&str`]: ../primitive.str.html
1710 /// use std::path::Path;
1712 /// let path = Path::new("foo.txt");
1713 /// assert_eq!(path.to_str(), Some("foo.txt"));
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 pub fn to_str(&self) -> Option<&str> {
1720 /// Converts a `Path` to a [`Cow<str>`].
1722 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1724 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1728 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1731 /// use std::path::Path;
1733 /// let path = Path::new("foo.txt");
1734 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1737 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1738 /// have returned `"fo�.txt"`.
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 pub fn to_string_lossy(&self) -> Cow<str> {
1741 self.inner.to_string_lossy()
1744 /// Converts a `Path` to an owned [`PathBuf`].
1746 /// [`PathBuf`]: struct.PathBuf.html
1751 /// use std::path::Path;
1753 /// let path_buf = Path::new("foo.txt").to_path_buf();
1754 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1756 #[rustc_conversion_suggestion]
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 pub fn to_path_buf(&self) -> PathBuf {
1759 PathBuf::from(self.inner.to_os_string())
1762 /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
1763 /// the current directory.
1765 /// * On Unix, a path is absolute if it starts with the root, so
1766 /// `is_absolute` and [`has_root`] are equivalent.
1768 /// * On Windows, a path is absolute if it has a prefix and starts with the
1769 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1774 /// use std::path::Path;
1776 /// assert!(!Path::new("foo.txt").is_absolute());
1779 /// [`has_root`]: #method.has_root
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 #[allow(deprecated)]
1782 pub fn is_absolute(&self) -> bool {
1783 if cfg!(target_os = "redox") {
1784 // FIXME: Allow Redox prefixes
1785 self.has_root() || has_redox_scheme(self.as_u8_slice())
1787 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1791 /// Returns `true` if the `Path` is relative, i.e. not absolute.
1793 /// See [`is_absolute`]'s documentation for more details.
1798 /// use std::path::Path;
1800 /// assert!(Path::new("foo.txt").is_relative());
1803 /// [`is_absolute`]: #method.is_absolute
1804 #[stable(feature = "rust1", since = "1.0.0")]
1805 pub fn is_relative(&self) -> bool {
1809 fn prefix(&self) -> Option<Prefix> {
1810 self.components().prefix
1813 /// Returns `true` if the `Path` has a root.
1815 /// * On Unix, a path has a root if it begins with `/`.
1817 /// * On Windows, a path has a root if it:
1818 /// * has no prefix and begins with a separator, e.g. `\\windows`
1819 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1820 /// * has any non-disk prefix, e.g. `\\server\share`
1825 /// use std::path::Path;
1827 /// assert!(Path::new("/etc/passwd").has_root());
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 pub fn has_root(&self) -> bool {
1831 self.components().has_root()
1834 /// Returns the `Path` without its final component, if there is one.
1836 /// Returns [`None`] if the path terminates in a root or prefix.
1838 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1843 /// use std::path::Path;
1845 /// let path = Path::new("/foo/bar");
1846 /// let parent = path.parent().unwrap();
1847 /// assert_eq!(parent, Path::new("/foo"));
1849 /// let grand_parent = parent.parent().unwrap();
1850 /// assert_eq!(grand_parent, Path::new("/"));
1851 /// assert_eq!(grand_parent.parent(), None);
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 pub fn parent(&self) -> Option<&Path> {
1855 let mut comps = self.components();
1856 let comp = comps.next_back();
1859 Component::Normal(_) |
1861 Component::ParentDir => Some(comps.as_path()),
1867 /// Produces an iterator over `Path` and its ancestors.
1869 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1870 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1871 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1872 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1878 /// #![feature(path_ancestors)]
1880 /// use std::path::Path;
1882 /// let mut ancestors = Path::new("/foo/bar").ancestors();
1883 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1884 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1885 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1886 /// assert_eq!(ancestors.next(), None);
1889 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1890 /// [`parent`]: struct.Path.html#method.parent
1891 #[unstable(feature = "path_ancestors", issue = "48581")]
1892 pub fn ancestors(&self) -> Ancestors {
1898 /// Returns the final component of the `Path`, if there is one.
1900 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1901 /// is the directory name.
1903 /// Returns [`None`] if the path terminates in `..`.
1905 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1910 /// use std::path::Path;
1911 /// use std::ffi::OsStr;
1913 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1914 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1915 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1916 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1917 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1918 /// assert_eq!(None, Path::new("/").file_name());
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 pub fn file_name(&self) -> Option<&OsStr> {
1922 self.components().next_back().and_then(|p| {
1924 Component::Normal(p) => Some(p.as_ref()),
1930 /// Returns a path that, when joined onto `base`, yields `self`.
1934 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1935 /// returns `false`), returns [`Err`].
1937 /// [`starts_with`]: #method.starts_with
1938 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1943 /// use std::path::Path;
1945 /// let path = Path::new("/test/haha/foo.txt");
1947 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
1948 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1949 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
1950 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
1951 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
1952 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1953 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1955 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1956 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1957 -> Result<&'a Path, StripPrefixError>
1958 where P: AsRef<Path>
1960 self._strip_prefix(base.as_ref())
1963 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1964 -> Result<&'a Path, StripPrefixError> {
1965 iter_after(self.components(), base.components())
1966 .map(|c| c.as_path())
1967 .ok_or(StripPrefixError(()))
1970 /// Determines whether `base` is a prefix of `self`.
1972 /// Only considers whole path components to match.
1977 /// use std::path::Path;
1979 /// let path = Path::new("/etc/passwd");
1981 /// assert!(path.starts_with("/etc"));
1982 /// assert!(path.starts_with("/etc/"));
1983 /// assert!(path.starts_with("/etc/passwd"));
1984 /// assert!(path.starts_with("/etc/passwd/"));
1986 /// assert!(!path.starts_with("/e"));
1988 #[stable(feature = "rust1", since = "1.0.0")]
1989 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1990 self._starts_with(base.as_ref())
1993 fn _starts_with(&self, base: &Path) -> bool {
1994 iter_after(self.components(), base.components()).is_some()
1997 /// Determines whether `child` is a suffix of `self`.
1999 /// Only considers whole path components to match.
2004 /// use std::path::Path;
2006 /// let path = Path::new("/etc/passwd");
2008 /// assert!(path.ends_with("passwd"));
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2012 self._ends_with(child.as_ref())
2015 fn _ends_with(&self, child: &Path) -> bool {
2016 iter_after(self.components().rev(), child.components().rev()).is_some()
2019 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2021 /// [`self.file_name`]: struct.Path.html#method.file_name
2025 /// * [`None`], if there is no file name;
2026 /// * The entire file name if there is no embedded `.`;
2027 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2028 /// * Otherwise, the portion of the file name before the final `.`
2030 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2035 /// use std::path::Path;
2037 /// let path = Path::new("foo.rs");
2039 /// assert_eq!("foo", path.file_stem().unwrap());
2041 #[stable(feature = "rust1", since = "1.0.0")]
2042 pub fn file_stem(&self) -> Option<&OsStr> {
2043 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2046 /// Extracts the extension of [`self.file_name`], if possible.
2048 /// The extension is:
2050 /// * [`None`], if there is no file name;
2051 /// * [`None`], if there is no embedded `.`;
2052 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2053 /// * Otherwise, the portion of the file name after the final `.`
2055 /// [`self.file_name`]: struct.Path.html#method.file_name
2056 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2061 /// use std::path::Path;
2063 /// let path = Path::new("foo.rs");
2065 /// assert_eq!("rs", path.extension().unwrap());
2067 #[stable(feature = "rust1", since = "1.0.0")]
2068 pub fn extension(&self) -> Option<&OsStr> {
2069 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2072 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2074 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2076 /// [`PathBuf`]: struct.PathBuf.html
2077 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2082 /// use std::path::{Path, PathBuf};
2084 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2088 self._join(path.as_ref())
2091 fn _join(&self, path: &Path) -> PathBuf {
2092 let mut buf = self.to_path_buf();
2097 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2099 /// See [`PathBuf::set_file_name`] for more details.
2101 /// [`PathBuf`]: struct.PathBuf.html
2102 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2107 /// use std::path::{Path, PathBuf};
2109 /// let path = Path::new("/tmp/foo.txt");
2110 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2112 /// let path = Path::new("/tmp");
2113 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2117 self._with_file_name(file_name.as_ref())
2120 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2121 let mut buf = self.to_path_buf();
2122 buf.set_file_name(file_name);
2126 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2128 /// See [`PathBuf::set_extension`] for more details.
2130 /// [`PathBuf`]: struct.PathBuf.html
2131 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2136 /// use std::path::{Path, PathBuf};
2138 /// let path = Path::new("foo.rs");
2139 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2143 self._with_extension(extension.as_ref())
2146 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2147 let mut buf = self.to_path_buf();
2148 buf.set_extension(extension);
2152 /// Produces an iterator over the [`Component`]s of the path.
2154 /// When parsing the path, there is a small amount of normalization:
2156 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2157 /// `a` and `b` as components.
2159 /// * Occurrences of `.` are normalized away, except if they are at the
2160 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2161 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2162 /// an additional [`CurDir`] component.
2164 /// Note that no other normalization takes place; in particular, `a/c`
2165 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2166 /// is a symbolic link (so its parent isn't `a`).
2171 /// use std::path::{Path, Component};
2172 /// use std::ffi::OsStr;
2174 /// let mut components = Path::new("/tmp/foo.txt").components();
2176 /// assert_eq!(components.next(), Some(Component::RootDir));
2177 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2178 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2179 /// assert_eq!(components.next(), None)
2182 /// [`Component`]: enum.Component.html
2183 /// [`CurDir`]: enum.Component.html#variant.CurDir
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 pub fn components(&self) -> Components {
2186 let prefix = parse_prefix(self.as_os_str());
2188 path: self.as_u8_slice(),
2190 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2191 has_redox_scheme(self.as_u8_slice()),
2192 front: State::Prefix,
2197 /// Produces an iterator over the path's components viewed as [`OsStr`]
2200 /// For more information about the particulars of how the path is separated
2201 /// into components, see [`components`].
2203 /// [`components`]: #method.components
2204 /// [`OsStr`]: ../ffi/struct.OsStr.html
2209 /// use std::path::{self, Path};
2210 /// use std::ffi::OsStr;
2212 /// let mut it = Path::new("/tmp/foo.txt").iter();
2213 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2214 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2215 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2216 /// assert_eq!(it.next(), None)
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 pub fn iter(&self) -> Iter {
2220 Iter { inner: self.components() }
2223 /// Returns an object that implements [`Display`] for safely printing paths
2224 /// that may contain non-Unicode data.
2226 /// [`Display`]: ../fmt/trait.Display.html
2231 /// use std::path::Path;
2233 /// let path = Path::new("/tmp/foo.rs");
2235 /// println!("{}", path.display());
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 pub fn display(&self) -> Display {
2239 Display { path: self }
2242 /// Queries the file system to get information about a file, directory, etc.
2244 /// This function will traverse symbolic links to query information about the
2245 /// destination file.
2247 /// This is an alias to [`fs::metadata`].
2249 /// [`fs::metadata`]: ../fs/fn.metadata.html
2254 /// use std::path::Path;
2256 /// let path = Path::new("/Minas/tirith");
2257 /// let metadata = path.metadata().expect("metadata call failed");
2258 /// println!("{:?}", metadata.file_type());
2260 #[stable(feature = "path_ext", since = "1.5.0")]
2261 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2265 /// Queries the metadata about a file without following symlinks.
2267 /// This is an alias to [`fs::symlink_metadata`].
2269 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2274 /// use std::path::Path;
2276 /// let path = Path::new("/Minas/tirith");
2277 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2278 /// println!("{:?}", metadata.file_type());
2280 #[stable(feature = "path_ext", since = "1.5.0")]
2281 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2282 fs::symlink_metadata(self)
2285 /// Returns the canonical form of the path with all intermediate components
2286 /// normalized and symbolic links resolved.
2288 /// This is an alias to [`fs::canonicalize`].
2290 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2295 /// use std::path::{Path, PathBuf};
2297 /// let path = Path::new("/foo/test/../test/bar.rs");
2298 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2300 #[stable(feature = "path_ext", since = "1.5.0")]
2301 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2302 fs::canonicalize(self)
2305 /// Reads a symbolic link, returning the file that the link points to.
2307 /// This is an alias to [`fs::read_link`].
2309 /// [`fs::read_link`]: ../fs/fn.read_link.html
2314 /// use std::path::Path;
2316 /// let path = Path::new("/laputa/sky_castle.rs");
2317 /// let path_link = path.read_link().expect("read_link call failed");
2319 #[stable(feature = "path_ext", since = "1.5.0")]
2320 pub fn read_link(&self) -> io::Result<PathBuf> {
2324 /// Returns an iterator over the entries within a directory.
2326 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2327 /// errors may be encountered after an iterator is initially constructed.
2329 /// This is an alias to [`fs::read_dir`].
2331 /// [`io::Result`]: ../io/type.Result.html
2332 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2333 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2338 /// use std::path::Path;
2340 /// let path = Path::new("/laputa");
2341 /// for entry in path.read_dir().expect("read_dir call failed") {
2342 /// if let Ok(entry) = entry {
2343 /// println!("{:?}", entry.path());
2347 #[stable(feature = "path_ext", since = "1.5.0")]
2348 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2352 /// Returns whether the path points at an existing entity.
2354 /// This function will traverse symbolic links to query information about the
2355 /// destination file. In case of broken symbolic links this will return `false`.
2357 /// If you cannot access the directory containing the file, e.g. because of a
2358 /// permission error, this will return `false`.
2363 /// use std::path::Path;
2364 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2369 /// This is a convenience function that coerces errors to false. If you want to
2370 /// check errors, call [fs::metadata].
2372 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2373 #[stable(feature = "path_ext", since = "1.5.0")]
2374 pub fn exists(&self) -> bool {
2375 fs::metadata(self).is_ok()
2378 /// Returns whether the path exists on disk and is pointing at a regular file.
2380 /// This function will traverse symbolic links to query information about the
2381 /// destination file. In case of broken symbolic links this will return `false`.
2383 /// If you cannot access the directory containing the file, e.g. because of a
2384 /// permission error, this will return `false`.
2389 /// use std::path::Path;
2390 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2391 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2396 /// This is a convenience function that coerces errors to false. If you want to
2397 /// check errors, call [fs::metadata] and handle its Result. Then call
2398 /// [fs::Metadata::is_file] if it was Ok.
2400 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2401 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2402 #[stable(feature = "path_ext", since = "1.5.0")]
2403 pub fn is_file(&self) -> bool {
2404 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2407 /// Returns whether the path exists on disk and is pointing at a directory.
2409 /// This function will traverse symbolic links to query information about the
2410 /// destination file. In case of broken symbolic links this will return `false`.
2412 /// If you cannot access the directory containing the file, e.g. because of a
2413 /// permission error, this will return `false`.
2418 /// use std::path::Path;
2419 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2420 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2425 /// This is a convenience function that coerces errors to false. If you want to
2426 /// check errors, call [fs::metadata] and handle its Result. Then call
2427 /// [fs::Metadata::is_dir] if it was Ok.
2429 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2430 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2431 #[stable(feature = "path_ext", since = "1.5.0")]
2432 pub fn is_dir(&self) -> bool {
2433 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2436 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2439 /// [`Box`]: ../../std/boxed/struct.Box.html
2440 /// [`PathBuf`]: struct.PathBuf.html
2441 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2442 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2443 let rw = Box::into_raw(self) as *mut OsStr;
2444 let inner = unsafe { Box::from_raw(rw) };
2445 PathBuf { inner: OsString::from(inner) }
2449 #[stable(feature = "rust1", since = "1.0.0")]
2450 impl AsRef<OsStr> for Path {
2451 fn as_ref(&self) -> &OsStr {
2456 #[stable(feature = "rust1", since = "1.0.0")]
2457 impl fmt::Debug for Path {
2458 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2459 fmt::Debug::fmt(&self.inner, formatter)
2463 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2465 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2466 /// [`Display`] trait in a way that mitigates that. It is created by the
2467 /// [`display`][`Path::display`] method on [`Path`].
2472 /// use std::path::Path;
2474 /// let path = Path::new("/tmp/foo.rs");
2476 /// println!("{}", path.display());
2479 /// [`Display`]: ../../std/fmt/trait.Display.html
2480 /// [`format!`]: ../../std/macro.format.html
2481 /// [`Path`]: struct.Path.html
2482 /// [`Path::display`]: struct.Path.html#method.display
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 pub struct Display<'a> {
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 impl<'a> fmt::Debug for Display<'a> {
2490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2491 fmt::Debug::fmt(&self.path, f)
2495 #[stable(feature = "rust1", since = "1.0.0")]
2496 impl<'a> fmt::Display for Display<'a> {
2497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2498 self.path.inner.display(f)
2502 #[stable(feature = "rust1", since = "1.0.0")]
2503 impl cmp::PartialEq for Path {
2504 fn eq(&self, other: &Path) -> bool {
2505 self.components().eq(other.components())
2509 #[stable(feature = "rust1", since = "1.0.0")]
2510 impl Hash for Path {
2511 fn hash<H: Hasher>(&self, h: &mut H) {
2512 for component in self.components() {
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 impl cmp::Eq for Path {}
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl cmp::PartialOrd for Path {
2523 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2524 self.components().partial_cmp(other.components())
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 impl cmp::Ord for Path {
2530 fn cmp(&self, other: &Path) -> cmp::Ordering {
2531 self.components().cmp(other.components())
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 impl AsRef<Path> for Path {
2537 fn as_ref(&self) -> &Path {
2542 #[stable(feature = "rust1", since = "1.0.0")]
2543 impl AsRef<Path> for OsStr {
2544 fn as_ref(&self) -> &Path {
2549 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2550 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2551 fn as_ref(&self) -> &Path {
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 impl AsRef<Path> for OsString {
2558 fn as_ref(&self) -> &Path {
2563 #[stable(feature = "rust1", since = "1.0.0")]
2564 impl AsRef<Path> for str {
2565 fn as_ref(&self) -> &Path {
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 impl AsRef<Path> for String {
2572 fn as_ref(&self) -> &Path {
2577 #[stable(feature = "rust1", since = "1.0.0")]
2578 impl AsRef<Path> for PathBuf {
2579 fn as_ref(&self) -> &Path {
2584 #[stable(feature = "path_into_iter", since = "1.6.0")]
2585 impl<'a> IntoIterator for &'a PathBuf {
2586 type Item = &'a OsStr;
2587 type IntoIter = Iter<'a>;
2588 fn into_iter(self) -> Iter<'a> { self.iter() }
2591 #[stable(feature = "path_into_iter", since = "1.6.0")]
2592 impl<'a> IntoIterator for &'a Path {
2593 type Item = &'a OsStr;
2594 type IntoIter = Iter<'a>;
2595 fn into_iter(self) -> Iter<'a> { self.iter() }
2598 macro_rules! impl_cmp {
2599 ($lhs:ty, $rhs: ty) => {
2600 #[stable(feature = "partialeq_path", since = "1.6.0")]
2601 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2603 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2606 #[stable(feature = "partialeq_path", since = "1.6.0")]
2607 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2609 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2612 #[stable(feature = "cmp_path", since = "1.8.0")]
2613 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2615 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2616 <Path as PartialOrd>::partial_cmp(self, other)
2620 #[stable(feature = "cmp_path", since = "1.8.0")]
2621 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2623 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2624 <Path as PartialOrd>::partial_cmp(self, other)
2630 impl_cmp!(PathBuf, Path);
2631 impl_cmp!(PathBuf, &'a Path);
2632 impl_cmp!(Cow<'a, Path>, Path);
2633 impl_cmp!(Cow<'a, Path>, &'b Path);
2634 impl_cmp!(Cow<'a, Path>, PathBuf);
2636 macro_rules! impl_cmp_os_str {
2637 ($lhs:ty, $rhs: ty) => {
2638 #[stable(feature = "cmp_path", since = "1.8.0")]
2639 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2641 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2644 #[stable(feature = "cmp_path", since = "1.8.0")]
2645 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2647 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2650 #[stable(feature = "cmp_path", since = "1.8.0")]
2651 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2653 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2654 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2658 #[stable(feature = "cmp_path", since = "1.8.0")]
2659 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2661 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2662 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2668 impl_cmp_os_str!(PathBuf, OsStr);
2669 impl_cmp_os_str!(PathBuf, &'a OsStr);
2670 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2671 impl_cmp_os_str!(PathBuf, OsString);
2672 impl_cmp_os_str!(Path, OsStr);
2673 impl_cmp_os_str!(Path, &'a OsStr);
2674 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2675 impl_cmp_os_str!(Path, OsString);
2676 impl_cmp_os_str!(&'a Path, OsStr);
2677 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2678 impl_cmp_os_str!(&'a Path, OsString);
2679 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2680 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2681 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2683 #[stable(since = "1.7.0", feature = "strip_prefix")]
2684 impl fmt::Display for StripPrefixError {
2685 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2686 self.description().fmt(f)
2690 #[stable(since = "1.7.0", feature = "strip_prefix")]
2691 impl Error for StripPrefixError {
2692 fn description(&self) -> &str { "prefix not found" }
2703 ($path:expr, iter: $iter:expr) => (
2705 let path = Path::new($path);
2707 // Forward iteration
2708 let comps = path.iter()
2709 .map(|p| p.to_string_lossy().into_owned())
2710 .collect::<Vec<String>>();
2711 let exp: &[&str] = &$iter;
2712 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2713 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2716 // Reverse iteration
2717 let comps = Path::new($path).iter().rev()
2718 .map(|p| p.to_string_lossy().into_owned())
2719 .collect::<Vec<String>>();
2720 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2721 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2726 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2728 let path = Path::new($path);
2730 let act_root = path.has_root();
2731 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2732 $has_root, act_root);
2734 let act_abs = path.is_absolute();
2735 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2736 $is_absolute, act_abs);
2740 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2742 let path = Path::new($path);
2744 let parent = path.parent().map(|p| p.to_str().unwrap());
2745 let exp_parent: Option<&str> = $parent;
2746 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2747 exp_parent, parent);
2749 let file = path.file_name().map(|p| p.to_str().unwrap());
2750 let exp_file: Option<&str> = $file;
2751 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2756 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2758 let path = Path::new($path);
2760 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2761 let exp_stem: Option<&str> = $file_stem;
2762 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2765 let ext = path.extension().map(|p| p.to_str().unwrap());
2766 let exp_ext: Option<&str> = $extension;
2767 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2772 ($path:expr, iter: $iter:expr,
2773 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2774 parent: $parent:expr, file_name: $file:expr,
2775 file_stem: $file_stem:expr, extension: $extension:expr) => (
2777 t!($path, iter: $iter);
2778 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2779 t!($path, parent: $parent, file_name: $file);
2780 t!($path, file_stem: $file_stem, extension: $extension);
2789 let static_path = Path::new("/home/foo");
2790 let static_cow_path: Cow<'static, Path> = static_path.into();
2791 let pathbuf = PathBuf::from("/home/foo");
2794 let path: &Path = &pathbuf;
2795 let borrowed_cow_path: Cow<Path> = path.into();
2797 assert_eq!(static_cow_path, borrowed_cow_path);
2800 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2802 assert_eq!(static_cow_path, owned_cow_path);
2807 pub fn test_decompositions_unix() {
2823 file_name: Some("foo"),
2824 file_stem: Some("foo"),
2843 file_name: Some("foo"),
2844 file_stem: Some("foo"),
2853 file_name: Some("foo"),
2854 file_stem: Some("foo"),
2863 file_name: Some("foo"),
2864 file_stem: Some("foo"),
2869 iter: ["foo", "bar"],
2872 parent: Some("foo"),
2873 file_name: Some("bar"),
2874 file_stem: Some("bar"),
2879 iter: ["/", "foo", "bar"],
2882 parent: Some("/foo"),
2883 file_name: Some("bar"),
2884 file_stem: Some("bar"),
2893 file_name: Some("foo"),
2894 file_stem: Some("foo"),
2899 iter: ["/", "foo", "bar"],
2902 parent: Some("///foo"),
2903 file_name: Some("bar"),
2904 file_stem: Some("bar"),
2943 file_name: Some("foo"),
2944 file_stem: Some("foo"),
2949 iter: ["foo", ".."],
2952 parent: Some("foo"),
2963 file_name: Some("foo"),
2964 file_stem: Some("foo"),
2969 iter: ["foo", "bar"],
2972 parent: Some("foo"),
2973 file_name: Some("bar"),
2974 file_stem: Some("bar"),
2979 iter: ["foo", ".."],
2982 parent: Some("foo"),
2989 iter: ["foo", "..", "bar"],
2992 parent: Some("foo/.."),
2993 file_name: Some("bar"),
2994 file_stem: Some("bar"),
3003 file_name: Some("a"),
3004 file_stem: Some("a"),
3033 file_name: Some("b"),
3034 file_stem: Some("b"),
3043 file_name: Some("b"),
3044 file_stem: Some("b"),
3053 file_name: Some("b"),
3054 file_stem: Some("b"),
3059 iter: ["a", "b", "c"],
3062 parent: Some("a/b"),
3063 file_name: Some("c"),
3064 file_stem: Some("c"),
3073 file_name: Some(".foo"),
3074 file_stem: Some(".foo"),
3081 pub fn test_decompositions_windows() {
3097 file_name: Some("foo"),
3098 file_stem: Some("foo"),
3153 iter: ["\\", "foo"],
3157 file_name: Some("foo"),
3158 file_stem: Some("foo"),
3167 file_name: Some("foo"),
3168 file_stem: Some("foo"),
3173 iter: ["\\", "foo"],
3177 file_name: Some("foo"),
3178 file_stem: Some("foo"),
3183 iter: ["foo", "bar"],
3186 parent: Some("foo"),
3187 file_name: Some("bar"),
3188 file_stem: Some("bar"),
3193 iter: ["\\", "foo", "bar"],
3196 parent: Some("/foo"),
3197 file_name: Some("bar"),
3198 file_stem: Some("bar"),
3203 iter: ["\\", "foo"],
3207 file_name: Some("foo"),
3208 file_stem: Some("foo"),
3213 iter: ["\\", "foo", "bar"],
3216 parent: Some("///foo"),
3217 file_name: Some("bar"),
3218 file_stem: Some("bar"),
3257 file_name: Some("foo"),
3258 file_stem: Some("foo"),
3263 iter: ["foo", ".."],
3266 parent: Some("foo"),
3277 file_name: Some("foo"),
3278 file_stem: Some("foo"),
3283 iter: ["foo", "bar"],
3286 parent: Some("foo"),
3287 file_name: Some("bar"),
3288 file_stem: Some("bar"),
3293 iter: ["foo", ".."],
3296 parent: Some("foo"),
3303 iter: ["foo", "..", "bar"],
3306 parent: Some("foo/.."),
3307 file_name: Some("bar"),
3308 file_stem: Some("bar"),
3317 file_name: Some("a"),
3318 file_stem: Some("a"),
3347 file_name: Some("b"),
3348 file_stem: Some("b"),
3357 file_name: Some("b"),
3358 file_stem: Some("b"),
3367 file_name: Some("b"),
3368 file_stem: Some("b"),
3373 iter: ["a", "b", "c"],
3376 parent: Some("a/b"),
3377 file_name: Some("c"),
3378 file_stem: Some("c"),
3382 iter: ["a", "b", "c"],
3385 parent: Some("a\\b"),
3386 file_name: Some("c"),
3387 file_stem: Some("c"),
3396 file_name: Some("a"),
3397 file_stem: Some("a"),
3402 iter: ["c:", "\\", "foo.txt"],
3405 parent: Some("c:\\"),
3406 file_name: Some("foo.txt"),
3407 file_stem: Some("foo"),
3408 extension: Some("txt")
3411 t!("\\\\server\\share\\foo.txt",
3412 iter: ["\\\\server\\share", "\\", "foo.txt"],
3415 parent: Some("\\\\server\\share\\"),
3416 file_name: Some("foo.txt"),
3417 file_stem: Some("foo"),
3418 extension: Some("txt")
3421 t!("\\\\server\\share",
3422 iter: ["\\\\server\\share", "\\"],
3432 iter: ["\\", "server"],
3436 file_name: Some("server"),
3437 file_stem: Some("server"),
3441 t!("\\\\?\\bar\\foo.txt",
3442 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3445 parent: Some("\\\\?\\bar\\"),
3446 file_name: Some("foo.txt"),
3447 file_stem: Some("foo"),
3448 extension: Some("txt")
3452 iter: ["\\\\?\\bar"],
3471 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3472 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3475 parent: Some("\\\\?\\UNC\\server\\share\\"),
3476 file_name: Some("foo.txt"),
3477 file_stem: Some("foo"),
3478 extension: Some("txt")
3481 t!("\\\\?\\UNC\\server",
3482 iter: ["\\\\?\\UNC\\server"],
3492 iter: ["\\\\?\\UNC\\"],
3501 t!("\\\\?\\C:\\foo.txt",
3502 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3505 parent: Some("\\\\?\\C:\\"),
3506 file_name: Some("foo.txt"),
3507 file_stem: Some("foo"),
3508 extension: Some("txt")
3513 iter: ["\\\\?\\C:", "\\"],
3524 iter: ["\\\\?\\C:"],
3534 t!("\\\\?\\foo/bar",
3535 iter: ["\\\\?\\foo/bar"],
3546 iter: ["\\\\?\\C:/foo"],
3556 t!("\\\\.\\foo\\bar",
3557 iter: ["\\\\.\\foo", "\\", "bar"],
3560 parent: Some("\\\\.\\foo\\"),
3561 file_name: Some("bar"),
3562 file_stem: Some("bar"),
3568 iter: ["\\\\.\\foo", "\\"],
3578 t!("\\\\.\\foo/bar",
3579 iter: ["\\\\.\\foo/bar", "\\"],
3589 t!("\\\\.\\foo\\bar/baz",
3590 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3593 parent: Some("\\\\.\\foo\\bar"),
3594 file_name: Some("baz"),
3595 file_stem: Some("baz"),
3601 iter: ["\\\\.\\", "\\"],
3611 iter: ["\\\\?\\a", "\\", "b"],
3614 parent: Some("\\\\?\\a\\"),
3615 file_name: Some("b"),
3616 file_stem: Some("b"),
3622 pub fn test_stem_ext() {
3624 file_stem: Some("foo"),
3629 file_stem: Some("foo"),
3634 file_stem: Some(".foo"),
3639 file_stem: Some("foo"),
3640 extension: Some("txt")
3644 file_stem: Some("foo.bar"),
3645 extension: Some("txt")
3649 file_stem: Some("foo.bar"),
3670 pub fn test_push() {
3672 ($path:expr, $push:expr, $expected:expr) => ( {
3673 let mut actual = PathBuf::from($path);
3675 assert!(actual.to_str() == Some($expected),
3676 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3677 $push, $path, $expected, actual.to_str().unwrap());
3682 tp!("", "foo", "foo");
3683 tp!("foo", "bar", "foo/bar");
3684 tp!("foo/", "bar", "foo/bar");
3685 tp!("foo//", "bar", "foo//bar");
3686 tp!("foo/.", "bar", "foo/./bar");
3687 tp!("foo./.", "bar", "foo././bar");
3688 tp!("foo", "", "foo/");
3689 tp!("foo", ".", "foo/.");
3690 tp!("foo", "..", "foo/..");
3691 tp!("foo", "/", "/");
3692 tp!("/foo/bar", "/", "/");
3693 tp!("/foo/bar", "/baz", "/baz");
3694 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3696 tp!("", "foo", "foo");
3697 tp!("foo", "bar", r"foo\bar");
3698 tp!("foo/", "bar", r"foo/bar");
3699 tp!(r"foo\", "bar", r"foo\bar");
3700 tp!("foo//", "bar", r"foo//bar");
3701 tp!(r"foo\\", "bar", r"foo\\bar");
3702 tp!("foo/.", "bar", r"foo/.\bar");
3703 tp!("foo./.", "bar", r"foo./.\bar");
3704 tp!(r"foo\.", "bar", r"foo\.\bar");
3705 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3706 tp!("foo", "", "foo\\");
3707 tp!("foo", ".", r"foo\.");
3708 tp!("foo", "..", r"foo\..");
3709 tp!("foo", "/", "/");
3710 tp!("foo", r"\", r"\");
3711 tp!("/foo/bar", "/", "/");
3712 tp!(r"\foo\bar", r"\", r"\");
3713 tp!("/foo/bar", "/baz", "/baz");
3714 tp!("/foo/bar", r"\baz", r"\baz");
3715 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3716 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3718 tp!("c:\\", "windows", "c:\\windows");
3719 tp!("c:", "windows", "c:windows");
3721 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3722 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3723 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3724 tp!("a\\b", "\\c\\d", "\\c\\d");
3725 tp!("a\\b", ".", "a\\b\\.");
3726 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3727 tp!("a\\b", "C:a.txt", "C:a.txt");
3728 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3729 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3730 tp!("C:\\a\\b\\c", "C:d", "C:d");
3731 tp!("C:a\\b\\c", "C:d", "C:d");
3732 tp!("C:", r"a\b\c", r"C:a\b\c");
3733 tp!("C:", r"..\a", r"C:..\a");
3734 tp!("\\\\server\\share\\foo",
3736 "\\\\server\\share\\foo\\bar");
3737 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3738 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3739 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3740 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3741 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3742 tp!("\\\\?\\UNC\\server\\share\\foo",
3744 "\\\\?\\UNC\\server\\share\\foo\\bar");
3745 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3746 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3748 // Note: modified from old path API
3749 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3752 "\\\\?\\UNC\\server\\share",
3753 "\\\\?\\UNC\\server\\share");
3754 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3755 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3756 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3757 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3759 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3766 ($path:expr, $expected:expr, $output:expr) => ( {
3767 let mut actual = PathBuf::from($path);
3768 let output = actual.pop();
3769 assert!(actual.to_str() == Some($expected) && output == $output,
3770 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3771 $path, $expected, $output,
3772 actual.to_str().unwrap(), output);
3777 tp!("/", "/", false);
3778 tp!("foo", "", true);
3780 tp!("/foo", "/", true);
3781 tp!("/foo/bar", "/foo", true);
3782 tp!("foo/bar", "foo", true);
3783 tp!("foo/.", "", true);
3784 tp!("foo//bar", "foo", true);
3787 tp!("a\\b\\c", "a\\b", true);
3788 tp!("\\a", "\\", true);
3789 tp!("\\", "\\", false);
3791 tp!("C:\\a\\b", "C:\\a", true);
3792 tp!("C:\\a", "C:\\", true);
3793 tp!("C:\\", "C:\\", false);
3794 tp!("C:a\\b", "C:a", true);
3795 tp!("C:a", "C:", true);
3796 tp!("C:", "C:", false);
3797 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3798 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3799 tp!("\\\\server\\share", "\\\\server\\share", false);
3800 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3801 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3802 tp!("\\\\?\\a", "\\\\?\\a", false);
3803 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3804 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3805 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3806 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3807 "\\\\?\\UNC\\server\\share\\a",
3809 tp!("\\\\?\\UNC\\server\\share\\a",
3810 "\\\\?\\UNC\\server\\share\\",
3812 tp!("\\\\?\\UNC\\server\\share",
3813 "\\\\?\\UNC\\server\\share",
3815 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3816 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3817 tp!("\\\\.\\a", "\\\\.\\a", false);
3819 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3824 pub fn test_set_file_name() {
3826 ($path:expr, $file:expr, $expected:expr) => ( {
3827 let mut p = PathBuf::from($path);
3828 p.set_file_name($file);
3829 assert!(p.to_str() == Some($expected),
3830 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3831 $path, $file, $expected,
3832 p.to_str().unwrap());
3836 tfn!("foo", "foo", "foo");
3837 tfn!("foo", "bar", "bar");
3838 tfn!("foo", "", "");
3839 tfn!("", "foo", "foo");
3841 tfn!(".", "foo", "./foo");
3842 tfn!("foo/", "bar", "bar");
3843 tfn!("foo/.", "bar", "bar");
3844 tfn!("..", "foo", "../foo");
3845 tfn!("foo/..", "bar", "foo/../bar");
3846 tfn!("/", "foo", "/foo");
3848 tfn!(".", "foo", r".\foo");
3849 tfn!(r"foo\", "bar", r"bar");
3850 tfn!(r"foo\.", "bar", r"bar");
3851 tfn!("..", "foo", r"..\foo");
3852 tfn!(r"foo\..", "bar", r"foo\..\bar");
3853 tfn!(r"\", "foo", r"\foo");
3858 pub fn test_set_extension() {
3860 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3861 let mut p = PathBuf::from($path);
3862 let output = p.set_extension($ext);
3863 assert!(p.to_str() == Some($expected) && output == $output,
3864 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3865 $path, $ext, $expected, $output,
3866 p.to_str().unwrap(), output);
3870 tfe!("foo", "txt", "foo.txt", true);
3871 tfe!("foo.bar", "txt", "foo.txt", true);
3872 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3873 tfe!(".test", "txt", ".test.txt", true);
3874 tfe!("foo.txt", "", "foo", true);
3875 tfe!("foo", "", "foo", true);
3876 tfe!("", "foo", "", false);
3877 tfe!(".", "foo", ".", false);
3878 tfe!("foo/", "bar", "foo.bar", true);
3879 tfe!("foo/.", "bar", "foo.bar", true);
3880 tfe!("..", "foo", "..", false);
3881 tfe!("foo/..", "bar", "foo/..", false);
3882 tfe!("/", "foo", "/", false);
3886 fn test_eq_receivers() {
3889 let borrowed: &Path = Path::new("foo/bar");
3890 let mut owned: PathBuf = PathBuf::new();
3893 let borrowed_cow: Cow<Path> = borrowed.into();
3894 let owned_cow: Cow<Path> = owned.clone().into();
3897 ($($current:expr),+) => {
3899 assert_eq!($current, borrowed);
3900 assert_eq!($current, owned);
3901 assert_eq!($current, borrowed_cow);
3902 assert_eq!($current, owned_cow);
3907 t!(borrowed, owned, borrowed_cow, owned_cow);
3911 pub fn test_compare() {
3912 use hash::{Hash, Hasher};
3913 use collections::hash_map::DefaultHasher;
3915 fn hash<T: Hash>(t: T) -> u64 {
3916 let mut s = DefaultHasher::new();
3922 ($path1:expr, $path2:expr, eq: $eq:expr,
3923 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3924 relative_from: $relative_from:expr) => ({
3925 let path1 = Path::new($path1);
3926 let path2 = Path::new($path2);
3928 let eq = path1 == path2;
3929 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3930 $path1, $path2, $eq, eq);
3931 assert!($eq == (hash(path1) == hash(path2)),
3932 "{:?} == {:?}, expected {:?}, got {} and {}",
3933 $path1, $path2, $eq, hash(path1), hash(path2));
3935 let starts_with = path1.starts_with(path2);
3936 assert!(starts_with == $starts_with,
3937 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3938 $starts_with, starts_with);
3940 let ends_with = path1.ends_with(path2);
3941 assert!(ends_with == $ends_with,
3942 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3943 $ends_with, ends_with);
3945 let relative_from = path1.strip_prefix(path2)
3946 .map(|p| p.to_str().unwrap())
3948 let exp: Option<&str> = $relative_from;
3949 assert!(relative_from == exp,
3950 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3951 $path1, $path2, exp, relative_from);
3959 relative_from: Some("")
3966 relative_from: Some("foo")
3980 relative_from: Some("")
3987 relative_from: Some("")
3990 tc!("foo/bar", "foo",
3994 relative_from: Some("bar")
3997 tc!("foo/bar/baz", "foo/bar",
4001 relative_from: Some("baz")
4004 tc!("foo/bar", "foo/bar/baz",
4011 tc!("./foo/bar/", ".",
4015 relative_from: Some("foo/bar")
4019 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4020 r"c:\src\rust\cargo-test\test",
4024 relative_from: Some("Cargo.toml")
4027 tc!(r"c:\foo", r"C:\foo",
4031 relative_from: Some("")
4037 fn test_components_debug() {
4038 let path = Path::new("/tmp");
4040 let mut components = path.components();
4042 let expected = "Components([RootDir, Normal(\"tmp\")])";
4043 let actual = format!("{:?}", components);
4044 assert_eq!(expected, actual);
4046 let _ = components.next().unwrap();
4047 let expected = "Components([Normal(\"tmp\")])";
4048 let actual = format!("{:?}", components);
4049 assert_eq!(expected, actual);
4051 let _ = components.next().unwrap();
4052 let expected = "Components([])";
4053 let actual = format!("{:?}", components);
4054 assert_eq!(expected, actual);
4059 fn test_iter_debug() {
4060 let path = Path::new("/tmp");
4062 let mut iter = path.iter();
4064 let expected = "Iter([\"/\", \"tmp\"])";
4065 let actual = format!("{:?}", iter);
4066 assert_eq!(expected, actual);
4068 let _ = iter.next().unwrap();
4069 let expected = "Iter([\"tmp\"])";
4070 let actual = format!("{:?}", iter);
4071 assert_eq!(expected, actual);
4073 let _ = iter.next().unwrap();
4074 let expected = "Iter([])";
4075 let actual = format!("{:?}", iter);
4076 assert_eq!(expected, actual);
4081 let orig: &str = "some/sort/of/path";
4082 let path = Path::new(orig);
4083 let boxed: Box<Path> = Box::from(path);
4084 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4085 assert_eq!(path, &*boxed);
4086 assert_eq!(&*boxed, &*path_buf);
4087 assert_eq!(&*path_buf, path);
4091 fn test_clone_into() {
4092 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4093 let path = Path::new("short");
4094 path.clone_into(&mut path_buf);
4095 assert_eq!(path, path_buf);
4096 assert!(path_buf.into_os_string().capacity() >= 15);
4100 fn display_format_flags() {
4101 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4102 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4107 let orig = "hello/world";
4108 let path = Path::new(orig);
4109 let rc: Rc<Path> = Rc::from(path);
4110 let arc: Arc<Path> = Arc::from(path);
4112 assert_eq!(&*rc, path);
4113 assert_eq!(&*arc, path);
4115 let rc2: Rc<Path> = Rc::from(path.to_owned());
4116 let arc2: Arc<Path> = Arc::from(path.to_owned());
4118 assert_eq!(&*rc2, path);
4119 assert_eq!(&*arc2, path);