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};
91 use string::ParseError;
94 use ffi::{OsStr, OsString};
96 use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
98 ////////////////////////////////////////////////////////////////////////////////
100 ////////////////////////////////////////////////////////////////////////////////
102 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
103 // taking advantage of the fact that OsStr always encodes ASCII characters
104 // as-is. Eventually, this transmutation should be replaced by direct uses of
105 // OsStr APIs for parsing, but it will take a while for those to become
108 ////////////////////////////////////////////////////////////////////////////////
110 ////////////////////////////////////////////////////////////////////////////////
112 /// Windows path prefixes, e.g., `C:` or `\\server\share`.
114 /// Windows uses a variety of path prefix styles, including references to drive
115 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
116 /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
117 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
118 /// no normalization is performed.
123 /// use std::path::{Component, Path, Prefix};
124 /// use std::path::Prefix::*;
125 /// use std::ffi::OsStr;
127 /// fn get_path_prefix(s: &str) -> Prefix {
128 /// let path = Path::new(s);
129 /// match path.components().next().unwrap() {
130 /// Component::Prefix(prefix_component) => prefix_component.kind(),
135 /// # if cfg!(windows) {
136 /// assert_eq!(Verbatim(OsStr::new("pictures")),
137 /// get_path_prefix(r"\\?\pictures\kittens"));
138 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
139 /// get_path_prefix(r"\\?\UNC\server\share"));
140 /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\"));
141 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
142 /// get_path_prefix(r"\\.\BrainInterface"));
143 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
144 /// get_path_prefix(r"\\server\share"));
145 /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
148 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
149 #[stable(feature = "rust1", since = "1.0.0")]
150 pub enum Prefix<'a> {
151 /// Verbatim prefix, e.g., `\\?\cat_pics`.
153 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
155 #[stable(feature = "rust1", since = "1.0.0")]
156 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
158 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
159 /// e.g., `\\?\UNC\server\share`.
161 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
162 /// server's hostname and a share name.
163 #[stable(feature = "rust1", since = "1.0.0")]
165 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
166 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
169 /// Verbatim disk prefix, e.g., `\\?\C:\`.
171 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
172 /// drive letter and `:\`.
173 #[stable(feature = "rust1", since = "1.0.0")]
174 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
176 /// Device namespace prefix, e.g., `\\.\COM42`.
178 /// Device namespace prefixes consist of `\\.\` immediately followed by the
180 #[stable(feature = "rust1", since = "1.0.0")]
181 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
183 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
184 /// `\\server\share`.
186 /// UNC prefixes consist of the server's hostname and a share name.
187 #[stable(feature = "rust1", since = "1.0.0")]
189 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
190 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
193 /// Prefix `C:` for the given disk drive.
194 #[stable(feature = "rust1", since = "1.0.0")]
195 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
198 impl<'a> Prefix<'a> {
200 fn len(&self) -> usize {
202 fn os_str_len(s: &OsStr) -> usize {
203 os_str_as_u8_slice(s).len()
206 Verbatim(x) => 4 + os_str_len(x),
207 VerbatimUNC(x, y) => {
209 if os_str_len(y) > 0 {
215 VerbatimDisk(_) => 6,
218 if os_str_len(y) > 0 {
224 DeviceNS(x) => 4 + os_str_len(x),
230 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
235 /// use std::path::Prefix::*;
236 /// use std::ffi::OsStr;
238 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
239 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
240 /// assert!(VerbatimDisk(b'C').is_verbatim());
241 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
242 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
243 /// assert!(!Disk(b'C').is_verbatim());
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub fn is_verbatim(&self) -> bool {
250 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
256 fn is_drive(&self) -> bool {
258 Prefix::Disk(_) => true,
264 fn has_implicit_root(&self) -> bool {
269 ////////////////////////////////////////////////////////////////////////////////
270 // Exposed parsing helpers
271 ////////////////////////////////////////////////////////////////////////////////
273 /// Determines whether the character is one of the permitted path
274 /// separators for the current platform.
281 /// assert!(path::is_separator('/')); // '/' works for both Unix and Windows
282 /// assert!(!path::is_separator('❤'));
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn is_separator(c: char) -> bool {
286 c.is_ascii() && is_sep_byte(c as u8)
289 /// The primary separator of path components for the current platform.
291 /// For example, `/` on Unix and `\` on Windows.
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
295 ////////////////////////////////////////////////////////////////////////////////
297 ////////////////////////////////////////////////////////////////////////////////
299 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
300 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
301 // `iter` after having exhausted `prefix`.
302 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
303 where I: Iterator<Item = Component<'a>> + Clone,
304 J: Iterator<Item = Component<'b>>,
307 let mut iter_next = iter.clone();
308 match (iter_next.next(), prefix.next()) {
309 (Some(ref x), Some(ref y)) if x == y => (),
310 (Some(_), Some(_)) => return None,
311 (Some(_), None) => return Some(iter),
312 (None, None) => return Some(iter),
313 (None, Some(_)) => return None,
319 // See note at the top of this module to understand why these are used:
320 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
321 unsafe { &*(s as *const OsStr as *const [u8]) }
323 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
324 &*(s as *const [u8] as *const OsStr)
327 // Detect scheme on Redox
328 fn has_redox_scheme(s: &[u8]) -> bool {
329 cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
332 ////////////////////////////////////////////////////////////////////////////////
333 // Cross-platform, iterator-independent parsing
334 ////////////////////////////////////////////////////////////////////////////////
336 /// Says whether the first byte after the prefix is a separator.
337 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
338 let path = if let Some(p) = prefix {
343 !path.is_empty() && is_sep_byte(path[0])
346 // basic workhorse for splitting stem and extension
347 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
349 if os_str_as_u8_slice(file) == b".." {
350 return (Some(file), None);
353 // The unsafety here stems from converting between &OsStr and &[u8]
354 // and back. This is safe to do because (1) we only look at ASCII
355 // contents of the encoding and (2) new &OsStr values are produced
356 // only from ASCII-bounded slices of existing &OsStr values.
358 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
359 let after = iter.next();
360 let before = iter.next();
361 if before == Some(b"") {
364 (before.map(|s| u8_slice_as_os_str(s)),
365 after.map(|s| u8_slice_as_os_str(s)))
370 ////////////////////////////////////////////////////////////////////////////////
371 // The core iterators
372 ////////////////////////////////////////////////////////////////////////////////
374 /// Component parsing works by a double-ended state machine; the cursors at the
375 /// front and back of the path each keep track of what parts of the path have
376 /// been consumed so far.
378 /// Going front to back, a path is made up of a prefix, a starting
379 /// directory component, and a body (of normal components)
380 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
383 StartDir = 1, // / or . or nothing
384 Body = 2, // foo/bar/baz
388 /// A structure wrapping a Windows path prefix as well as its unparsed string
391 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
392 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
393 /// returned by [`as_os_str`].
395 /// Instances of this `struct` can be obtained by matching against the
396 /// [`Prefix` variant] on [`Component`].
398 /// Does not occur on Unix.
403 /// # if cfg!(windows) {
404 /// use std::path::{Component, Path, Prefix};
405 /// use std::ffi::OsStr;
407 /// let path = Path::new(r"c:\you\later\");
408 /// match path.components().next().unwrap() {
409 /// Component::Prefix(prefix_component) => {
410 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
411 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
413 /// _ => unreachable!(),
418 /// [`as_os_str`]: #method.as_os_str
419 /// [`Component`]: enum.Component.html
420 /// [`kind`]: #method.kind
421 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
422 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
423 /// [`Prefix`]: enum.Prefix.html
424 #[stable(feature = "rust1", since = "1.0.0")]
425 #[derive(Copy, Clone, Eq, Debug)]
426 pub struct PrefixComponent<'a> {
427 /// The prefix as an unparsed `OsStr` slice.
430 /// The parsed prefix data.
434 impl<'a> PrefixComponent<'a> {
435 /// Returns the parsed prefix data.
437 /// See [`Prefix`]'s documentation for more information on the different
438 /// kinds of prefixes.
440 /// [`Prefix`]: enum.Prefix.html
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn kind(&self) -> Prefix<'a> {
446 /// Returns the raw [`OsStr`] slice for this prefix.
448 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn as_os_str(&self) -> &'a OsStr {
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
457 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
458 cmp::PartialEq::eq(&self.parsed, &other.parsed)
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
464 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
465 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
469 #[stable(feature = "rust1", since = "1.0.0")]
470 impl<'a> cmp::Ord for PrefixComponent<'a> {
471 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
472 cmp::Ord::cmp(&self.parsed, &other.parsed)
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl<'a> Hash for PrefixComponent<'a> {
478 fn hash<H: Hasher>(&self, h: &mut H) {
483 /// A single component of a path.
485 /// A `Component` roughly corresponds to a substring between path separators
488 /// This `enum` is created by iterating over [`Components`], which in turn is
489 /// created by the [`components`][`Path::components`] method on [`Path`].
494 /// use std::path::{Component, Path};
496 /// let path = Path::new("/tmp/foo/bar.txt");
497 /// let components = path.components().collect::<Vec<_>>();
498 /// assert_eq!(&components, &[
499 /// Component::RootDir,
500 /// Component::Normal("tmp".as_ref()),
501 /// Component::Normal("foo".as_ref()),
502 /// Component::Normal("bar.txt".as_ref()),
506 /// [`Components`]: struct.Components.html
507 /// [`Path`]: struct.Path.html
508 /// [`Path::components`]: struct.Path.html#method.components
509 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub enum Component<'a> {
512 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
514 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
517 /// Does not occur on Unix.
519 /// [`Prefix`]: enum.Prefix.html
520 #[stable(feature = "rust1", since = "1.0.0")]
522 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
525 /// The root directory component, appears after any prefix and before anything else.
527 /// It represents a separator that designates that a path starts from root.
528 #[stable(feature = "rust1", since = "1.0.0")]
531 /// A reference to the current directory, i.e., `.`.
532 #[stable(feature = "rust1", since = "1.0.0")]
535 /// A reference to the parent directory, i.e., `..`.
536 #[stable(feature = "rust1", since = "1.0.0")]
539 /// A normal component, e.g., `a` and `b` in `a/b`.
541 /// This variant is the most common one, it represents references to files
543 #[stable(feature = "rust1", since = "1.0.0")]
544 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
547 impl<'a> Component<'a> {
548 /// Extracts the underlying [`OsStr`] slice.
553 /// use std::path::Path;
555 /// let path = Path::new("./tmp/foo/bar.txt");
556 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
557 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
560 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn as_os_str(self) -> &'a OsStr {
564 Component::Prefix(p) => p.as_os_str(),
565 Component::RootDir => OsStr::new(MAIN_SEP_STR),
566 Component::CurDir => OsStr::new("."),
567 Component::ParentDir => OsStr::new(".."),
568 Component::Normal(path) => path,
573 #[stable(feature = "rust1", since = "1.0.0")]
574 impl<'a> AsRef<OsStr> for Component<'a> {
575 fn as_ref(&self) -> &OsStr {
580 #[stable(feature = "path_component_asref", since = "1.25.0")]
581 impl<'a> AsRef<Path> for Component<'a> {
582 fn as_ref(&self) -> &Path {
583 self.as_os_str().as_ref()
587 /// An iterator over the [`Component`]s of a [`Path`].
589 /// This `struct` is created by the [`components`] method on [`Path`].
590 /// See its documentation for more.
595 /// use std::path::Path;
597 /// let path = Path::new("/tmp/foo/bar.txt");
599 /// for component in path.components() {
600 /// println!("{:?}", component);
604 /// [`Component`]: enum.Component.html
605 /// [`components`]: struct.Path.html#method.components
606 /// [`Path`]: struct.Path.html
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub struct Components<'a> {
610 // The path left to parse components from
613 // The prefix as it was originally parsed, if any
614 prefix: Option<Prefix<'a>>,
616 // true if path *physically* has a root separator; for most Windows
617 // prefixes, it may have a "logical" rootseparator for the purposes of
618 // normalization, e.g., \\server\share == \\server\share\.
619 has_physical_root: bool,
621 // The iterator is double-ended, and these two states keep track of what has
622 // been produced from either end
627 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
629 /// This `struct` is created by the [`iter`] method on [`Path`].
630 /// See its documentation for more.
632 /// [`Component`]: enum.Component.html
633 /// [`iter`]: struct.Path.html#method.iter
634 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
635 /// [`Path`]: struct.Path.html
637 #[stable(feature = "rust1", since = "1.0.0")]
638 pub struct Iter<'a> {
639 inner: Components<'a>,
642 #[stable(feature = "path_components_debug", since = "1.13.0")]
643 impl<'a> fmt::Debug for Components<'a> {
644 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
645 struct DebugHelper<'a>(&'a Path);
647 impl<'a> fmt::Debug for DebugHelper<'a> {
648 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
650 .entries(self.0.components())
655 f.debug_tuple("Components")
656 .field(&DebugHelper(self.as_path()))
661 impl<'a> Components<'a> {
662 // how long is the prefix, if any?
664 fn prefix_len(&self) -> usize {
665 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
669 fn prefix_verbatim(&self) -> bool {
670 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
673 /// how much of the prefix is left from the point of view of iteration?
675 fn prefix_remaining(&self) -> usize {
676 if self.front == State::Prefix {
683 // Given the iteration so far, how much of the pre-State::Body path is left?
685 fn len_before_body(&self) -> usize {
686 let root = if self.front <= State::StartDir && self.has_physical_root {
691 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
696 self.prefix_remaining() + root + cur_dir
699 // is the iteration complete?
701 fn finished(&self) -> bool {
702 self.front == State::Done || self.back == State::Done || self.front > self.back
706 fn is_sep_byte(&self, b: u8) -> bool {
707 if self.prefix_verbatim() {
714 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
719 /// use std::path::Path;
721 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
722 /// components.next();
723 /// components.next();
725 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
727 #[stable(feature = "rust1", since = "1.0.0")]
728 pub fn as_path(&self) -> &'a Path {
729 let mut comps = self.clone();
730 if comps.front == State::Body {
733 if comps.back == State::Body {
736 unsafe { Path::from_u8_slice(comps.path) }
739 /// Is the *original* path rooted?
740 fn has_root(&self) -> bool {
741 if self.has_physical_root {
744 if let Some(p) = self.prefix {
745 if p.has_implicit_root() {
752 /// Should the normalized path include a leading . ?
753 fn include_cur_dir(&self) -> bool {
757 let mut iter = self.path[self.prefix_len()..].iter();
758 match (iter.next(), iter.next()) {
759 (Some(&b'.'), None) => true,
760 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
765 // parse a given byte sequence into the corresponding path component
766 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
768 b"." if self.prefix_verbatim() => Some(Component::CurDir),
769 b"." => None, // . components are normalized away, except at
770 // the beginning of a path, which is treated
771 // separately via `include_cur_dir`
772 b".." => Some(Component::ParentDir),
774 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
778 // parse a component from the left, saying how many bytes to consume to
779 // remove the component
780 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
781 debug_assert!(self.front == State::Body);
782 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
783 None => (0, self.path),
784 Some(i) => (1, &self.path[..i]),
786 (comp.len() + extra, self.parse_single_component(comp))
789 // parse a component from the right, saying how many bytes to consume to
790 // remove the component
791 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
792 debug_assert!(self.back == State::Body);
793 let start = self.len_before_body();
794 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
795 None => (0, &self.path[start..]),
796 Some(i) => (1, &self.path[start + i + 1..]),
798 (comp.len() + extra, self.parse_single_component(comp))
801 // trim away repeated separators (i.e., empty components) on the left
802 fn trim_left(&mut self) {
803 while !self.path.is_empty() {
804 let (size, comp) = self.parse_next_component();
808 self.path = &self.path[size..];
813 // trim away repeated separators (i.e., empty components) on the right
814 fn trim_right(&mut self) {
815 while self.path.len() > self.len_before_body() {
816 let (size, comp) = self.parse_next_component_back();
820 self.path = &self.path[..self.path.len() - size];
826 #[stable(feature = "rust1", since = "1.0.0")]
827 impl<'a> AsRef<Path> for Components<'a> {
828 fn as_ref(&self) -> &Path {
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<'a> AsRef<OsStr> for Components<'a> {
835 fn as_ref(&self) -> &OsStr {
836 self.as_path().as_os_str()
840 #[stable(feature = "path_iter_debug", since = "1.13.0")]
841 impl<'a> fmt::Debug for Iter<'a> {
842 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
843 struct DebugHelper<'a>(&'a Path);
845 impl<'a> fmt::Debug for DebugHelper<'a> {
846 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
848 .entries(self.0.iter())
853 f.debug_tuple("Iter")
854 .field(&DebugHelper(self.as_path()))
860 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
865 /// use std::path::Path;
867 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
871 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
873 #[stable(feature = "rust1", since = "1.0.0")]
874 pub fn as_path(&self) -> &'a Path {
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<'a> AsRef<Path> for Iter<'a> {
881 fn as_ref(&self) -> &Path {
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<'a> AsRef<OsStr> for Iter<'a> {
888 fn as_ref(&self) -> &OsStr {
889 self.as_path().as_os_str()
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<'a> Iterator for Iter<'a> {
895 type Item = &'a OsStr;
897 fn next(&mut self) -> Option<&'a OsStr> {
898 self.inner.next().map(Component::as_os_str)
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a> DoubleEndedIterator for Iter<'a> {
904 fn next_back(&mut self) -> Option<&'a OsStr> {
905 self.inner.next_back().map(Component::as_os_str)
909 #[stable(feature = "fused", since = "1.26.0")]
910 impl<'a> FusedIterator for Iter<'a> {}
912 #[stable(feature = "rust1", since = "1.0.0")]
913 impl<'a> Iterator for Components<'a> {
914 type Item = Component<'a>;
916 fn next(&mut self) -> Option<Component<'a>> {
917 while !self.finished() {
919 State::Prefix if self.prefix_len() > 0 => {
920 self.front = State::StartDir;
921 debug_assert!(self.prefix_len() <= self.path.len());
922 let raw = &self.path[..self.prefix_len()];
923 self.path = &self.path[self.prefix_len()..];
924 return Some(Component::Prefix(PrefixComponent {
925 raw: unsafe { u8_slice_as_os_str(raw) },
926 parsed: self.prefix.unwrap(),
930 self.front = State::StartDir;
933 self.front = State::Body;
934 if self.has_physical_root {
935 debug_assert!(!self.path.is_empty());
936 self.path = &self.path[1..];
937 return Some(Component::RootDir);
938 } else if let Some(p) = self.prefix {
939 if p.has_implicit_root() && !p.is_verbatim() {
940 return Some(Component::RootDir);
942 } else if self.include_cur_dir() {
943 debug_assert!(!self.path.is_empty());
944 self.path = &self.path[1..];
945 return Some(Component::CurDir);
948 State::Body if !self.path.is_empty() => {
949 let (size, comp) = self.parse_next_component();
950 self.path = &self.path[size..];
956 self.front = State::Done;
958 State::Done => unreachable!(),
965 #[stable(feature = "rust1", since = "1.0.0")]
966 impl<'a> DoubleEndedIterator for Components<'a> {
967 fn next_back(&mut self) -> Option<Component<'a>> {
968 while !self.finished() {
970 State::Body if self.path.len() > self.len_before_body() => {
971 let (size, comp) = self.parse_next_component_back();
972 self.path = &self.path[..self.path.len() - size];
978 self.back = State::StartDir;
981 self.back = State::Prefix;
982 if self.has_physical_root {
983 self.path = &self.path[..self.path.len() - 1];
984 return Some(Component::RootDir);
985 } else if let Some(p) = self.prefix {
986 if p.has_implicit_root() && !p.is_verbatim() {
987 return Some(Component::RootDir);
989 } else if self.include_cur_dir() {
990 self.path = &self.path[..self.path.len() - 1];
991 return Some(Component::CurDir);
994 State::Prefix if self.prefix_len() > 0 => {
995 self.back = State::Done;
996 return Some(Component::Prefix(PrefixComponent {
997 raw: unsafe { u8_slice_as_os_str(self.path) },
998 parsed: self.prefix.unwrap(),
1002 self.back = State::Done;
1005 State::Done => unreachable!(),
1012 #[stable(feature = "fused", since = "1.26.0")]
1013 impl<'a> FusedIterator for Components<'a> {}
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<'a> cmp::PartialEq for Components<'a> {
1017 fn eq(&self, other: &Components<'a>) -> bool {
1018 Iterator::eq(self.clone(), other.clone())
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<'a> cmp::Eq for Components<'a> {}
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<'a> cmp::PartialOrd for Components<'a> {
1027 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1028 Iterator::partial_cmp(self.clone(), other.clone())
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 impl<'a> cmp::Ord for Components<'a> {
1034 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
1035 Iterator::cmp(self.clone(), other.clone())
1039 /// An iterator over [`Path`] and its ancestors.
1041 /// This `struct` is created by the [`ancestors`] method on [`Path`].
1042 /// See its documentation for more.
1047 /// use std::path::Path;
1049 /// let path = Path::new("/foo/bar");
1051 /// for ancestor in path.ancestors() {
1052 /// println!("{}", ancestor.display());
1056 /// [`ancestors`]: struct.Path.html#method.ancestors
1057 /// [`Path`]: struct.Path.html
1058 #[derive(Copy, Clone, Debug)]
1059 #[stable(feature = "path_ancestors", since = "1.28.0")]
1060 pub struct Ancestors<'a> {
1061 next: Option<&'a Path>,
1064 #[stable(feature = "path_ancestors", since = "1.28.0")]
1065 impl<'a> Iterator for Ancestors<'a> {
1066 type Item = &'a Path;
1068 fn next(&mut self) -> Option<Self::Item> {
1069 let next = self.next;
1070 self.next = next.and_then(Path::parent);
1075 #[stable(feature = "path_ancestors", since = "1.28.0")]
1076 impl<'a> FusedIterator for Ancestors<'a> {}
1078 ////////////////////////////////////////////////////////////////////////////////
1079 // Basic types and traits
1080 ////////////////////////////////////////////////////////////////////////////////
1082 /// An owned, mutable path (akin to [`String`]).
1084 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1085 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1086 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1088 /// [`String`]: ../string/struct.String.html
1089 /// [`Path`]: struct.Path.html
1090 /// [`push`]: struct.PathBuf.html#method.push
1091 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1092 /// [`Deref`]: ../ops/trait.Deref.html
1094 /// More details about the overall approach can be found in
1095 /// the [module documentation](index.html).
1099 /// You can use [`push`] to build up a `PathBuf` from
1103 /// use std::path::PathBuf;
1105 /// let mut path = PathBuf::new();
1107 /// path.push(r"C:\");
1108 /// path.push("windows");
1109 /// path.push("system32");
1111 /// path.set_extension("dll");
1114 /// However, [`push`] is best used for dynamic situations. This is a better way
1115 /// to do this when you know all of the components ahead of time:
1118 /// use std::path::PathBuf;
1120 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1123 /// We can still do better than this! Since these are all strings, we can use
1127 /// use std::path::PathBuf;
1129 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1132 /// Which method works best depends on what kind of situation you're in.
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 pub struct PathBuf {
1140 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1141 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1144 /// Allocates an empty `PathBuf`.
1149 /// use std::path::PathBuf;
1151 /// let path = PathBuf::new();
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn new() -> PathBuf {
1155 PathBuf { inner: OsString::new() }
1158 /// Coerces to a [`Path`] slice.
1160 /// [`Path`]: struct.Path.html
1165 /// use std::path::{Path, PathBuf};
1167 /// let p = PathBuf::from("/test");
1168 /// assert_eq!(Path::new("/test"), p.as_path());
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub fn as_path(&self) -> &Path {
1175 /// Extends `self` with `path`.
1177 /// If `path` is absolute, it replaces the current path.
1181 /// * if `path` has a root but no prefix (e.g., `\windows`), it
1182 /// replaces everything except for the prefix (if any) of `self`.
1183 /// * if `path` has a prefix but no root, it replaces `self`.
1187 /// Pushing a relative path extends the existing path:
1190 /// use std::path::PathBuf;
1192 /// let mut path = PathBuf::from("/tmp");
1193 /// path.push("file.bk");
1194 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1197 /// Pushing an absolute path replaces the existing path:
1200 /// use std::path::PathBuf;
1202 /// let mut path = PathBuf::from("/tmp");
1203 /// path.push("/etc");
1204 /// assert_eq!(path, PathBuf::from("/etc"));
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1208 self._push(path.as_ref())
1211 fn _push(&mut self, path: &Path) {
1212 // in general, a separator is needed if the rightmost byte is not a separator
1213 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1215 // in the special case of `C:` on Windows, do *not* add a separator
1217 let comps = self.components();
1218 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1219 comps.prefix.unwrap().is_drive() {
1224 // absolute `path` replaces `self`
1225 if path.is_absolute() || path.prefix().is_some() {
1226 self.as_mut_vec().truncate(0);
1228 // `path` has a root but no prefix, e.g., `\windows` (Windows only)
1229 } else if path.has_root() {
1230 let prefix_len = self.components().prefix_remaining();
1231 self.as_mut_vec().truncate(prefix_len);
1233 // `path` is a pure relative path
1234 } else if need_sep {
1235 self.inner.push(MAIN_SEP_STR);
1238 self.inner.push(path);
1241 /// Truncates `self` to [`self.parent`].
1243 /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1244 /// Otherwise, returns `true`.
1246 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1247 /// [`self.parent`]: struct.PathBuf.html#method.parent
1248 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1253 /// use std::path::{Path, PathBuf};
1255 /// let mut p = PathBuf::from("/test/test.rs");
1258 /// assert_eq!(Path::new("/test"), p);
1260 /// assert_eq!(Path::new("/"), p);
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 pub fn pop(&mut self) -> bool {
1264 match self.parent().map(|p| p.as_u8_slice().len()) {
1266 self.as_mut_vec().truncate(len);
1273 /// Updates [`self.file_name`] to `file_name`.
1275 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1278 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1279 /// `file_name`. The new path will be a sibling of the original path.
1280 /// (That is, it will have the same parent.)
1282 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1283 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1284 /// [`pop`]: struct.PathBuf.html#method.pop
1289 /// use std::path::PathBuf;
1291 /// let mut buf = PathBuf::from("/");
1292 /// assert!(buf.file_name() == None);
1293 /// buf.set_file_name("bar");
1294 /// assert!(buf == PathBuf::from("/bar"));
1295 /// assert!(buf.file_name().is_some());
1296 /// buf.set_file_name("baz.txt");
1297 /// assert!(buf == PathBuf::from("/baz.txt"));
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1301 self._set_file_name(file_name.as_ref())
1304 fn _set_file_name(&mut self, file_name: &OsStr) {
1305 if self.file_name().is_some() {
1306 let popped = self.pop();
1307 debug_assert!(popped);
1309 self.push(file_name);
1312 /// Updates [`self.extension`] to `extension`.
1314 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1315 /// returns `true` and updates the extension otherwise.
1317 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1320 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1321 /// [`self.extension`]: struct.PathBuf.html#method.extension
1322 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1327 /// use std::path::{Path, PathBuf};
1329 /// let mut p = PathBuf::from("/feel/the");
1331 /// p.set_extension("force");
1332 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1334 /// p.set_extension("dark_side");
1335 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1339 self._set_extension(extension.as_ref())
1342 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1343 if self.file_name().is_none() {
1347 let mut stem = match self.file_stem() {
1348 Some(stem) => stem.to_os_string(),
1349 None => OsString::new(),
1352 if !os_str_as_u8_slice(extension).is_empty() {
1354 stem.push(extension);
1356 self.set_file_name(&stem);
1361 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1363 /// [`OsString`]: ../ffi/struct.OsString.html
1368 /// use std::path::PathBuf;
1370 /// let p = PathBuf::from("/the/head");
1371 /// let os_str = p.into_os_string();
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub fn into_os_string(self) -> OsString {
1378 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1380 /// [`Box`]: ../../std/boxed/struct.Box.html
1381 /// [`Path`]: struct.Path.html
1382 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1383 pub fn into_boxed_path(self) -> Box<Path> {
1384 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1385 unsafe { Box::from_raw(rw) }
1389 #[stable(feature = "box_from_path", since = "1.17.0")]
1390 impl<'a> From<&'a Path> for Box<Path> {
1391 fn from(path: &'a Path) -> Box<Path> {
1392 let boxed: Box<OsStr> = path.inner.into();
1393 let rw = Box::into_raw(boxed) as *mut Path;
1394 unsafe { Box::from_raw(rw) }
1398 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1399 impl From<Box<Path>> for PathBuf {
1400 /// Converts a `Box<Path>` into a `PathBuf`
1402 /// This conversion does not allocate or copy memory.
1403 fn from(boxed: Box<Path>) -> PathBuf {
1404 boxed.into_path_buf()
1408 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1409 impl From<PathBuf> for Box<Path> {
1410 /// Converts a `PathBuf` into a `Box<Path>`
1412 /// This conversion currently should not allocate memory,
1413 /// but this behavior is not guaranteed on all platforms or in all future versions.
1414 fn from(p: PathBuf) -> Box<Path> {
1419 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1420 impl Clone for Box<Path> {
1422 fn clone(&self) -> Self {
1423 self.to_path_buf().into_boxed_path()
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1429 fn from(s: &'a T) -> PathBuf {
1430 PathBuf::from(s.as_ref().to_os_string())
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl From<OsString> for PathBuf {
1436 /// Converts a `OsString` into a `PathBuf`
1438 /// This conversion does not allocate or copy memory.
1439 fn from(s: OsString) -> PathBuf {
1440 PathBuf { inner: s }
1444 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1445 impl From<PathBuf> for OsString {
1446 /// Converts a `PathBuf` into a `OsString`
1448 /// This conversion does not allocate or copy memory.
1449 fn from(path_buf : PathBuf) -> OsString {
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 impl From<String> for PathBuf {
1456 /// Converts a `String` into a `PathBuf`
1458 /// This conversion does not allocate or copy memory.
1459 fn from(s: String) -> PathBuf {
1460 PathBuf::from(OsString::from(s))
1464 #[stable(feature = "path_from_str", since = "1.26.0")]
1465 impl FromStr for PathBuf {
1466 type Err = ParseError;
1468 fn from_str(s: &str) -> Result<Self, Self::Err> {
1469 Ok(PathBuf::from(s))
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1475 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1476 let mut buf = PathBuf::new();
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1484 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1486 self.push(p.as_ref())
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl fmt::Debug for PathBuf {
1493 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1494 fmt::Debug::fmt(&**self, formatter)
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl ops::Deref for PathBuf {
1502 fn deref(&self) -> &Path {
1503 Path::new(&self.inner)
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl Borrow<Path> for PathBuf {
1509 fn borrow(&self) -> &Path {
1514 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1515 impl Default for PathBuf {
1516 fn default() -> Self {
1521 #[stable(feature = "cow_from_path", since = "1.6.0")]
1522 impl<'a> From<&'a Path> for Cow<'a, Path> {
1524 fn from(s: &'a Path) -> Cow<'a, Path> {
1529 #[stable(feature = "cow_from_path", since = "1.6.0")]
1530 impl<'a> From<PathBuf> for Cow<'a, Path> {
1532 fn from(s: PathBuf) -> Cow<'a, Path> {
1537 #[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
1538 impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
1540 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
1541 Cow::Borrowed(p.as_path())
1545 #[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
1546 impl<'a> From<Cow<'a, Path>> for PathBuf {
1548 fn from(p: Cow<'a, Path>) -> Self {
1553 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1554 impl From<PathBuf> for Arc<Path> {
1555 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1557 fn from(s: PathBuf) -> Arc<Path> {
1558 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1559 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1563 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1564 impl<'a> From<&'a Path> for Arc<Path> {
1565 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1567 fn from(s: &Path) -> Arc<Path> {
1568 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1569 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1573 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1574 impl From<PathBuf> for Rc<Path> {
1575 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1577 fn from(s: PathBuf) -> Rc<Path> {
1578 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1579 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1583 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1584 impl<'a> From<&'a Path> for Rc<Path> {
1585 /// Converts a Path into a Rc by copying the Path data into a new Rc buffer.
1587 fn from(s: &Path) -> Rc<Path> {
1588 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1589 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl ToOwned for Path {
1595 type Owned = PathBuf;
1596 fn to_owned(&self) -> PathBuf {
1599 fn clone_into(&self, target: &mut PathBuf) {
1600 self.inner.clone_into(&mut target.inner);
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl cmp::PartialEq for PathBuf {
1606 fn eq(&self, other: &PathBuf) -> bool {
1607 self.components() == other.components()
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl Hash for PathBuf {
1613 fn hash<H: Hasher>(&self, h: &mut H) {
1614 self.as_path().hash(h)
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 impl cmp::Eq for PathBuf {}
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl cmp::PartialOrd for PathBuf {
1623 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1624 self.components().partial_cmp(other.components())
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl cmp::Ord for PathBuf {
1630 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1631 self.components().cmp(other.components())
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl AsRef<OsStr> for PathBuf {
1637 fn as_ref(&self) -> &OsStr {
1642 /// A slice of a path (akin to [`str`]).
1644 /// This type supports a number of operations for inspecting a path, including
1645 /// breaking the path into its components (separated by `/` on Unix and by either
1646 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1647 /// is absolute, and so on.
1649 /// This is an *unsized* type, meaning that it must always be used behind a
1650 /// pointer like `&` or [`Box`]. For an owned version of this type,
1651 /// see [`PathBuf`].
1653 /// [`str`]: ../primitive.str.html
1654 /// [`Box`]: ../boxed/struct.Box.html
1655 /// [`PathBuf`]: struct.PathBuf.html
1657 /// More details about the overall approach can be found in
1658 /// the [module documentation](index.html).
1663 /// use std::path::Path;
1664 /// use std::ffi::OsStr;
1666 /// // Note: this example does work on Windows
1667 /// let path = Path::new("./foo/bar.txt");
1669 /// let parent = path.parent();
1670 /// assert_eq!(parent, Some(Path::new("./foo")));
1672 /// let file_stem = path.file_stem();
1673 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1675 /// let extension = path.extension();
1676 /// assert_eq!(extension, Some(OsStr::new("txt")));
1678 #[stable(feature = "rust1", since = "1.0.0")]
1683 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1686 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1687 /// See its documentation for more.
1689 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1690 /// [`Path`]: struct.Path.html
1691 #[derive(Debug, Clone, PartialEq, Eq)]
1692 #[stable(since = "1.7.0", feature = "strip_prefix")]
1693 pub struct StripPrefixError(());
1696 // The following (private!) function allows construction of a path from a u8
1697 // slice, which is only safe when it is known to follow the OsStr encoding.
1698 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1699 Path::new(u8_slice_as_os_str(s))
1701 // The following (private!) function reveals the byte encoding used for OsStr.
1702 fn as_u8_slice(&self) -> &[u8] {
1703 os_str_as_u8_slice(&self.inner)
1706 /// Directly wraps a string slice as a `Path` slice.
1708 /// This is a cost-free conversion.
1713 /// use std::path::Path;
1715 /// Path::new("foo.txt");
1718 /// You can create `Path`s from `String`s, or even other `Path`s:
1721 /// use std::path::Path;
1723 /// let string = String::from("foo.txt");
1724 /// let from_string = Path::new(&string);
1725 /// let from_path = Path::new(&from_string);
1726 /// assert_eq!(from_string, from_path);
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1730 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1733 /// Yields the underlying [`OsStr`] slice.
1735 /// [`OsStr`]: ../ffi/struct.OsStr.html
1740 /// use std::path::Path;
1742 /// let os_str = Path::new("foo.txt").as_os_str();
1743 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub fn as_os_str(&self) -> &OsStr {
1750 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1752 /// This conversion may entail doing a check for UTF-8 validity.
1754 /// [`&str`]: ../primitive.str.html
1759 /// use std::path::Path;
1761 /// let path = Path::new("foo.txt");
1762 /// assert_eq!(path.to_str(), Some("foo.txt"));
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 pub fn to_str(&self) -> Option<&str> {
1769 /// Converts a `Path` to a [`Cow<str>`].
1771 /// Any non-Unicode sequences are replaced with
1772 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
1774 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1775 /// [U+FFFD]: ../char/constant.REPLACEMENT_CHARACTER.html
1779 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1782 /// use std::path::Path;
1784 /// let path = Path::new("foo.txt");
1785 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1788 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1789 /// have returned `"fo�.txt"`.
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 pub fn to_string_lossy(&self) -> Cow<str> {
1792 self.inner.to_string_lossy()
1795 /// Converts a `Path` to an owned [`PathBuf`].
1797 /// [`PathBuf`]: struct.PathBuf.html
1802 /// use std::path::Path;
1804 /// let path_buf = Path::new("foo.txt").to_path_buf();
1805 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1807 #[rustc_conversion_suggestion]
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 pub fn to_path_buf(&self) -> PathBuf {
1810 PathBuf::from(self.inner.to_os_string())
1813 /// Returns `true` if the `Path` is absolute, i.e., if it is independent of
1814 /// the current directory.
1816 /// * On Unix, a path is absolute if it starts with the root, so
1817 /// `is_absolute` and [`has_root`] are equivalent.
1819 /// * On Windows, a path is absolute if it has a prefix and starts with the
1820 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1825 /// use std::path::Path;
1827 /// assert!(!Path::new("foo.txt").is_absolute());
1830 /// [`has_root`]: #method.has_root
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 #[allow(deprecated)]
1833 pub fn is_absolute(&self) -> bool {
1834 if cfg!(target_os = "redox") {
1835 // FIXME: Allow Redox prefixes
1836 self.has_root() || has_redox_scheme(self.as_u8_slice())
1838 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1842 /// Returns `true` if the `Path` is relative, i.e., not absolute.
1844 /// See [`is_absolute`]'s documentation for more details.
1849 /// use std::path::Path;
1851 /// assert!(Path::new("foo.txt").is_relative());
1854 /// [`is_absolute`]: #method.is_absolute
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 pub fn is_relative(&self) -> bool {
1860 fn prefix(&self) -> Option<Prefix> {
1861 self.components().prefix
1864 /// Returns `true` if the `Path` has a root.
1866 /// * On Unix, a path has a root if it begins with `/`.
1868 /// * On Windows, a path has a root if it:
1869 /// * has no prefix and begins with a separator, e.g., `\windows`
1870 /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows`
1871 /// * has any non-disk prefix, e.g., `\\server\share`
1876 /// use std::path::Path;
1878 /// assert!(Path::new("/etc/passwd").has_root());
1880 #[stable(feature = "rust1", since = "1.0.0")]
1881 pub fn has_root(&self) -> bool {
1882 self.components().has_root()
1885 /// Returns the `Path` without its final component, if there is one.
1887 /// Returns [`None`] if the path terminates in a root or prefix.
1889 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1894 /// use std::path::Path;
1896 /// let path = Path::new("/foo/bar");
1897 /// let parent = path.parent().unwrap();
1898 /// assert_eq!(parent, Path::new("/foo"));
1900 /// let grand_parent = parent.parent().unwrap();
1901 /// assert_eq!(grand_parent, Path::new("/"));
1902 /// assert_eq!(grand_parent.parent(), None);
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 pub fn parent(&self) -> Option<&Path> {
1906 let mut comps = self.components();
1907 let comp = comps.next_back();
1910 Component::Normal(_) |
1912 Component::ParentDir => Some(comps.as_path()),
1918 /// Produces an iterator over `Path` and its ancestors.
1920 /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero
1921 /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
1922 /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
1923 /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
1929 /// use std::path::Path;
1931 /// let mut ancestors = Path::new("/foo/bar").ancestors();
1932 /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
1933 /// assert_eq!(ancestors.next(), Some(Path::new("/foo")));
1934 /// assert_eq!(ancestors.next(), Some(Path::new("/")));
1935 /// assert_eq!(ancestors.next(), None);
1938 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1939 /// [`parent`]: struct.Path.html#method.parent
1940 #[stable(feature = "path_ancestors", since = "1.28.0")]
1941 pub fn ancestors(&self) -> Ancestors {
1947 /// Returns the final component of the `Path`, if there is one.
1949 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1950 /// is the directory name.
1952 /// Returns [`None`] if the path terminates in `..`.
1954 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1959 /// use std::path::Path;
1960 /// use std::ffi::OsStr;
1962 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1963 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1964 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1965 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1966 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1967 /// assert_eq!(None, Path::new("/").file_name());
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 pub fn file_name(&self) -> Option<&OsStr> {
1971 self.components().next_back().and_then(|p| {
1973 Component::Normal(p) => Some(p.as_ref()),
1979 /// Returns a path that, when joined onto `base`, yields `self`.
1983 /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
1984 /// returns `false`), returns [`Err`].
1986 /// [`starts_with`]: #method.starts_with
1987 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1992 /// use std::path::{Path, PathBuf};
1994 /// let path = Path::new("/test/haha/foo.txt");
1996 /// assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
1997 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1998 /// assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
1999 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
2000 /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
2001 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
2002 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
2004 /// let prefix = PathBuf::from("/test/");
2005 /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
2007 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2008 pub fn strip_prefix<P>(&self, base: P)
2009 -> Result<&Path, StripPrefixError>
2010 where P: AsRef<Path>
2012 self._strip_prefix(base.as_ref())
2015 fn _strip_prefix(&self, base: &Path)
2016 -> Result<&Path, StripPrefixError> {
2017 iter_after(self.components(), base.components())
2018 .map(|c| c.as_path())
2019 .ok_or(StripPrefixError(()))
2022 /// Determines whether `base` is a prefix of `self`.
2024 /// Only considers whole path components to match.
2029 /// use std::path::Path;
2031 /// let path = Path::new("/etc/passwd");
2033 /// assert!(path.starts_with("/etc"));
2034 /// assert!(path.starts_with("/etc/"));
2035 /// assert!(path.starts_with("/etc/passwd"));
2036 /// assert!(path.starts_with("/etc/passwd/"));
2038 /// assert!(!path.starts_with("/e"));
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2042 self._starts_with(base.as_ref())
2045 fn _starts_with(&self, base: &Path) -> bool {
2046 iter_after(self.components(), base.components()).is_some()
2049 /// Determines whether `child` is a suffix of `self`.
2051 /// Only considers whole path components to match.
2056 /// use std::path::Path;
2058 /// let path = Path::new("/etc/passwd");
2060 /// assert!(path.ends_with("passwd"));
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2064 self._ends_with(child.as_ref())
2067 fn _ends_with(&self, child: &Path) -> bool {
2068 iter_after(self.components().rev(), child.components().rev()).is_some()
2071 /// Extracts the stem (non-extension) portion of [`self.file_name`].
2073 /// [`self.file_name`]: struct.Path.html#method.file_name
2077 /// * [`None`], if there is no file name;
2078 /// * The entire file name if there is no embedded `.`;
2079 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
2080 /// * Otherwise, the portion of the file name before the final `.`
2082 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2087 /// use std::path::Path;
2089 /// let path = Path::new("foo.rs");
2091 /// assert_eq!("foo", path.file_stem().unwrap());
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 pub fn file_stem(&self) -> Option<&OsStr> {
2095 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
2098 /// Extracts the extension of [`self.file_name`], if possible.
2100 /// The extension is:
2102 /// * [`None`], if there is no file name;
2103 /// * [`None`], if there is no embedded `.`;
2104 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
2105 /// * Otherwise, the portion of the file name after the final `.`
2107 /// [`self.file_name`]: struct.Path.html#method.file_name
2108 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2113 /// use std::path::Path;
2115 /// let path = Path::new("foo.rs");
2117 /// assert_eq!("rs", path.extension().unwrap());
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 pub fn extension(&self) -> Option<&OsStr> {
2121 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
2124 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
2126 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
2128 /// [`PathBuf`]: struct.PathBuf.html
2129 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2134 /// use std::path::{Path, PathBuf};
2136 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2138 #[stable(feature = "rust1", since = "1.0.0")]
2139 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2140 self._join(path.as_ref())
2143 fn _join(&self, path: &Path) -> PathBuf {
2144 let mut buf = self.to_path_buf();
2149 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2151 /// See [`PathBuf::set_file_name`] for more details.
2153 /// [`PathBuf`]: struct.PathBuf.html
2154 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2159 /// use std::path::{Path, PathBuf};
2161 /// let path = Path::new("/tmp/foo.txt");
2162 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2164 /// let path = Path::new("/tmp");
2165 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2169 self._with_file_name(file_name.as_ref())
2172 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2173 let mut buf = self.to_path_buf();
2174 buf.set_file_name(file_name);
2178 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2180 /// See [`PathBuf::set_extension`] for more details.
2182 /// [`PathBuf`]: struct.PathBuf.html
2183 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2188 /// use std::path::{Path, PathBuf};
2190 /// let path = Path::new("foo.rs");
2191 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2193 #[stable(feature = "rust1", since = "1.0.0")]
2194 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2195 self._with_extension(extension.as_ref())
2198 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2199 let mut buf = self.to_path_buf();
2200 buf.set_extension(extension);
2204 /// Produces an iterator over the [`Component`]s of the path.
2206 /// When parsing the path, there is a small amount of normalization:
2208 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2209 /// `a` and `b` as components.
2211 /// * Occurrences of `.` are normalized away, except if they are at the
2212 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2213 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2214 /// an additional [`CurDir`] component.
2216 /// Note that no other normalization takes place; in particular, `a/c`
2217 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2218 /// is a symbolic link (so its parent isn't `a`).
2223 /// use std::path::{Path, Component};
2224 /// use std::ffi::OsStr;
2226 /// let mut components = Path::new("/tmp/foo.txt").components();
2228 /// assert_eq!(components.next(), Some(Component::RootDir));
2229 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2230 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2231 /// assert_eq!(components.next(), None)
2234 /// [`Component`]: enum.Component.html
2235 /// [`CurDir`]: enum.Component.html#variant.CurDir
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 pub fn components(&self) -> Components {
2238 let prefix = parse_prefix(self.as_os_str());
2240 path: self.as_u8_slice(),
2242 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2243 has_redox_scheme(self.as_u8_slice()),
2244 front: State::Prefix,
2249 /// Produces an iterator over the path's components viewed as [`OsStr`]
2252 /// For more information about the particulars of how the path is separated
2253 /// into components, see [`components`].
2255 /// [`components`]: #method.components
2256 /// [`OsStr`]: ../ffi/struct.OsStr.html
2261 /// use std::path::{self, Path};
2262 /// use std::ffi::OsStr;
2264 /// let mut it = Path::new("/tmp/foo.txt").iter();
2265 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2266 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2267 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2268 /// assert_eq!(it.next(), None)
2270 #[stable(feature = "rust1", since = "1.0.0")]
2271 pub fn iter(&self) -> Iter {
2272 Iter { inner: self.components() }
2275 /// Returns an object that implements [`Display`] for safely printing paths
2276 /// that may contain non-Unicode data.
2278 /// [`Display`]: ../fmt/trait.Display.html
2283 /// use std::path::Path;
2285 /// let path = Path::new("/tmp/foo.rs");
2287 /// println!("{}", path.display());
2289 #[stable(feature = "rust1", since = "1.0.0")]
2290 pub fn display(&self) -> Display {
2291 Display { path: self }
2294 /// Queries the file system to get information about a file, directory, etc.
2296 /// This function will traverse symbolic links to query information about the
2297 /// destination file.
2299 /// This is an alias to [`fs::metadata`].
2301 /// [`fs::metadata`]: ../fs/fn.metadata.html
2306 /// use std::path::Path;
2308 /// let path = Path::new("/Minas/tirith");
2309 /// let metadata = path.metadata().expect("metadata call failed");
2310 /// println!("{:?}", metadata.file_type());
2312 #[stable(feature = "path_ext", since = "1.5.0")]
2313 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2317 /// Queries the metadata about a file without following symlinks.
2319 /// This is an alias to [`fs::symlink_metadata`].
2321 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2326 /// use std::path::Path;
2328 /// let path = Path::new("/Minas/tirith");
2329 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2330 /// println!("{:?}", metadata.file_type());
2332 #[stable(feature = "path_ext", since = "1.5.0")]
2333 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2334 fs::symlink_metadata(self)
2337 /// Returns the canonical, absolute form of the path with all intermediate
2338 /// components normalized and symbolic links resolved.
2340 /// This is an alias to [`fs::canonicalize`].
2342 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2347 /// use std::path::{Path, PathBuf};
2349 /// let path = Path::new("/foo/test/../test/bar.rs");
2350 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2352 #[stable(feature = "path_ext", since = "1.5.0")]
2353 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2354 fs::canonicalize(self)
2357 /// Reads a symbolic link, returning the file that the link points to.
2359 /// This is an alias to [`fs::read_link`].
2361 /// [`fs::read_link`]: ../fs/fn.read_link.html
2366 /// use std::path::Path;
2368 /// let path = Path::new("/laputa/sky_castle.rs");
2369 /// let path_link = path.read_link().expect("read_link call failed");
2371 #[stable(feature = "path_ext", since = "1.5.0")]
2372 pub fn read_link(&self) -> io::Result<PathBuf> {
2376 /// Returns an iterator over the entries within a directory.
2378 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2379 /// errors may be encountered after an iterator is initially constructed.
2381 /// This is an alias to [`fs::read_dir`].
2383 /// [`io::Result`]: ../io/type.Result.html
2384 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2385 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2390 /// use std::path::Path;
2392 /// let path = Path::new("/laputa");
2393 /// for entry in path.read_dir().expect("read_dir call failed") {
2394 /// if let Ok(entry) = entry {
2395 /// println!("{:?}", entry.path());
2399 #[stable(feature = "path_ext", since = "1.5.0")]
2400 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2404 /// Returns whether the path points at an existing entity.
2406 /// This function will traverse symbolic links to query information about the
2407 /// destination file. In case of broken symbolic links this will return `false`.
2409 /// If you cannot access the directory containing the file, e.g., because of a
2410 /// permission error, this will return `false`.
2415 /// use std::path::Path;
2416 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2421 /// This is a convenience function that coerces errors to false. If you want to
2422 /// check errors, call [fs::metadata].
2424 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2425 #[stable(feature = "path_ext", since = "1.5.0")]
2426 pub fn exists(&self) -> bool {
2427 fs::metadata(self).is_ok()
2430 /// Returns whether the path exists on disk and is pointing at a regular file.
2432 /// This function will traverse symbolic links to query information about the
2433 /// destination file. In case of broken symbolic links this will return `false`.
2435 /// If you cannot access the directory containing the file, e.g., because of a
2436 /// permission error, this will return `false`.
2441 /// use std::path::Path;
2442 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2443 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2448 /// This is a convenience function that coerces errors to false. If you want to
2449 /// check errors, call [fs::metadata] and handle its Result. Then call
2450 /// [fs::Metadata::is_file] if it was Ok.
2452 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2453 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2454 #[stable(feature = "path_ext", since = "1.5.0")]
2455 pub fn is_file(&self) -> bool {
2456 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2459 /// Returns whether the path exists on disk and is pointing at a directory.
2461 /// This function will traverse symbolic links to query information about the
2462 /// destination file. In case of broken symbolic links this will return `false`.
2464 /// If you cannot access the directory containing the file, e.g., because of a
2465 /// permission error, this will return `false`.
2470 /// use std::path::Path;
2471 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2472 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2477 /// This is a convenience function that coerces errors to false. If you want to
2478 /// check errors, call [fs::metadata] and handle its Result. Then call
2479 /// [fs::Metadata::is_dir] if it was Ok.
2481 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2482 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2483 #[stable(feature = "path_ext", since = "1.5.0")]
2484 pub fn is_dir(&self) -> bool {
2485 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2488 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2491 /// [`Box`]: ../../std/boxed/struct.Box.html
2492 /// [`PathBuf`]: struct.PathBuf.html
2493 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2494 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2495 let rw = Box::into_raw(self) as *mut OsStr;
2496 let inner = unsafe { Box::from_raw(rw) };
2497 PathBuf { inner: OsString::from(inner) }
2501 #[stable(feature = "rust1", since = "1.0.0")]
2502 impl AsRef<OsStr> for Path {
2503 fn as_ref(&self) -> &OsStr {
2508 #[stable(feature = "rust1", since = "1.0.0")]
2509 impl fmt::Debug for Path {
2510 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2511 fmt::Debug::fmt(&self.inner, formatter)
2515 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2517 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2518 /// [`Display`] trait in a way that mitigates that. It is created by the
2519 /// [`display`][`Path::display`] method on [`Path`].
2524 /// use std::path::Path;
2526 /// let path = Path::new("/tmp/foo.rs");
2528 /// println!("{}", path.display());
2531 /// [`Display`]: ../../std/fmt/trait.Display.html
2532 /// [`format!`]: ../../std/macro.format.html
2533 /// [`Path`]: struct.Path.html
2534 /// [`Path::display`]: struct.Path.html#method.display
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 pub struct Display<'a> {
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 impl<'a> fmt::Debug for Display<'a> {
2542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2543 fmt::Debug::fmt(&self.path, f)
2547 #[stable(feature = "rust1", since = "1.0.0")]
2548 impl<'a> fmt::Display for Display<'a> {
2549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2550 self.path.inner.display(f)
2554 #[stable(feature = "rust1", since = "1.0.0")]
2555 impl cmp::PartialEq for Path {
2556 fn eq(&self, other: &Path) -> bool {
2557 self.components().eq(other.components())
2561 #[stable(feature = "rust1", since = "1.0.0")]
2562 impl Hash for Path {
2563 fn hash<H: Hasher>(&self, h: &mut H) {
2564 for component in self.components() {
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 impl cmp::Eq for Path {}
2573 #[stable(feature = "rust1", since = "1.0.0")]
2574 impl cmp::PartialOrd for Path {
2575 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2576 self.components().partial_cmp(other.components())
2580 #[stable(feature = "rust1", since = "1.0.0")]
2581 impl cmp::Ord for Path {
2582 fn cmp(&self, other: &Path) -> cmp::Ordering {
2583 self.components().cmp(other.components())
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 impl AsRef<Path> for Path {
2589 fn as_ref(&self) -> &Path {
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 impl AsRef<Path> for OsStr {
2596 fn as_ref(&self) -> &Path {
2601 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2602 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2603 fn as_ref(&self) -> &Path {
2608 #[stable(feature = "rust1", since = "1.0.0")]
2609 impl AsRef<Path> for OsString {
2610 fn as_ref(&self) -> &Path {
2615 #[stable(feature = "rust1", since = "1.0.0")]
2616 impl AsRef<Path> for str {
2617 fn as_ref(&self) -> &Path {
2622 #[stable(feature = "rust1", since = "1.0.0")]
2623 impl AsRef<Path> for String {
2624 fn as_ref(&self) -> &Path {
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 impl AsRef<Path> for PathBuf {
2631 fn as_ref(&self) -> &Path {
2636 #[stable(feature = "path_into_iter", since = "1.6.0")]
2637 impl<'a> IntoIterator for &'a PathBuf {
2638 type Item = &'a OsStr;
2639 type IntoIter = Iter<'a>;
2640 fn into_iter(self) -> Iter<'a> { self.iter() }
2643 #[stable(feature = "path_into_iter", since = "1.6.0")]
2644 impl<'a> IntoIterator for &'a Path {
2645 type Item = &'a OsStr;
2646 type IntoIter = Iter<'a>;
2647 fn into_iter(self) -> Iter<'a> { self.iter() }
2650 macro_rules! impl_cmp {
2651 ($lhs:ty, $rhs: ty) => {
2652 #[stable(feature = "partialeq_path", since = "1.6.0")]
2653 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2655 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2658 #[stable(feature = "partialeq_path", since = "1.6.0")]
2659 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2661 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2664 #[stable(feature = "cmp_path", since = "1.8.0")]
2665 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2667 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2668 <Path as PartialOrd>::partial_cmp(self, other)
2672 #[stable(feature = "cmp_path", since = "1.8.0")]
2673 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2675 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2676 <Path as PartialOrd>::partial_cmp(self, other)
2682 impl_cmp!(PathBuf, Path);
2683 impl_cmp!(PathBuf, &'a Path);
2684 impl_cmp!(Cow<'a, Path>, Path);
2685 impl_cmp!(Cow<'a, Path>, &'b Path);
2686 impl_cmp!(Cow<'a, Path>, PathBuf);
2688 macro_rules! impl_cmp_os_str {
2689 ($lhs:ty, $rhs: ty) => {
2690 #[stable(feature = "cmp_path", since = "1.8.0")]
2691 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2693 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2696 #[stable(feature = "cmp_path", since = "1.8.0")]
2697 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2699 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2702 #[stable(feature = "cmp_path", since = "1.8.0")]
2703 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2705 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2706 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2710 #[stable(feature = "cmp_path", since = "1.8.0")]
2711 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2713 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2714 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2720 impl_cmp_os_str!(PathBuf, OsStr);
2721 impl_cmp_os_str!(PathBuf, &'a OsStr);
2722 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2723 impl_cmp_os_str!(PathBuf, OsString);
2724 impl_cmp_os_str!(Path, OsStr);
2725 impl_cmp_os_str!(Path, &'a OsStr);
2726 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2727 impl_cmp_os_str!(Path, OsString);
2728 impl_cmp_os_str!(&'a Path, OsStr);
2729 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2730 impl_cmp_os_str!(&'a Path, OsString);
2731 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2732 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2733 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2735 #[stable(since = "1.7.0", feature = "strip_prefix")]
2736 impl fmt::Display for StripPrefixError {
2737 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2738 self.description().fmt(f)
2742 #[stable(since = "1.7.0", feature = "strip_prefix")]
2743 impl Error for StripPrefixError {
2744 fn description(&self) -> &str { "prefix not found" }
2755 ($path:expr, iter: $iter:expr) => (
2757 let path = Path::new($path);
2759 // Forward iteration
2760 let comps = path.iter()
2761 .map(|p| p.to_string_lossy().into_owned())
2762 .collect::<Vec<String>>();
2763 let exp: &[&str] = &$iter;
2764 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2765 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2768 // Reverse iteration
2769 let comps = Path::new($path).iter().rev()
2770 .map(|p| p.to_string_lossy().into_owned())
2771 .collect::<Vec<String>>();
2772 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2773 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2778 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2780 let path = Path::new($path);
2782 let act_root = path.has_root();
2783 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2784 $has_root, act_root);
2786 let act_abs = path.is_absolute();
2787 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2788 $is_absolute, act_abs);
2792 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2794 let path = Path::new($path);
2796 let parent = path.parent().map(|p| p.to_str().unwrap());
2797 let exp_parent: Option<&str> = $parent;
2798 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2799 exp_parent, parent);
2801 let file = path.file_name().map(|p| p.to_str().unwrap());
2802 let exp_file: Option<&str> = $file;
2803 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2808 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2810 let path = Path::new($path);
2812 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2813 let exp_stem: Option<&str> = $file_stem;
2814 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2817 let ext = path.extension().map(|p| p.to_str().unwrap());
2818 let exp_ext: Option<&str> = $extension;
2819 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2824 ($path:expr, iter: $iter:expr,
2825 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2826 parent: $parent:expr, file_name: $file:expr,
2827 file_stem: $file_stem:expr, extension: $extension:expr) => (
2829 t!($path, iter: $iter);
2830 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2831 t!($path, parent: $parent, file_name: $file);
2832 t!($path, file_stem: $file_stem, extension: $extension);
2841 let static_path = Path::new("/home/foo");
2842 let static_cow_path: Cow<'static, Path> = static_path.into();
2843 let pathbuf = PathBuf::from("/home/foo");
2846 let path: &Path = &pathbuf;
2847 let borrowed_cow_path: Cow<Path> = path.into();
2849 assert_eq!(static_cow_path, borrowed_cow_path);
2852 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2854 assert_eq!(static_cow_path, owned_cow_path);
2859 pub fn test_decompositions_unix() {
2875 file_name: Some("foo"),
2876 file_stem: Some("foo"),
2895 file_name: Some("foo"),
2896 file_stem: Some("foo"),
2905 file_name: Some("foo"),
2906 file_stem: Some("foo"),
2915 file_name: Some("foo"),
2916 file_stem: Some("foo"),
2921 iter: ["foo", "bar"],
2924 parent: Some("foo"),
2925 file_name: Some("bar"),
2926 file_stem: Some("bar"),
2931 iter: ["/", "foo", "bar"],
2934 parent: Some("/foo"),
2935 file_name: Some("bar"),
2936 file_stem: Some("bar"),
2945 file_name: Some("foo"),
2946 file_stem: Some("foo"),
2951 iter: ["/", "foo", "bar"],
2954 parent: Some("///foo"),
2955 file_name: Some("bar"),
2956 file_stem: Some("bar"),
2995 file_name: Some("foo"),
2996 file_stem: Some("foo"),
3001 iter: ["foo", ".."],
3004 parent: Some("foo"),
3015 file_name: Some("foo"),
3016 file_stem: Some("foo"),
3021 iter: ["foo", "bar"],
3024 parent: Some("foo"),
3025 file_name: Some("bar"),
3026 file_stem: Some("bar"),
3031 iter: ["foo", ".."],
3034 parent: Some("foo"),
3041 iter: ["foo", "..", "bar"],
3044 parent: Some("foo/.."),
3045 file_name: Some("bar"),
3046 file_stem: Some("bar"),
3055 file_name: Some("a"),
3056 file_stem: Some("a"),
3085 file_name: Some("b"),
3086 file_stem: Some("b"),
3095 file_name: Some("b"),
3096 file_stem: Some("b"),
3105 file_name: Some("b"),
3106 file_stem: Some("b"),
3111 iter: ["a", "b", "c"],
3114 parent: Some("a/b"),
3115 file_name: Some("c"),
3116 file_stem: Some("c"),
3125 file_name: Some(".foo"),
3126 file_stem: Some(".foo"),
3133 pub fn test_decompositions_windows() {
3149 file_name: Some("foo"),
3150 file_stem: Some("foo"),
3205 iter: ["\\", "foo"],
3209 file_name: Some("foo"),
3210 file_stem: Some("foo"),
3219 file_name: Some("foo"),
3220 file_stem: Some("foo"),
3225 iter: ["\\", "foo"],
3229 file_name: Some("foo"),
3230 file_stem: Some("foo"),
3235 iter: ["foo", "bar"],
3238 parent: Some("foo"),
3239 file_name: Some("bar"),
3240 file_stem: Some("bar"),
3245 iter: ["\\", "foo", "bar"],
3248 parent: Some("/foo"),
3249 file_name: Some("bar"),
3250 file_stem: Some("bar"),
3255 iter: ["\\", "foo"],
3259 file_name: Some("foo"),
3260 file_stem: Some("foo"),
3265 iter: ["\\", "foo", "bar"],
3268 parent: Some("///foo"),
3269 file_name: Some("bar"),
3270 file_stem: Some("bar"),
3309 file_name: Some("foo"),
3310 file_stem: Some("foo"),
3315 iter: ["foo", ".."],
3318 parent: Some("foo"),
3329 file_name: Some("foo"),
3330 file_stem: Some("foo"),
3335 iter: ["foo", "bar"],
3338 parent: Some("foo"),
3339 file_name: Some("bar"),
3340 file_stem: Some("bar"),
3345 iter: ["foo", ".."],
3348 parent: Some("foo"),
3355 iter: ["foo", "..", "bar"],
3358 parent: Some("foo/.."),
3359 file_name: Some("bar"),
3360 file_stem: Some("bar"),
3369 file_name: Some("a"),
3370 file_stem: Some("a"),
3399 file_name: Some("b"),
3400 file_stem: Some("b"),
3409 file_name: Some("b"),
3410 file_stem: Some("b"),
3419 file_name: Some("b"),
3420 file_stem: Some("b"),
3425 iter: ["a", "b", "c"],
3428 parent: Some("a/b"),
3429 file_name: Some("c"),
3430 file_stem: Some("c"),
3434 iter: ["a", "b", "c"],
3437 parent: Some("a\\b"),
3438 file_name: Some("c"),
3439 file_stem: Some("c"),
3448 file_name: Some("a"),
3449 file_stem: Some("a"),
3454 iter: ["c:", "\\", "foo.txt"],
3457 parent: Some("c:\\"),
3458 file_name: Some("foo.txt"),
3459 file_stem: Some("foo"),
3460 extension: Some("txt")
3463 t!("\\\\server\\share\\foo.txt",
3464 iter: ["\\\\server\\share", "\\", "foo.txt"],
3467 parent: Some("\\\\server\\share\\"),
3468 file_name: Some("foo.txt"),
3469 file_stem: Some("foo"),
3470 extension: Some("txt")
3473 t!("\\\\server\\share",
3474 iter: ["\\\\server\\share", "\\"],
3484 iter: ["\\", "server"],
3488 file_name: Some("server"),
3489 file_stem: Some("server"),
3493 t!("\\\\?\\bar\\foo.txt",
3494 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3497 parent: Some("\\\\?\\bar\\"),
3498 file_name: Some("foo.txt"),
3499 file_stem: Some("foo"),
3500 extension: Some("txt")
3504 iter: ["\\\\?\\bar"],
3523 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3524 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3527 parent: Some("\\\\?\\UNC\\server\\share\\"),
3528 file_name: Some("foo.txt"),
3529 file_stem: Some("foo"),
3530 extension: Some("txt")
3533 t!("\\\\?\\UNC\\server",
3534 iter: ["\\\\?\\UNC\\server"],
3544 iter: ["\\\\?\\UNC\\"],
3553 t!("\\\\?\\C:\\foo.txt",
3554 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3557 parent: Some("\\\\?\\C:\\"),
3558 file_name: Some("foo.txt"),
3559 file_stem: Some("foo"),
3560 extension: Some("txt")
3565 iter: ["\\\\?\\C:", "\\"],
3576 iter: ["\\\\?\\C:"],
3586 t!("\\\\?\\foo/bar",
3587 iter: ["\\\\?\\foo/bar"],
3598 iter: ["\\\\?\\C:/foo"],
3608 t!("\\\\.\\foo\\bar",
3609 iter: ["\\\\.\\foo", "\\", "bar"],
3612 parent: Some("\\\\.\\foo\\"),
3613 file_name: Some("bar"),
3614 file_stem: Some("bar"),
3620 iter: ["\\\\.\\foo", "\\"],
3630 t!("\\\\.\\foo/bar",
3631 iter: ["\\\\.\\foo/bar", "\\"],
3641 t!("\\\\.\\foo\\bar/baz",
3642 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3645 parent: Some("\\\\.\\foo\\bar"),
3646 file_name: Some("baz"),
3647 file_stem: Some("baz"),
3653 iter: ["\\\\.\\", "\\"],
3663 iter: ["\\\\?\\a", "\\", "b"],
3666 parent: Some("\\\\?\\a\\"),
3667 file_name: Some("b"),
3668 file_stem: Some("b"),
3674 pub fn test_stem_ext() {
3676 file_stem: Some("foo"),
3681 file_stem: Some("foo"),
3686 file_stem: Some(".foo"),
3691 file_stem: Some("foo"),
3692 extension: Some("txt")
3696 file_stem: Some("foo.bar"),
3697 extension: Some("txt")
3701 file_stem: Some("foo.bar"),
3722 pub fn test_push() {
3724 ($path:expr, $push:expr, $expected:expr) => ( {
3725 let mut actual = PathBuf::from($path);
3727 assert!(actual.to_str() == Some($expected),
3728 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3729 $push, $path, $expected, actual.to_str().unwrap());
3734 tp!("", "foo", "foo");
3735 tp!("foo", "bar", "foo/bar");
3736 tp!("foo/", "bar", "foo/bar");
3737 tp!("foo//", "bar", "foo//bar");
3738 tp!("foo/.", "bar", "foo/./bar");
3739 tp!("foo./.", "bar", "foo././bar");
3740 tp!("foo", "", "foo/");
3741 tp!("foo", ".", "foo/.");
3742 tp!("foo", "..", "foo/..");
3743 tp!("foo", "/", "/");
3744 tp!("/foo/bar", "/", "/");
3745 tp!("/foo/bar", "/baz", "/baz");
3746 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3748 tp!("", "foo", "foo");
3749 tp!("foo", "bar", r"foo\bar");
3750 tp!("foo/", "bar", r"foo/bar");
3751 tp!(r"foo\", "bar", r"foo\bar");
3752 tp!("foo//", "bar", r"foo//bar");
3753 tp!(r"foo\\", "bar", r"foo\\bar");
3754 tp!("foo/.", "bar", r"foo/.\bar");
3755 tp!("foo./.", "bar", r"foo./.\bar");
3756 tp!(r"foo\.", "bar", r"foo\.\bar");
3757 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3758 tp!("foo", "", "foo\\");
3759 tp!("foo", ".", r"foo\.");
3760 tp!("foo", "..", r"foo\..");
3761 tp!("foo", "/", "/");
3762 tp!("foo", r"\", r"\");
3763 tp!("/foo/bar", "/", "/");
3764 tp!(r"\foo\bar", r"\", r"\");
3765 tp!("/foo/bar", "/baz", "/baz");
3766 tp!("/foo/bar", r"\baz", r"\baz");
3767 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3768 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3770 tp!("c:\\", "windows", "c:\\windows");
3771 tp!("c:", "windows", "c:windows");
3773 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3774 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3775 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3776 tp!("a\\b", "\\c\\d", "\\c\\d");
3777 tp!("a\\b", ".", "a\\b\\.");
3778 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3779 tp!("a\\b", "C:a.txt", "C:a.txt");
3780 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3781 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3782 tp!("C:\\a\\b\\c", "C:d", "C:d");
3783 tp!("C:a\\b\\c", "C:d", "C:d");
3784 tp!("C:", r"a\b\c", r"C:a\b\c");
3785 tp!("C:", r"..\a", r"C:..\a");
3786 tp!("\\\\server\\share\\foo",
3788 "\\\\server\\share\\foo\\bar");
3789 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3790 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3791 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3792 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3793 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3794 tp!("\\\\?\\UNC\\server\\share\\foo",
3796 "\\\\?\\UNC\\server\\share\\foo\\bar");
3797 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3798 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3800 // Note: modified from old path API
3801 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3804 "\\\\?\\UNC\\server\\share",
3805 "\\\\?\\UNC\\server\\share");
3806 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3807 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3808 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3809 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3811 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3818 ($path:expr, $expected:expr, $output:expr) => ( {
3819 let mut actual = PathBuf::from($path);
3820 let output = actual.pop();
3821 assert!(actual.to_str() == Some($expected) && output == $output,
3822 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3823 $path, $expected, $output,
3824 actual.to_str().unwrap(), output);
3829 tp!("/", "/", false);
3830 tp!("foo", "", true);
3832 tp!("/foo", "/", true);
3833 tp!("/foo/bar", "/foo", true);
3834 tp!("foo/bar", "foo", true);
3835 tp!("foo/.", "", true);
3836 tp!("foo//bar", "foo", true);
3839 tp!("a\\b\\c", "a\\b", true);
3840 tp!("\\a", "\\", true);
3841 tp!("\\", "\\", false);
3843 tp!("C:\\a\\b", "C:\\a", true);
3844 tp!("C:\\a", "C:\\", true);
3845 tp!("C:\\", "C:\\", false);
3846 tp!("C:a\\b", "C:a", true);
3847 tp!("C:a", "C:", true);
3848 tp!("C:", "C:", false);
3849 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3850 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3851 tp!("\\\\server\\share", "\\\\server\\share", false);
3852 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3853 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3854 tp!("\\\\?\\a", "\\\\?\\a", false);
3855 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3856 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3857 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3858 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3859 "\\\\?\\UNC\\server\\share\\a",
3861 tp!("\\\\?\\UNC\\server\\share\\a",
3862 "\\\\?\\UNC\\server\\share\\",
3864 tp!("\\\\?\\UNC\\server\\share",
3865 "\\\\?\\UNC\\server\\share",
3867 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3868 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3869 tp!("\\\\.\\a", "\\\\.\\a", false);
3871 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3876 pub fn test_set_file_name() {
3878 ($path:expr, $file:expr, $expected:expr) => ( {
3879 let mut p = PathBuf::from($path);
3880 p.set_file_name($file);
3881 assert!(p.to_str() == Some($expected),
3882 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3883 $path, $file, $expected,
3884 p.to_str().unwrap());
3888 tfn!("foo", "foo", "foo");
3889 tfn!("foo", "bar", "bar");
3890 tfn!("foo", "", "");
3891 tfn!("", "foo", "foo");
3893 tfn!(".", "foo", "./foo");
3894 tfn!("foo/", "bar", "bar");
3895 tfn!("foo/.", "bar", "bar");
3896 tfn!("..", "foo", "../foo");
3897 tfn!("foo/..", "bar", "foo/../bar");
3898 tfn!("/", "foo", "/foo");
3900 tfn!(".", "foo", r".\foo");
3901 tfn!(r"foo\", "bar", r"bar");
3902 tfn!(r"foo\.", "bar", r"bar");
3903 tfn!("..", "foo", r"..\foo");
3904 tfn!(r"foo\..", "bar", r"foo\..\bar");
3905 tfn!(r"\", "foo", r"\foo");
3910 pub fn test_set_extension() {
3912 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3913 let mut p = PathBuf::from($path);
3914 let output = p.set_extension($ext);
3915 assert!(p.to_str() == Some($expected) && output == $output,
3916 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3917 $path, $ext, $expected, $output,
3918 p.to_str().unwrap(), output);
3922 tfe!("foo", "txt", "foo.txt", true);
3923 tfe!("foo.bar", "txt", "foo.txt", true);
3924 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3925 tfe!(".test", "txt", ".test.txt", true);
3926 tfe!("foo.txt", "", "foo", true);
3927 tfe!("foo", "", "foo", true);
3928 tfe!("", "foo", "", false);
3929 tfe!(".", "foo", ".", false);
3930 tfe!("foo/", "bar", "foo.bar", true);
3931 tfe!("foo/.", "bar", "foo.bar", true);
3932 tfe!("..", "foo", "..", false);
3933 tfe!("foo/..", "bar", "foo/..", false);
3934 tfe!("/", "foo", "/", false);
3938 fn test_eq_receivers() {
3941 let borrowed: &Path = Path::new("foo/bar");
3942 let mut owned: PathBuf = PathBuf::new();
3945 let borrowed_cow: Cow<Path> = borrowed.into();
3946 let owned_cow: Cow<Path> = owned.clone().into();
3949 ($($current:expr),+) => {
3951 assert_eq!($current, borrowed);
3952 assert_eq!($current, owned);
3953 assert_eq!($current, borrowed_cow);
3954 assert_eq!($current, owned_cow);
3959 t!(borrowed, owned, borrowed_cow, owned_cow);
3963 pub fn test_compare() {
3964 use hash::{Hash, Hasher};
3965 use collections::hash_map::DefaultHasher;
3967 fn hash<T: Hash>(t: T) -> u64 {
3968 let mut s = DefaultHasher::new();
3974 ($path1:expr, $path2:expr, eq: $eq:expr,
3975 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3976 relative_from: $relative_from:expr) => ({
3977 let path1 = Path::new($path1);
3978 let path2 = Path::new($path2);
3980 let eq = path1 == path2;
3981 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3982 $path1, $path2, $eq, eq);
3983 assert!($eq == (hash(path1) == hash(path2)),
3984 "{:?} == {:?}, expected {:?}, got {} and {}",
3985 $path1, $path2, $eq, hash(path1), hash(path2));
3987 let starts_with = path1.starts_with(path2);
3988 assert!(starts_with == $starts_with,
3989 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3990 $starts_with, starts_with);
3992 let ends_with = path1.ends_with(path2);
3993 assert!(ends_with == $ends_with,
3994 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3995 $ends_with, ends_with);
3997 let relative_from = path1.strip_prefix(path2)
3998 .map(|p| p.to_str().unwrap())
4000 let exp: Option<&str> = $relative_from;
4001 assert!(relative_from == exp,
4002 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
4003 $path1, $path2, exp, relative_from);
4011 relative_from: Some("")
4018 relative_from: Some("foo")
4032 relative_from: Some("")
4039 relative_from: Some("")
4042 tc!("foo/bar", "foo",
4046 relative_from: Some("bar")
4049 tc!("foo/bar/baz", "foo/bar",
4053 relative_from: Some("baz")
4056 tc!("foo/bar", "foo/bar/baz",
4063 tc!("./foo/bar/", ".",
4067 relative_from: Some("foo/bar")
4071 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
4072 r"c:\src\rust\cargo-test\test",
4076 relative_from: Some("Cargo.toml")
4079 tc!(r"c:\foo", r"C:\foo",
4083 relative_from: Some("")
4089 fn test_components_debug() {
4090 let path = Path::new("/tmp");
4092 let mut components = path.components();
4094 let expected = "Components([RootDir, Normal(\"tmp\")])";
4095 let actual = format!("{:?}", components);
4096 assert_eq!(expected, actual);
4098 let _ = components.next().unwrap();
4099 let expected = "Components([Normal(\"tmp\")])";
4100 let actual = format!("{:?}", components);
4101 assert_eq!(expected, actual);
4103 let _ = components.next().unwrap();
4104 let expected = "Components([])";
4105 let actual = format!("{:?}", components);
4106 assert_eq!(expected, actual);
4111 fn test_iter_debug() {
4112 let path = Path::new("/tmp");
4114 let mut iter = path.iter();
4116 let expected = "Iter([\"/\", \"tmp\"])";
4117 let actual = format!("{:?}", iter);
4118 assert_eq!(expected, actual);
4120 let _ = iter.next().unwrap();
4121 let expected = "Iter([\"tmp\"])";
4122 let actual = format!("{:?}", iter);
4123 assert_eq!(expected, actual);
4125 let _ = iter.next().unwrap();
4126 let expected = "Iter([])";
4127 let actual = format!("{:?}", iter);
4128 assert_eq!(expected, actual);
4133 let orig: &str = "some/sort/of/path";
4134 let path = Path::new(orig);
4135 let boxed: Box<Path> = Box::from(path);
4136 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4137 assert_eq!(path, &*boxed);
4138 assert_eq!(&*boxed, &*path_buf);
4139 assert_eq!(&*path_buf, path);
4143 fn test_clone_into() {
4144 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4145 let path = Path::new("short");
4146 path.clone_into(&mut path_buf);
4147 assert_eq!(path, path_buf);
4148 assert!(path_buf.into_os_string().capacity() >= 15);
4152 fn display_format_flags() {
4153 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4154 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4159 let orig = "hello/world";
4160 let path = Path::new(orig);
4161 let rc: Rc<Path> = Rc::from(path);
4162 let arc: Arc<Path> = Arc::from(path);
4164 assert_eq!(&*rc, path);
4165 assert_eq!(&*arc, path);
4167 let rc2: Rc<Path> = Rc::from(path.to_owned());
4168 let arc2: Arc<Path> = Arc::from(path.to_owned());
4170 assert_eq!(&*rc2, path);
4171 assert_eq!(&*arc2, path);