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`] (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 //! let mut path = PathBuf::from("c:\\");
55 //! path.push("windows");
56 //! path.push("system32");
57 //! path.set_extension("dll");
60 //! [`Component`]: ../../std/path/enum.Component.html
61 //! [`components`]: ../../std/path/struct.Path.html#method.components
62 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
63 //! [`Path`]: ../../std/path/struct.Path.html
64 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
65 //! [`String`]: ../../std/string/struct.String.html
66 //! [`str`]: ../../std/primitive.str.html
67 //! [`OsString`]: ../../std/ffi/struct.OsString.html
68 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
70 #![stable(feature = "rust1", since = "1.0.0")]
73 use borrow::{Borrow, Cow};
78 use hash::{Hash, Hasher};
80 use iter::{self, FusedIterator};
82 use ops::{self, Deref};
84 use ffi::{OsStr, OsString};
86 use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
88 ////////////////////////////////////////////////////////////////////////////////
90 ////////////////////////////////////////////////////////////////////////////////
92 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
93 // taking advantage of the fact that OsStr always encodes ASCII characters
94 // as-is. Eventually, this transmutation should be replaced by direct uses of
95 // OsStr APIs for parsing, but it will take a while for those to become
98 ////////////////////////////////////////////////////////////////////////////////
100 ////////////////////////////////////////////////////////////////////////////////
102 /// Windows path prefixes, e.g. `C:` or `\\server\share`.
104 /// Windows uses a variety of path prefix styles, including references to drive
105 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
106 /// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
107 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
108 /// no normalization is performed.
113 /// use std::path::{Component, Path, Prefix};
114 /// use std::path::Prefix::*;
115 /// use std::ffi::OsStr;
117 /// fn get_path_prefix(s: &str) -> Prefix {
118 /// let path = Path::new(s);
119 /// match path.components().next().unwrap() {
120 /// Component::Prefix(prefix_component) => prefix_component.kind(),
125 /// # if cfg!(windows) {
126 /// assert_eq!(Verbatim(OsStr::new("pictures")),
127 /// get_path_prefix(r"\\?\pictures\kittens"));
128 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
129 /// get_path_prefix(r"\\?\UNC\server\share"));
130 /// assert_eq!(VerbatimDisk('C' as u8), get_path_prefix(r"\\?\c:\"));
131 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
132 /// get_path_prefix(r"\\.\BrainInterface"));
133 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
134 /// get_path_prefix(r"\\server\share"));
135 /// assert_eq!(Disk('C' as u8), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
138 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
139 #[stable(feature = "rust1", since = "1.0.0")]
140 pub enum Prefix<'a> {
141 /// Verbatim prefix, e.g. `\\?\cat_pics`.
143 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
145 #[stable(feature = "rust1", since = "1.0.0")]
146 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
148 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
149 /// e.g. `\\?\UNC\server\share`.
151 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
152 /// server's hostname and a share name.
153 #[stable(feature = "rust1", since = "1.0.0")]
155 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
156 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
159 /// Verbatim disk prefix, e.g. `\\?\C:\`.
161 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
162 /// drive letter and `:\`.
163 #[stable(feature = "rust1", since = "1.0.0")]
164 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
166 /// Device namespace prefix, e.g. `\\.\COM42`.
168 /// Device namespace prefixes consist of `\\.\` immediately followed by the
170 #[stable(feature = "rust1", since = "1.0.0")]
171 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
173 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
174 /// `\\server\share`.
176 /// UNC prefixes consist of the server's hostname and a share name.
177 #[stable(feature = "rust1", since = "1.0.0")]
179 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
180 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
183 /// Prefix `C:` for the given disk drive.
184 #[stable(feature = "rust1", since = "1.0.0")]
185 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
188 impl<'a> Prefix<'a> {
190 fn len(&self) -> usize {
192 fn os_str_len(s: &OsStr) -> usize {
193 os_str_as_u8_slice(s).len()
196 Verbatim(x) => 4 + os_str_len(x),
197 VerbatimUNC(x, y) => {
199 if os_str_len(y) > 0 {
205 VerbatimDisk(_) => 6,
208 if os_str_len(y) > 0 {
214 DeviceNS(x) => 4 + os_str_len(x),
220 /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
225 /// use std::path::Prefix::*;
226 /// use std::ffi::OsStr;
228 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
229 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
230 /// assert!(VerbatimDisk('C' as u8).is_verbatim());
231 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
232 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
233 /// assert!(!Disk('C' as u8).is_verbatim());
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn is_verbatim(&self) -> bool {
240 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
246 fn is_drive(&self) -> bool {
248 Prefix::Disk(_) => true,
254 fn has_implicit_root(&self) -> bool {
259 ////////////////////////////////////////////////////////////////////////////////
260 // Exposed parsing helpers
261 ////////////////////////////////////////////////////////////////////////////////
263 /// Determines whether the character is one of the permitted path
264 /// separators for the current platform.
271 /// assert!(path::is_separator('/'));
272 /// assert!(!path::is_separator('❤'));
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn is_separator(c: char) -> bool {
276 c.is_ascii() && is_sep_byte(c as u8)
279 /// The primary separator of path components for the current platform.
281 /// For example, `/` on Unix and `\` on Windows.
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
285 ////////////////////////////////////////////////////////////////////////////////
287 ////////////////////////////////////////////////////////////////////////////////
289 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
290 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
291 // `iter` after having exhausted `prefix`.
292 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
293 where I: Iterator<Item = A> + Clone,
294 J: Iterator<Item = A>,
298 let mut iter_next = iter.clone();
299 match (iter_next.next(), prefix.next()) {
300 (Some(ref x), Some(ref y)) if x == y => (),
301 (Some(_), Some(_)) => return None,
302 (Some(_), None) => return Some(iter),
303 (None, None) => return Some(iter),
304 (None, Some(_)) => return None,
310 // See note at the top of this module to understand why these are used:
311 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
312 unsafe { mem::transmute(s) }
314 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
318 ////////////////////////////////////////////////////////////////////////////////
319 // Cross-platform, iterator-independent parsing
320 ////////////////////////////////////////////////////////////////////////////////
322 /// Says whether the first byte after the prefix is a separator.
323 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
324 let path = if let Some(p) = prefix {
329 !path.is_empty() && is_sep_byte(path[0])
332 // basic workhorse for splitting stem and extension
333 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
335 if os_str_as_u8_slice(file) == b".." {
336 return (Some(file), None);
339 // The unsafety here stems from converting between &OsStr and &[u8]
340 // and back. This is safe to do because (1) we only look at ASCII
341 // contents of the encoding and (2) new &OsStr values are produced
342 // only from ASCII-bounded slices of existing &OsStr values.
344 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
345 let after = iter.next();
346 let before = iter.next();
347 if before == Some(b"") {
350 (before.map(|s| u8_slice_as_os_str(s)),
351 after.map(|s| u8_slice_as_os_str(s)))
356 ////////////////////////////////////////////////////////////////////////////////
357 // The core iterators
358 ////////////////////////////////////////////////////////////////////////////////
360 /// Component parsing works by a double-ended state machine; the cursors at the
361 /// front and back of the path each keep track of what parts of the path have
362 /// been consumed so far.
364 /// Going front to back, a path is made up of a prefix, a starting
365 /// directory component, and a body (of normal components)
366 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
369 StartDir = 1, // / or . or nothing
370 Body = 2, // foo/bar/baz
374 /// A structure wrapping a Windows path prefix as well as its unparsed string
377 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
378 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
379 /// returned by [`as_os_str`].
381 /// Instances of this `struct` can be obtained by matching against the
382 /// [`Prefix` variant] on [`Component`].
384 /// Does not occur on Unix.
389 /// # if cfg!(windows) {
390 /// use std::path::{Component, Path, Prefix};
391 /// use std::ffi::OsStr;
393 /// let path = Path::new(r"c:\you\later\");
394 /// match path.components().next().unwrap() {
395 /// Component::Prefix(prefix_component) => {
396 /// assert_eq!(Prefix::Disk('C' as u8), prefix_component.kind());
397 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
399 /// _ => unreachable!(),
404 /// [`as_os_str`]: #method.as_os_str
405 /// [`Component`]: enum.Component.html
406 /// [`kind`]: #method.kind
407 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
408 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
409 /// [`Prefix`]: enum.Prefix.html
410 #[stable(feature = "rust1", since = "1.0.0")]
411 #[derive(Copy, Clone, Eq, Debug)]
412 pub struct PrefixComponent<'a> {
413 /// The prefix as an unparsed `OsStr` slice.
416 /// The parsed prefix data.
420 impl<'a> PrefixComponent<'a> {
421 /// Returns the parsed prefix data.
423 /// See [`Prefix`]'s documentation for more information on the different
424 /// kinds of prefixes.
426 /// [`Prefix`]: enum.Prefix.html
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn kind(&self) -> Prefix<'a> {
432 /// Returns the raw [`OsStr`] slice for this prefix.
434 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn as_os_str(&self) -> &'a OsStr {
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
443 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
444 cmp::PartialEq::eq(&self.parsed, &other.parsed)
448 #[stable(feature = "rust1", since = "1.0.0")]
449 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
450 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
451 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl<'a> cmp::Ord for PrefixComponent<'a> {
457 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
458 cmp::Ord::cmp(&self.parsed, &other.parsed)
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl<'a> Hash for PrefixComponent<'a> {
464 fn hash<H: Hasher>(&self, h: &mut H) {
469 /// A single component of a path.
471 /// A `Component` roughtly corresponds to a substring between path separators
474 /// This `enum` is created by iterating over [`Components`], which in turn is
475 /// created by the [`components`][`Path::components`] method on [`Path`].
480 /// use std::path::{Component, Path};
482 /// let path = Path::new("/tmp/foo/bar.txt");
483 /// let components = path.components().collect::<Vec<_>>();
484 /// assert_eq!(&components, &[
485 /// Component::RootDir,
486 /// Component::Normal("tmp".as_ref()),
487 /// Component::Normal("foo".as_ref()),
488 /// Component::Normal("bar.txt".as_ref()),
492 /// [`Components`]: struct.Components.html
493 /// [`Path`]: struct.Path.html
494 /// [`Path::components`]: struct.Path.html#method.components
495 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub enum Component<'a> {
498 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
500 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
503 /// Does not occur on Unix.
505 /// [`Prefix`]: enum.Prefix.html
506 #[stable(feature = "rust1", since = "1.0.0")]
508 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
511 /// The root directory component, appears after any prefix and before anything else.
513 /// It represents a separator that designates that a path starts from root.
514 #[stable(feature = "rust1", since = "1.0.0")]
517 /// A reference to the current directory, i.e. `.`.
518 #[stable(feature = "rust1", since = "1.0.0")]
521 /// A reference to the parent directory, i.e. `..`.
522 #[stable(feature = "rust1", since = "1.0.0")]
525 /// A normal component, e.g. `a` and `b` in `a/b`.
527 /// This variant is the most common one, it represents references to files
529 #[stable(feature = "rust1", since = "1.0.0")]
530 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
533 impl<'a> Component<'a> {
534 /// Extracts the underlying [`OsStr`] slice.
539 /// use std::path::Path;
541 /// let path = Path::new("./tmp/foo/bar.txt");
542 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
543 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
546 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
547 #[stable(feature = "rust1", since = "1.0.0")]
548 pub fn as_os_str(self) -> &'a OsStr {
550 Component::Prefix(p) => p.as_os_str(),
551 Component::RootDir => OsStr::new(MAIN_SEP_STR),
552 Component::CurDir => OsStr::new("."),
553 Component::ParentDir => OsStr::new(".."),
554 Component::Normal(path) => path,
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl<'a> AsRef<OsStr> for Component<'a> {
561 fn as_ref(&self) -> &OsStr {
566 /// An interator over the [`Component`]s of a [`Path`].
568 /// This `struct` is created by the [`components`] method on [`Path`].
569 /// See its documentation for more.
574 /// use std::path::Path;
576 /// let path = Path::new("/tmp/foo/bar.txt");
578 /// for component in path.components() {
579 /// println!("{:?}", component);
583 /// [`Component`]: enum.Component.html
584 /// [`components`]: struct.Path.html#method.components
585 /// [`Path`]: struct.Path.html
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub struct Components<'a> {
589 // The path left to parse components from
592 // The prefix as it was originally parsed, if any
593 prefix: Option<Prefix<'a>>,
595 // true if path *physically* has a root separator; for most Windows
596 // prefixes, it may have a "logical" rootseparator for the purposes of
597 // normalization, e.g. \\server\share == \\server\share\.
598 has_physical_root: bool,
600 // The iterator is double-ended, and these two states keep track of what has
601 // been produced from either end
606 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
608 /// This `struct` is created by the [`iter`] method on [`Path`].
609 /// See its documentation for more.
611 /// [`Component`]: enum.Component.html
612 /// [`iter`]: struct.Path.html#method.iter
613 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
614 /// [`Path`]: struct.Path.html
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub struct Iter<'a> {
618 inner: Components<'a>,
621 #[stable(feature = "path_components_debug", since = "1.13.0")]
622 impl<'a> fmt::Debug for Components<'a> {
623 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
624 struct DebugHelper<'a>(&'a Path);
626 impl<'a> fmt::Debug for DebugHelper<'a> {
627 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
629 .entries(self.0.components())
634 f.debug_tuple("Components")
635 .field(&DebugHelper(self.as_path()))
640 impl<'a> Components<'a> {
641 // how long is the prefix, if any?
643 fn prefix_len(&self) -> usize {
644 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
648 fn prefix_verbatim(&self) -> bool {
649 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
652 /// how much of the prefix is left from the point of view of iteration?
654 fn prefix_remaining(&self) -> usize {
655 if self.front == State::Prefix {
662 // Given the iteration so far, how much of the pre-State::Body path is left?
664 fn len_before_body(&self) -> usize {
665 let root = if self.front <= State::StartDir && self.has_physical_root {
670 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
675 self.prefix_remaining() + root + cur_dir
678 // is the iteration complete?
680 fn finished(&self) -> bool {
681 self.front == State::Done || self.back == State::Done || self.front > self.back
685 fn is_sep_byte(&self, b: u8) -> bool {
686 if self.prefix_verbatim() {
693 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
698 /// use std::path::Path;
700 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
701 /// components.next();
702 /// components.next();
704 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn as_path(&self) -> &'a Path {
708 let mut comps = self.clone();
709 if comps.front == State::Body {
712 if comps.back == State::Body {
715 unsafe { Path::from_u8_slice(comps.path) }
718 /// Is the *original* path rooted?
719 fn has_root(&self) -> bool {
720 if self.has_physical_root {
723 if let Some(p) = self.prefix {
724 if p.has_implicit_root() {
731 /// Should the normalized path include a leading . ?
732 fn include_cur_dir(&self) -> bool {
736 let mut iter = self.path[self.prefix_len()..].iter();
737 match (iter.next(), iter.next()) {
738 (Some(&b'.'), None) => true,
739 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
744 // parse a given byte sequence into the corresponding path component
745 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
747 b"." if self.prefix_verbatim() => Some(Component::CurDir),
748 b"." => None, // . components are normalized away, except at
749 // the beginning of a path, which is treated
750 // separately via `include_cur_dir`
751 b".." => Some(Component::ParentDir),
753 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
757 // parse a component from the left, saying how many bytes to consume to
758 // remove the component
759 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
760 debug_assert!(self.front == State::Body);
761 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
762 None => (0, self.path),
763 Some(i) => (1, &self.path[..i]),
765 (comp.len() + extra, self.parse_single_component(comp))
768 // parse a component from the right, saying how many bytes to consume to
769 // remove the component
770 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
771 debug_assert!(self.back == State::Body);
772 let start = self.len_before_body();
773 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
774 None => (0, &self.path[start..]),
775 Some(i) => (1, &self.path[start + i + 1..]),
777 (comp.len() + extra, self.parse_single_component(comp))
780 // trim away repeated separators (i.e. empty components) on the left
781 fn trim_left(&mut self) {
782 while !self.path.is_empty() {
783 let (size, comp) = self.parse_next_component();
787 self.path = &self.path[size..];
792 // trim away repeated separators (i.e. empty components) on the right
793 fn trim_right(&mut self) {
794 while self.path.len() > self.len_before_body() {
795 let (size, comp) = self.parse_next_component_back();
799 self.path = &self.path[..self.path.len() - size];
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<'a> AsRef<Path> for Components<'a> {
807 fn as_ref(&self) -> &Path {
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl<'a> AsRef<OsStr> for Components<'a> {
814 fn as_ref(&self) -> &OsStr {
815 self.as_path().as_os_str()
819 #[stable(feature = "path_iter_debug", since = "1.13.0")]
820 impl<'a> fmt::Debug for Iter<'a> {
821 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
822 struct DebugHelper<'a>(&'a Path);
824 impl<'a> fmt::Debug for DebugHelper<'a> {
825 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
827 .entries(self.0.iter())
832 f.debug_tuple("Iter")
833 .field(&DebugHelper(self.as_path()))
839 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
844 /// use std::path::Path;
846 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
850 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub fn as_path(&self) -> &'a Path {
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl<'a> AsRef<Path> for Iter<'a> {
860 fn as_ref(&self) -> &Path {
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<'a> AsRef<OsStr> for Iter<'a> {
867 fn as_ref(&self) -> &OsStr {
868 self.as_path().as_os_str()
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a> Iterator for Iter<'a> {
874 type Item = &'a OsStr;
876 fn next(&mut self) -> Option<&'a OsStr> {
877 self.inner.next().map(Component::as_os_str)
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl<'a> DoubleEndedIterator for Iter<'a> {
883 fn next_back(&mut self) -> Option<&'a OsStr> {
884 self.inner.next_back().map(Component::as_os_str)
888 #[unstable(feature = "fused", issue = "35602")]
889 impl<'a> FusedIterator for Iter<'a> {}
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<'a> Iterator for Components<'a> {
893 type Item = Component<'a>;
895 fn next(&mut self) -> Option<Component<'a>> {
896 while !self.finished() {
898 State::Prefix if self.prefix_len() > 0 => {
899 self.front = State::StartDir;
900 debug_assert!(self.prefix_len() <= self.path.len());
901 let raw = &self.path[..self.prefix_len()];
902 self.path = &self.path[self.prefix_len()..];
903 return Some(Component::Prefix(PrefixComponent {
904 raw: unsafe { u8_slice_as_os_str(raw) },
905 parsed: self.prefix.unwrap(),
909 self.front = State::StartDir;
912 self.front = State::Body;
913 if self.has_physical_root {
914 debug_assert!(!self.path.is_empty());
915 self.path = &self.path[1..];
916 return Some(Component::RootDir);
917 } else if let Some(p) = self.prefix {
918 if p.has_implicit_root() && !p.is_verbatim() {
919 return Some(Component::RootDir);
921 } else if self.include_cur_dir() {
922 debug_assert!(!self.path.is_empty());
923 self.path = &self.path[1..];
924 return Some(Component::CurDir);
927 State::Body if !self.path.is_empty() => {
928 let (size, comp) = self.parse_next_component();
929 self.path = &self.path[size..];
935 self.front = State::Done;
937 State::Done => unreachable!(),
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl<'a> DoubleEndedIterator for Components<'a> {
946 fn next_back(&mut self) -> Option<Component<'a>> {
947 while !self.finished() {
949 State::Body if self.path.len() > self.len_before_body() => {
950 let (size, comp) = self.parse_next_component_back();
951 self.path = &self.path[..self.path.len() - size];
957 self.back = State::StartDir;
960 self.back = State::Prefix;
961 if self.has_physical_root {
962 self.path = &self.path[..self.path.len() - 1];
963 return Some(Component::RootDir);
964 } else if let Some(p) = self.prefix {
965 if p.has_implicit_root() && !p.is_verbatim() {
966 return Some(Component::RootDir);
968 } else if self.include_cur_dir() {
969 self.path = &self.path[..self.path.len() - 1];
970 return Some(Component::CurDir);
973 State::Prefix if self.prefix_len() > 0 => {
974 self.back = State::Done;
975 return Some(Component::Prefix(PrefixComponent {
976 raw: unsafe { u8_slice_as_os_str(self.path) },
977 parsed: self.prefix.unwrap(),
981 self.back = State::Done;
984 State::Done => unreachable!(),
991 #[unstable(feature = "fused", issue = "35602")]
992 impl<'a> FusedIterator for Components<'a> {}
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl<'a> cmp::PartialEq for Components<'a> {
996 fn eq(&self, other: &Components<'a>) -> bool {
997 Iterator::eq(self.clone(), other.clone())
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<'a> cmp::Eq for Components<'a> {}
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<'a> cmp::PartialOrd for Components<'a> {
1006 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1007 Iterator::partial_cmp(self.clone(), other.clone())
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl<'a> cmp::Ord for Components<'a> {
1013 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
1014 Iterator::cmp(self.clone(), other.clone())
1018 ////////////////////////////////////////////////////////////////////////////////
1019 // Basic types and traits
1020 ////////////////////////////////////////////////////////////////////////////////
1022 /// An owned, mutable path (akin to [`String`]).
1024 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1025 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1026 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1028 /// [`String`]: ../string/struct.String.html
1029 /// [`Path`]: struct.Path.html
1030 /// [`push`]: struct.PathBuf.html#method.push
1031 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1032 /// [`Deref`]: ../ops/trait.Deref.html
1034 /// More details about the overall approach can be found in
1035 /// the module documentation.
1040 /// use std::path::PathBuf;
1042 /// let mut path = PathBuf::from("c:\\");
1043 /// path.push("windows");
1044 /// path.push("system32");
1045 /// path.set_extension("dll");
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 pub struct PathBuf {
1054 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1055 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1058 /// Allocates an empty `PathBuf`.
1063 /// use std::path::PathBuf;
1065 /// let path = PathBuf::new();
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 pub fn new() -> PathBuf {
1069 PathBuf { inner: OsString::new() }
1072 /// Coerces to a [`Path`] slice.
1074 /// [`Path`]: struct.Path.html
1079 /// use std::path::{Path, PathBuf};
1081 /// let p = PathBuf::from("/test");
1082 /// assert_eq!(Path::new("/test"), p.as_path());
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 pub fn as_path(&self) -> &Path {
1089 /// Extends `self` with `path`.
1091 /// If `path` is absolute, it replaces the current path.
1095 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1096 /// replaces everything except for the prefix (if any) of `self`.
1097 /// * if `path` has a prefix but no root, it replaces `self`.
1101 /// Pushing a relative path extends the existing path:
1104 /// use std::path::PathBuf;
1106 /// let mut path = PathBuf::from("/tmp");
1107 /// path.push("file.bk");
1108 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1111 /// Pushing an absolute path replaces the existing path:
1114 /// use std::path::PathBuf;
1116 /// let mut path = PathBuf::from("/tmp");
1117 /// path.push("/etc");
1118 /// assert_eq!(path, PathBuf::from("/etc"));
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1122 self._push(path.as_ref())
1125 fn _push(&mut self, path: &Path) {
1126 // in general, a separator is needed if the rightmost byte is not a separator
1127 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1129 // in the special case of `C:` on Windows, do *not* add a separator
1131 let comps = self.components();
1132 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1133 comps.prefix.unwrap().is_drive() {
1138 // absolute `path` replaces `self`
1139 if path.is_absolute() || path.prefix().is_some() {
1140 self.as_mut_vec().truncate(0);
1142 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1143 } else if path.has_root() {
1144 let prefix_len = self.components().prefix_remaining();
1145 self.as_mut_vec().truncate(prefix_len);
1147 // `path` is a pure relative path
1148 } else if need_sep {
1149 self.inner.push(MAIN_SEP_STR);
1152 self.inner.push(path);
1155 /// Truncate `self` to [`self.parent`].
1157 /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1158 /// Otherwise, returns `true`.
1160 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1161 /// [`self.parent`]: struct.PathBuf.html#method.parent
1162 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1167 /// use std::path::{Path, PathBuf};
1169 /// let mut p = PathBuf::from("/test/test.rs");
1172 /// assert_eq!(Path::new("/test"), p);
1174 /// assert_eq!(Path::new("/"), p);
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 pub fn pop(&mut self) -> bool {
1178 match self.parent().map(|p| p.as_u8_slice().len()) {
1180 self.as_mut_vec().truncate(len);
1187 /// Updates [`self.file_name`] to `file_name`.
1189 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1192 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1193 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1198 /// use std::path::PathBuf;
1200 /// let mut buf = PathBuf::from("/");
1201 /// assert!(buf.file_name() == None);
1202 /// buf.set_file_name("bar");
1203 /// assert!(buf == PathBuf::from("/bar"));
1204 /// assert!(buf.file_name().is_some());
1205 /// buf.set_file_name("baz.txt");
1206 /// assert!(buf == PathBuf::from("/baz.txt"));
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1210 self._set_file_name(file_name.as_ref())
1213 fn _set_file_name(&mut self, file_name: &OsStr) {
1214 if self.file_name().is_some() {
1215 let popped = self.pop();
1216 debug_assert!(popped);
1218 self.push(file_name);
1221 /// Updates [`self.extension`] to `extension`.
1223 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1224 /// returns `true` and updates the extension otherwise.
1226 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1229 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1230 /// [`self.extension`]: struct.PathBuf.html#method.extension
1231 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1236 /// use std::path::{Path, PathBuf};
1238 /// let mut p = PathBuf::from("/feel/the");
1240 /// p.set_extension("force");
1241 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1243 /// p.set_extension("dark_side");
1244 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1248 self._set_extension(extension.as_ref())
1251 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1252 if self.file_name().is_none() {
1256 let mut stem = match self.file_stem() {
1257 Some(stem) => stem.to_os_string(),
1258 None => OsString::new(),
1261 if !os_str_as_u8_slice(extension).is_empty() {
1263 stem.push(extension);
1265 self.set_file_name(&stem);
1270 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1272 /// [`OsString`]: ../ffi/struct.OsString.html
1277 /// use std::path::PathBuf;
1279 /// let p = PathBuf::from("/the/head");
1280 /// let os_str = p.into_os_string();
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 pub fn into_os_string(self) -> OsString {
1287 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1289 /// [`Box`]: ../../std/boxed/struct.Box.html
1290 /// [`Path`]: struct.Path.html
1291 #[unstable(feature = "into_boxed_path", issue = "40380")]
1292 pub fn into_boxed_path(self) -> Box<Path> {
1293 unsafe { mem::transmute(self.inner.into_boxed_os_str()) }
1297 #[stable(feature = "box_from_path", since = "1.17.0")]
1298 impl<'a> From<&'a Path> for Box<Path> {
1299 fn from(path: &'a Path) -> Box<Path> {
1300 let boxed: Box<OsStr> = path.inner.into();
1301 unsafe { mem::transmute(boxed) }
1305 #[stable(feature = "path_buf_from_box", since = "1.17.0")]
1306 impl<'a> From<Box<Path>> for PathBuf {
1307 fn from(boxed: Box<Path>) -> PathBuf {
1308 boxed.into_path_buf()
1312 #[stable(feature = "box_from_path_buf", since = "1.17.0")]
1313 impl Into<Box<Path>> for PathBuf {
1314 fn into(self) -> Box<Path> {
1315 self.into_boxed_path()
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1321 fn from(s: &'a T) -> PathBuf {
1322 PathBuf::from(s.as_ref().to_os_string())
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl From<OsString> for PathBuf {
1328 fn from(s: OsString) -> PathBuf {
1329 PathBuf { inner: s }
1333 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1334 impl From<PathBuf> for OsString {
1335 fn from(path_buf : PathBuf) -> OsString {
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl From<String> for PathBuf {
1342 fn from(s: String) -> PathBuf {
1343 PathBuf::from(OsString::from(s))
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1349 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1350 let mut buf = PathBuf::new();
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1358 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1360 self.push(p.as_ref())
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl fmt::Debug for PathBuf {
1367 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1368 fmt::Debug::fmt(&**self, formatter)
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl ops::Deref for PathBuf {
1376 fn deref(&self) -> &Path {
1377 Path::new(&self.inner)
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl Borrow<Path> for PathBuf {
1383 fn borrow(&self) -> &Path {
1388 #[stable(feature = "default_for_pathbuf", since = "1.16.0")]
1389 impl Default for PathBuf {
1390 fn default() -> Self {
1395 #[stable(feature = "cow_from_path", since = "1.6.0")]
1396 impl<'a> From<&'a Path> for Cow<'a, Path> {
1398 fn from(s: &'a Path) -> Cow<'a, Path> {
1403 #[stable(feature = "cow_from_path", since = "1.6.0")]
1404 impl<'a> From<PathBuf> for Cow<'a, Path> {
1406 fn from(s: PathBuf) -> Cow<'a, Path> {
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl ToOwned for Path {
1413 type Owned = PathBuf;
1414 fn to_owned(&self) -> PathBuf {
1417 fn clone_into(&self, target: &mut PathBuf) {
1418 self.inner.clone_into(&mut target.inner);
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 impl cmp::PartialEq for PathBuf {
1424 fn eq(&self, other: &PathBuf) -> bool {
1425 self.components() == other.components()
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 impl Hash for PathBuf {
1431 fn hash<H: Hasher>(&self, h: &mut H) {
1432 self.as_path().hash(h)
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl cmp::Eq for PathBuf {}
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 impl cmp::PartialOrd for PathBuf {
1441 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1442 self.components().partial_cmp(other.components())
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl cmp::Ord for PathBuf {
1448 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1449 self.components().cmp(other.components())
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl AsRef<OsStr> for PathBuf {
1455 fn as_ref(&self) -> &OsStr {
1460 /// A slice of a path (akin to [`str`]).
1462 /// This type supports a number of operations for inspecting a path, including
1463 /// breaking the path into its components (separated by `/` or `\`, depending on
1464 /// the platform), extracting the file name, determining whether the path is
1465 /// absolute, and so on.
1467 /// This is an *unsized* type, meaning that it must always be used behind a
1468 /// pointer like `&` or [`Box`]. For an owned version of this type,
1469 /// see [`PathBuf`].
1471 /// [`str`]: ../primitive.str.html
1472 /// [`Box`]: ../boxed/struct.Box.html
1473 /// [`PathBuf`]: struct.PathBuf.html
1475 /// More details about the overall approach can be found in
1476 /// the module documentation.
1481 /// use std::path::Path;
1482 /// use std::ffi::OsStr;
1484 /// let path = Path::new("/tmp/foo/bar.txt");
1486 /// let parent = path.parent();
1487 /// assert_eq!(parent, Some(Path::new("/tmp/foo")));
1489 /// let file_stem = path.file_stem();
1490 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1492 /// let extension = path.extension();
1493 /// assert_eq!(extension, Some(OsStr::new("txt")));
1495 #[stable(feature = "rust1", since = "1.0.0")]
1500 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1503 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1504 /// See its documentation for more.
1506 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1507 /// [`Path`]: struct.Path.html
1508 #[derive(Debug, Clone, PartialEq, Eq)]
1509 #[stable(since = "1.7.0", feature = "strip_prefix")]
1510 pub struct StripPrefixError(());
1513 // The following (private!) function allows construction of a path from a u8
1514 // slice, which is only safe when it is known to follow the OsStr encoding.
1515 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1516 Path::new(u8_slice_as_os_str(s))
1518 // The following (private!) function reveals the byte encoding used for OsStr.
1519 fn as_u8_slice(&self) -> &[u8] {
1520 os_str_as_u8_slice(&self.inner)
1523 /// Directly wraps a string slice as a `Path` slice.
1525 /// This is a cost-free conversion.
1530 /// use std::path::Path;
1532 /// Path::new("foo.txt");
1535 /// You can create `Path`s from `String`s, or even other `Path`s:
1538 /// use std::path::Path;
1540 /// let string = String::from("foo.txt");
1541 /// let from_string = Path::new(&string);
1542 /// let from_path = Path::new(&from_string);
1543 /// assert_eq!(from_string, from_path);
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1547 unsafe { mem::transmute(s.as_ref()) }
1550 /// Yields the underlying [`OsStr`] slice.
1552 /// [`OsStr`]: ../ffi/struct.OsStr.html
1557 /// use std::path::Path;
1559 /// let os_str = Path::new("foo.txt").as_os_str();
1560 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 pub fn as_os_str(&self) -> &OsStr {
1567 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1569 /// This conversion may entail doing a check for UTF-8 validity.
1571 /// [`&str`]: ../primitive.str.html
1576 /// use std::path::Path;
1578 /// let path = Path::new("foo.txt");
1579 /// assert_eq!(path.to_str(), Some("foo.txt"));
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 pub fn to_str(&self) -> Option<&str> {
1586 /// Converts a `Path` to a [`Cow<str>`].
1588 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1590 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1594 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1597 /// use std::path::Path;
1599 /// let path = Path::new("foo.txt");
1600 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1603 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1604 /// have returned `"fo�.txt"`.
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub fn to_string_lossy(&self) -> Cow<str> {
1607 self.inner.to_string_lossy()
1610 /// Converts a `Path` to an owned [`PathBuf`].
1612 /// [`PathBuf`]: struct.PathBuf.html
1617 /// use std::path::Path;
1619 /// let path_buf = Path::new("foo.txt").to_path_buf();
1620 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 pub fn to_path_buf(&self) -> PathBuf {
1624 PathBuf::from(self.inner.to_os_string())
1627 /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
1628 /// the current directory.
1630 /// * On Unix, a path is absolute if it starts with the root, so
1631 /// `is_absolute` and [`has_root`] are equivalent.
1633 /// * On Windows, a path is absolute if it has a prefix and starts with the
1634 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1639 /// use std::path::Path;
1641 /// assert!(!Path::new("foo.txt").is_absolute());
1644 /// [`has_root`]: #method.has_root
1645 #[stable(feature = "rust1", since = "1.0.0")]
1646 #[allow(deprecated)]
1647 pub fn is_absolute(&self) -> bool {
1648 // FIXME: Remove target_os = "redox" and allow Redox prefixes
1649 self.has_root() && (cfg!(unix) || cfg!(target_os = "redox") || self.prefix().is_some())
1652 /// Return `false` if the `Path` is relative, i.e. not absolute.
1654 /// See [`is_absolute`]'s documentation for more details.
1659 /// use std::path::Path;
1661 /// assert!(Path::new("foo.txt").is_relative());
1664 /// [`is_absolute`]: #method.is_absolute
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 pub fn is_relative(&self) -> bool {
1670 fn prefix(&self) -> Option<Prefix> {
1671 self.components().prefix
1674 /// Returns `true` if the `Path` has a root.
1676 /// * On Unix, a path has a root if it begins with `/`.
1678 /// * On Windows, a path has a root if it:
1679 /// * has no prefix and begins with a separator, e.g. `\\windows`
1680 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1681 /// * has any non-disk prefix, e.g. `\\server\share`
1686 /// use std::path::Path;
1688 /// assert!(Path::new("/etc/passwd").has_root());
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 pub fn has_root(&self) -> bool {
1692 self.components().has_root()
1695 /// Returns the `Path` without its final component, if there is one.
1697 /// Returns [`None`] if the path terminates in a root or prefix.
1699 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1704 /// use std::path::Path;
1706 /// let path = Path::new("/foo/bar");
1707 /// let parent = path.parent().unwrap();
1708 /// assert_eq!(parent, Path::new("/foo"));
1710 /// let grand_parent = parent.parent().unwrap();
1711 /// assert_eq!(grand_parent, Path::new("/"));
1712 /// assert_eq!(grand_parent.parent(), None);
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 pub fn parent(&self) -> Option<&Path> {
1716 let mut comps = self.components();
1717 let comp = comps.next_back();
1720 Component::Normal(_) |
1722 Component::ParentDir => Some(comps.as_path()),
1728 /// Returns the final component of the `Path`, if it is a normal file.
1730 /// Returns [`None`] If the path terminates in `..`.
1732 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1737 /// use std::path::Path;
1738 /// use std::ffi::OsStr;
1740 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt").file_name());
1741 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1742 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1743 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub fn file_name(&self) -> Option<&OsStr> {
1747 self.components().next_back().and_then(|p| {
1749 Component::Normal(p) => Some(p.as_ref()),
1755 /// Returns a path that, when joined onto `base`, yields `self`.
1759 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1760 /// returns `false`), returns [`Err`].
1762 /// [`starts_with`]: #method.starts_with
1763 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1768 /// use std::path::Path;
1770 /// let path = Path::new("/test/haha/foo.txt");
1772 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1773 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1774 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1776 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1777 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1778 -> Result<&'a Path, StripPrefixError>
1779 where P: AsRef<Path>
1781 self._strip_prefix(base.as_ref())
1784 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1785 -> Result<&'a Path, StripPrefixError> {
1786 iter_after(self.components(), base.components())
1787 .map(|c| c.as_path())
1788 .ok_or(StripPrefixError(()))
1791 /// Determines whether `base` is a prefix of `self`.
1793 /// Only considers whole path components to match.
1798 /// use std::path::Path;
1800 /// let path = Path::new("/etc/passwd");
1802 /// assert!(path.starts_with("/etc"));
1804 /// assert!(!path.starts_with("/e"));
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1808 self._starts_with(base.as_ref())
1811 fn _starts_with(&self, base: &Path) -> bool {
1812 iter_after(self.components(), base.components()).is_some()
1815 /// Determines whether `child` is a suffix of `self`.
1817 /// Only considers whole path components to match.
1822 /// use std::path::Path;
1824 /// let path = Path::new("/etc/passwd");
1826 /// assert!(path.ends_with("passwd"));
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1830 self._ends_with(child.as_ref())
1833 fn _ends_with(&self, child: &Path) -> bool {
1834 iter_after(self.components().rev(), child.components().rev()).is_some()
1837 /// Extracts the stem (non-extension) portion of [`self.file_name`].
1839 /// [`self.file_name`]: struct.Path.html#method.file_name
1843 /// * [`None`], if there is no file name;
1844 /// * The entire file name if there is no embedded `.`;
1845 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1846 /// * Otherwise, the portion of the file name before the final `.`
1848 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1853 /// use std::path::Path;
1855 /// let path = Path::new("foo.rs");
1857 /// assert_eq!("foo", path.file_stem().unwrap());
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 pub fn file_stem(&self) -> Option<&OsStr> {
1861 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1864 /// Extracts the extension of [`self.file_name`], if possible.
1866 /// The extension is:
1868 /// * [`None`], if there is no file name;
1869 /// * [`None`], if there is no embedded `.`;
1870 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1871 /// * Otherwise, the portion of the file name after the final `.`
1873 /// [`self.file_name`]: struct.Path.html#method.file_name
1874 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1879 /// use std::path::Path;
1881 /// let path = Path::new("foo.rs");
1883 /// assert_eq!("rs", path.extension().unwrap());
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 pub fn extension(&self) -> Option<&OsStr> {
1887 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1890 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1892 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1894 /// [`PathBuf`]: struct.PathBuf.html
1895 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1900 /// use std::path::{Path, PathBuf};
1902 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1906 self._join(path.as_ref())
1909 fn _join(&self, path: &Path) -> PathBuf {
1910 let mut buf = self.to_path_buf();
1915 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1917 /// See [`PathBuf::set_file_name`] for more details.
1919 /// [`PathBuf`]: struct.PathBuf.html
1920 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1925 /// use std::path::{Path, PathBuf};
1927 /// let path = Path::new("/tmp/foo.txt");
1928 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1932 self._with_file_name(file_name.as_ref())
1935 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1936 let mut buf = self.to_path_buf();
1937 buf.set_file_name(file_name);
1941 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
1943 /// See [`PathBuf::set_extension`] for more details.
1945 /// [`PathBuf`]: struct.PathBuf.html
1946 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
1951 /// use std::path::{Path, PathBuf};
1953 /// let path = Path::new("foo.rs");
1954 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1958 self._with_extension(extension.as_ref())
1961 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1962 let mut buf = self.to_path_buf();
1963 buf.set_extension(extension);
1967 /// Produces an iterator over the [`Component`]s of the path.
1969 /// When parsing the path, there is a small amount of normalization:
1971 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
1972 /// `a` and `b` as components.
1974 /// * Occurentces of `.` are normalized away, exept if they are at the
1975 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
1976 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
1977 /// an additional [`CurDir`] component.
1979 /// Note that no other normalization takes place; in particular, `a/c`
1980 /// and `a/b/../c` are distinct, to account for the possibility that `b`
1981 /// is a symbolic link (so its parent isn't `a`).
1986 /// use std::path::{Path, Component};
1987 /// use std::ffi::OsStr;
1989 /// let mut components = Path::new("/tmp/foo.txt").components();
1991 /// assert_eq!(components.next(), Some(Component::RootDir));
1992 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1993 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1994 /// assert_eq!(components.next(), None)
1997 /// [`Component`]: enum.Component.html
1998 /// [`CurDir`]: enum.Component.html#variant.CurDir
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 pub fn components(&self) -> Components {
2001 let prefix = parse_prefix(self.as_os_str());
2003 path: self.as_u8_slice(),
2005 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
2006 front: State::Prefix,
2011 /// Produces an iterator over the path's components viewed as [`OsStr`]
2014 /// For more information about the particulars of how the path is separated
2015 /// into components, see [`components`].
2017 /// [`components`]: #method.components
2018 /// [`OsStr`]: ../ffi/struct.OsStr.html
2023 /// use std::path::{self, Path};
2024 /// use std::ffi::OsStr;
2026 /// let mut it = Path::new("/tmp/foo.txt").iter();
2027 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2028 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2029 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2030 /// assert_eq!(it.next(), None)
2032 #[stable(feature = "rust1", since = "1.0.0")]
2033 pub fn iter(&self) -> Iter {
2034 Iter { inner: self.components() }
2037 /// Returns an object that implements [`Display`] for safely printing paths
2038 /// that may contain non-Unicode data.
2040 /// [`Display`]: ../fmt/trait.Display.html
2045 /// use std::path::Path;
2047 /// let path = Path::new("/tmp/foo.rs");
2049 /// println!("{}", path.display());
2051 #[stable(feature = "rust1", since = "1.0.0")]
2052 pub fn display(&self) -> Display {
2053 Display { path: self }
2056 /// Queries the file system to get information about a file, directory, etc.
2058 /// This function will traverse symbolic links to query information about the
2059 /// destination file.
2061 /// This is an alias to [`fs::metadata`].
2063 /// [`fs::metadata`]: ../fs/fn.metadata.html
2068 /// use std::path::Path;
2070 /// let path = Path::new("/Minas/tirith");
2071 /// let metadata = path.metadata().expect("metadata call failed");
2072 /// println!("{:?}", metadata.file_type());
2074 #[stable(feature = "path_ext", since = "1.5.0")]
2075 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2079 /// Queries the metadata about a file without following symlinks.
2081 /// This is an alias to [`fs::symlink_metadata`].
2083 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2088 /// use std::path::Path;
2090 /// let path = Path::new("/Minas/tirith");
2091 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2092 /// println!("{:?}", metadata.file_type());
2094 #[stable(feature = "path_ext", since = "1.5.0")]
2095 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2096 fs::symlink_metadata(self)
2099 /// Returns the canonical form of the path with all intermediate components
2100 /// normalized and symbolic links resolved.
2102 /// This is an alias to [`fs::canonicalize`].
2104 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2109 /// use std::path::{Path, PathBuf};
2111 /// let path = Path::new("/foo/test/../test/bar.rs");
2112 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2114 #[stable(feature = "path_ext", since = "1.5.0")]
2115 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2116 fs::canonicalize(self)
2119 /// Reads a symbolic link, returning the file that the link points to.
2121 /// This is an alias to [`fs::read_link`].
2123 /// [`fs::read_link`]: ../fs/fn.read_link.html
2128 /// use std::path::Path;
2130 /// let path = Path::new("/laputa/sky_castle.rs");
2131 /// let path_link = path.read_link().expect("read_link call failed");
2133 #[stable(feature = "path_ext", since = "1.5.0")]
2134 pub fn read_link(&self) -> io::Result<PathBuf> {
2138 /// Returns an iterator over the entries within a directory.
2140 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2141 /// errors may be encountered after an iterator is initially constructed.
2143 /// This is an alias to [`fs::read_dir`].
2145 /// [`io::Result`]: ../io/type.Result.html
2146 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2147 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2152 /// use std::path::Path;
2154 /// let path = Path::new("/laputa");
2155 /// for entry in path.read_dir().expect("read_dir call failed") {
2156 /// if let Ok(entry) = entry {
2157 /// println!("{:?}", entry.path());
2161 #[stable(feature = "path_ext", since = "1.5.0")]
2162 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2166 /// Returns whether the path points at an existing entity.
2168 /// This function will traverse symbolic links to query information about the
2169 /// destination file. In case of broken symbolic links this will return `false`.
2174 /// use std::path::Path;
2175 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2177 #[stable(feature = "path_ext", since = "1.5.0")]
2178 pub fn exists(&self) -> bool {
2179 fs::metadata(self).is_ok()
2182 /// Returns whether the path is pointing at a regular file.
2184 /// This function will traverse symbolic links to query information about the
2185 /// destination file. In case of broken symbolic links this will return `false`.
2190 /// use std::path::Path;
2191 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2192 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2194 #[stable(feature = "path_ext", since = "1.5.0")]
2195 pub fn is_file(&self) -> bool {
2196 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2199 /// Returns whether the path is pointing at a directory.
2201 /// This function will traverse symbolic links to query information about the
2202 /// destination file. In case of broken symbolic links this will return `false`.
2207 /// use std::path::Path;
2208 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2209 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2211 #[stable(feature = "path_ext", since = "1.5.0")]
2212 pub fn is_dir(&self) -> bool {
2213 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2216 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2219 /// [`Box`]: ../../std/boxed/struct.Box.html
2220 /// [`PathBuf`]: struct.PathBuf.html
2221 #[unstable(feature = "into_boxed_path", issue = "40380")]
2222 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2223 let inner: Box<OsStr> = unsafe { mem::transmute(self) };
2224 PathBuf { inner: OsString::from(inner) }
2228 #[stable(feature = "rust1", since = "1.0.0")]
2229 impl AsRef<OsStr> for Path {
2230 fn as_ref(&self) -> &OsStr {
2235 #[stable(feature = "rust1", since = "1.0.0")]
2236 impl fmt::Debug for Path {
2237 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2238 self.inner.fmt(formatter)
2242 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2244 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2245 /// [`Display`] trait in a way that mitigates that. It is created by the
2246 /// [`display`][`Path::display`] method on [`Path`].
2251 /// use std::path::Path;
2253 /// let path = Path::new("/tmp/foo.rs");
2255 /// println!("{}", path.display());
2258 /// [`Display`]: ../../std/fmt/trait.Display.html
2259 /// [`format!`]: ../../std/macro.format.html
2260 /// [`Path`]: struct.Path.html
2261 /// [`Path::display`]: struct.Path.html#method.display
2262 #[stable(feature = "rust1", since = "1.0.0")]
2263 pub struct Display<'a> {
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<'a> fmt::Debug for Display<'a> {
2269 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2270 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
2274 #[stable(feature = "rust1", since = "1.0.0")]
2275 impl<'a> fmt::Display for Display<'a> {
2276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2277 fmt::Display::fmt(&self.path.to_string_lossy(), f)
2281 #[stable(feature = "rust1", since = "1.0.0")]
2282 impl cmp::PartialEq for Path {
2283 fn eq(&self, other: &Path) -> bool {
2284 self.components().eq(other.components())
2288 #[stable(feature = "rust1", since = "1.0.0")]
2289 impl Hash for Path {
2290 fn hash<H: Hasher>(&self, h: &mut H) {
2291 for component in self.components() {
2297 #[stable(feature = "rust1", since = "1.0.0")]
2298 impl cmp::Eq for Path {}
2300 #[stable(feature = "rust1", since = "1.0.0")]
2301 impl cmp::PartialOrd for Path {
2302 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2303 self.components().partial_cmp(other.components())
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl cmp::Ord for Path {
2309 fn cmp(&self, other: &Path) -> cmp::Ordering {
2310 self.components().cmp(other.components())
2314 #[stable(feature = "rust1", since = "1.0.0")]
2315 impl AsRef<Path> for Path {
2316 fn as_ref(&self) -> &Path {
2321 #[stable(feature = "rust1", since = "1.0.0")]
2322 impl AsRef<Path> for OsStr {
2323 fn as_ref(&self) -> &Path {
2328 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2329 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2330 fn as_ref(&self) -> &Path {
2335 #[stable(feature = "rust1", since = "1.0.0")]
2336 impl AsRef<Path> for OsString {
2337 fn as_ref(&self) -> &Path {
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 impl AsRef<Path> for str {
2344 fn as_ref(&self) -> &Path {
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl AsRef<Path> for String {
2351 fn as_ref(&self) -> &Path {
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl AsRef<Path> for PathBuf {
2358 fn as_ref(&self) -> &Path {
2363 #[stable(feature = "path_into_iter", since = "1.6.0")]
2364 impl<'a> IntoIterator for &'a PathBuf {
2365 type Item = &'a OsStr;
2366 type IntoIter = Iter<'a>;
2367 fn into_iter(self) -> Iter<'a> { self.iter() }
2370 #[stable(feature = "path_into_iter", since = "1.6.0")]
2371 impl<'a> IntoIterator for &'a Path {
2372 type Item = &'a OsStr;
2373 type IntoIter = Iter<'a>;
2374 fn into_iter(self) -> Iter<'a> { self.iter() }
2377 macro_rules! impl_cmp {
2378 ($lhs:ty, $rhs: ty) => {
2379 #[stable(feature = "partialeq_path", since = "1.6.0")]
2380 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2382 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2385 #[stable(feature = "partialeq_path", since = "1.6.0")]
2386 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2388 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2391 #[stable(feature = "cmp_path", since = "1.8.0")]
2392 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2394 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2395 <Path as PartialOrd>::partial_cmp(self, other)
2399 #[stable(feature = "cmp_path", since = "1.8.0")]
2400 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2402 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2403 <Path as PartialOrd>::partial_cmp(self, other)
2409 impl_cmp!(PathBuf, Path);
2410 impl_cmp!(PathBuf, &'a Path);
2411 impl_cmp!(Cow<'a, Path>, Path);
2412 impl_cmp!(Cow<'a, Path>, &'b Path);
2413 impl_cmp!(Cow<'a, Path>, PathBuf);
2415 macro_rules! impl_cmp_os_str {
2416 ($lhs:ty, $rhs: ty) => {
2417 #[stable(feature = "cmp_path", since = "1.8.0")]
2418 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2420 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2423 #[stable(feature = "cmp_path", since = "1.8.0")]
2424 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2426 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2429 #[stable(feature = "cmp_path", since = "1.8.0")]
2430 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2432 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2433 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2437 #[stable(feature = "cmp_path", since = "1.8.0")]
2438 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2440 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2441 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2447 impl_cmp_os_str!(PathBuf, OsStr);
2448 impl_cmp_os_str!(PathBuf, &'a OsStr);
2449 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2450 impl_cmp_os_str!(PathBuf, OsString);
2451 impl_cmp_os_str!(Path, OsStr);
2452 impl_cmp_os_str!(Path, &'a OsStr);
2453 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2454 impl_cmp_os_str!(Path, OsString);
2455 impl_cmp_os_str!(&'a Path, OsStr);
2456 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2457 impl_cmp_os_str!(&'a Path, OsString);
2458 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2459 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2460 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2462 #[stable(since = "1.7.0", feature = "strip_prefix")]
2463 impl fmt::Display for StripPrefixError {
2464 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2465 self.description().fmt(f)
2469 #[stable(since = "1.7.0", feature = "strip_prefix")]
2470 impl Error for StripPrefixError {
2471 fn description(&self) -> &str { "prefix not found" }
2479 ($path:expr, iter: $iter:expr) => (
2481 let path = Path::new($path);
2483 // Forward iteration
2484 let comps = path.iter()
2485 .map(|p| p.to_string_lossy().into_owned())
2486 .collect::<Vec<String>>();
2487 let exp: &[&str] = &$iter;
2488 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2489 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2492 // Reverse iteration
2493 let comps = Path::new($path).iter().rev()
2494 .map(|p| p.to_string_lossy().into_owned())
2495 .collect::<Vec<String>>();
2496 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2497 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2502 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2504 let path = Path::new($path);
2506 let act_root = path.has_root();
2507 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2508 $has_root, act_root);
2510 let act_abs = path.is_absolute();
2511 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2512 $is_absolute, act_abs);
2516 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2518 let path = Path::new($path);
2520 let parent = path.parent().map(|p| p.to_str().unwrap());
2521 let exp_parent: Option<&str> = $parent;
2522 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2523 exp_parent, parent);
2525 let file = path.file_name().map(|p| p.to_str().unwrap());
2526 let exp_file: Option<&str> = $file;
2527 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2532 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2534 let path = Path::new($path);
2536 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2537 let exp_stem: Option<&str> = $file_stem;
2538 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2541 let ext = path.extension().map(|p| p.to_str().unwrap());
2542 let exp_ext: Option<&str> = $extension;
2543 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2548 ($path:expr, iter: $iter:expr,
2549 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2550 parent: $parent:expr, file_name: $file:expr,
2551 file_stem: $file_stem:expr, extension: $extension:expr) => (
2553 t!($path, iter: $iter);
2554 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2555 t!($path, parent: $parent, file_name: $file);
2556 t!($path, file_stem: $file_stem, extension: $extension);
2565 let static_path = Path::new("/home/foo");
2566 let static_cow_path: Cow<'static, Path> = static_path.into();
2567 let pathbuf = PathBuf::from("/home/foo");
2570 let path: &Path = &pathbuf;
2571 let borrowed_cow_path: Cow<Path> = path.into();
2573 assert_eq!(static_cow_path, borrowed_cow_path);
2576 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2578 assert_eq!(static_cow_path, owned_cow_path);
2583 pub fn test_decompositions_unix() {
2599 file_name: Some("foo"),
2600 file_stem: Some("foo"),
2619 file_name: Some("foo"),
2620 file_stem: Some("foo"),
2629 file_name: Some("foo"),
2630 file_stem: Some("foo"),
2639 file_name: Some("foo"),
2640 file_stem: Some("foo"),
2645 iter: ["foo", "bar"],
2648 parent: Some("foo"),
2649 file_name: Some("bar"),
2650 file_stem: Some("bar"),
2655 iter: ["/", "foo", "bar"],
2658 parent: Some("/foo"),
2659 file_name: Some("bar"),
2660 file_stem: Some("bar"),
2669 file_name: Some("foo"),
2670 file_stem: Some("foo"),
2675 iter: ["/", "foo", "bar"],
2678 parent: Some("///foo"),
2679 file_name: Some("bar"),
2680 file_stem: Some("bar"),
2719 file_name: Some("foo"),
2720 file_stem: Some("foo"),
2725 iter: ["foo", ".."],
2728 parent: Some("foo"),
2739 file_name: Some("foo"),
2740 file_stem: Some("foo"),
2745 iter: ["foo", "bar"],
2748 parent: Some("foo"),
2749 file_name: Some("bar"),
2750 file_stem: Some("bar"),
2755 iter: ["foo", ".."],
2758 parent: Some("foo"),
2765 iter: ["foo", "..", "bar"],
2768 parent: Some("foo/.."),
2769 file_name: Some("bar"),
2770 file_stem: Some("bar"),
2779 file_name: Some("a"),
2780 file_stem: Some("a"),
2809 file_name: Some("b"),
2810 file_stem: Some("b"),
2819 file_name: Some("b"),
2820 file_stem: Some("b"),
2829 file_name: Some("b"),
2830 file_stem: Some("b"),
2835 iter: ["a", "b", "c"],
2838 parent: Some("a/b"),
2839 file_name: Some("c"),
2840 file_stem: Some("c"),
2849 file_name: Some(".foo"),
2850 file_stem: Some(".foo"),
2857 pub fn test_decompositions_windows() {
2873 file_name: Some("foo"),
2874 file_stem: Some("foo"),
2929 iter: ["\\", "foo"],
2933 file_name: Some("foo"),
2934 file_stem: Some("foo"),
2943 file_name: Some("foo"),
2944 file_stem: Some("foo"),
2949 iter: ["\\", "foo"],
2953 file_name: Some("foo"),
2954 file_stem: Some("foo"),
2959 iter: ["foo", "bar"],
2962 parent: Some("foo"),
2963 file_name: Some("bar"),
2964 file_stem: Some("bar"),
2969 iter: ["\\", "foo", "bar"],
2972 parent: Some("/foo"),
2973 file_name: Some("bar"),
2974 file_stem: Some("bar"),
2979 iter: ["\\", "foo"],
2983 file_name: Some("foo"),
2984 file_stem: Some("foo"),
2989 iter: ["\\", "foo", "bar"],
2992 parent: Some("///foo"),
2993 file_name: Some("bar"),
2994 file_stem: Some("bar"),
3033 file_name: Some("foo"),
3034 file_stem: Some("foo"),
3039 iter: ["foo", ".."],
3042 parent: Some("foo"),
3053 file_name: Some("foo"),
3054 file_stem: Some("foo"),
3059 iter: ["foo", "bar"],
3062 parent: Some("foo"),
3063 file_name: Some("bar"),
3064 file_stem: Some("bar"),
3069 iter: ["foo", ".."],
3072 parent: Some("foo"),
3079 iter: ["foo", "..", "bar"],
3082 parent: Some("foo/.."),
3083 file_name: Some("bar"),
3084 file_stem: Some("bar"),
3093 file_name: Some("a"),
3094 file_stem: Some("a"),
3123 file_name: Some("b"),
3124 file_stem: Some("b"),
3133 file_name: Some("b"),
3134 file_stem: Some("b"),
3143 file_name: Some("b"),
3144 file_stem: Some("b"),
3149 iter: ["a", "b", "c"],
3152 parent: Some("a/b"),
3153 file_name: Some("c"),
3154 file_stem: Some("c"),
3158 iter: ["a", "b", "c"],
3161 parent: Some("a\\b"),
3162 file_name: Some("c"),
3163 file_stem: Some("c"),
3172 file_name: Some("a"),
3173 file_stem: Some("a"),
3178 iter: ["c:", "\\", "foo.txt"],
3181 parent: Some("c:\\"),
3182 file_name: Some("foo.txt"),
3183 file_stem: Some("foo"),
3184 extension: Some("txt")
3187 t!("\\\\server\\share\\foo.txt",
3188 iter: ["\\\\server\\share", "\\", "foo.txt"],
3191 parent: Some("\\\\server\\share\\"),
3192 file_name: Some("foo.txt"),
3193 file_stem: Some("foo"),
3194 extension: Some("txt")
3197 t!("\\\\server\\share",
3198 iter: ["\\\\server\\share", "\\"],
3208 iter: ["\\", "server"],
3212 file_name: Some("server"),
3213 file_stem: Some("server"),
3217 t!("\\\\?\\bar\\foo.txt",
3218 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3221 parent: Some("\\\\?\\bar\\"),
3222 file_name: Some("foo.txt"),
3223 file_stem: Some("foo"),
3224 extension: Some("txt")
3228 iter: ["\\\\?\\bar"],
3247 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3248 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3251 parent: Some("\\\\?\\UNC\\server\\share\\"),
3252 file_name: Some("foo.txt"),
3253 file_stem: Some("foo"),
3254 extension: Some("txt")
3257 t!("\\\\?\\UNC\\server",
3258 iter: ["\\\\?\\UNC\\server"],
3268 iter: ["\\\\?\\UNC\\"],
3277 t!("\\\\?\\C:\\foo.txt",
3278 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3281 parent: Some("\\\\?\\C:\\"),
3282 file_name: Some("foo.txt"),
3283 file_stem: Some("foo"),
3284 extension: Some("txt")
3289 iter: ["\\\\?\\C:", "\\"],
3300 iter: ["\\\\?\\C:"],
3310 t!("\\\\?\\foo/bar",
3311 iter: ["\\\\?\\foo/bar"],
3322 iter: ["\\\\?\\C:/foo"],
3332 t!("\\\\.\\foo\\bar",
3333 iter: ["\\\\.\\foo", "\\", "bar"],
3336 parent: Some("\\\\.\\foo\\"),
3337 file_name: Some("bar"),
3338 file_stem: Some("bar"),
3344 iter: ["\\\\.\\foo", "\\"],
3354 t!("\\\\.\\foo/bar",
3355 iter: ["\\\\.\\foo/bar", "\\"],
3365 t!("\\\\.\\foo\\bar/baz",
3366 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3369 parent: Some("\\\\.\\foo\\bar"),
3370 file_name: Some("baz"),
3371 file_stem: Some("baz"),
3377 iter: ["\\\\.\\", "\\"],
3387 iter: ["\\\\?\\a", "\\", "b"],
3390 parent: Some("\\\\?\\a\\"),
3391 file_name: Some("b"),
3392 file_stem: Some("b"),
3398 pub fn test_stem_ext() {
3400 file_stem: Some("foo"),
3405 file_stem: Some("foo"),
3410 file_stem: Some(".foo"),
3415 file_stem: Some("foo"),
3416 extension: Some("txt")
3420 file_stem: Some("foo.bar"),
3421 extension: Some("txt")
3425 file_stem: Some("foo.bar"),
3446 pub fn test_push() {
3448 ($path:expr, $push:expr, $expected:expr) => ( {
3449 let mut actual = PathBuf::from($path);
3451 assert!(actual.to_str() == Some($expected),
3452 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3453 $push, $path, $expected, actual.to_str().unwrap());
3458 tp!("", "foo", "foo");
3459 tp!("foo", "bar", "foo/bar");
3460 tp!("foo/", "bar", "foo/bar");
3461 tp!("foo//", "bar", "foo//bar");
3462 tp!("foo/.", "bar", "foo/./bar");
3463 tp!("foo./.", "bar", "foo././bar");
3464 tp!("foo", "", "foo/");
3465 tp!("foo", ".", "foo/.");
3466 tp!("foo", "..", "foo/..");
3467 tp!("foo", "/", "/");
3468 tp!("/foo/bar", "/", "/");
3469 tp!("/foo/bar", "/baz", "/baz");
3470 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3472 tp!("", "foo", "foo");
3473 tp!("foo", "bar", r"foo\bar");
3474 tp!("foo/", "bar", r"foo/bar");
3475 tp!(r"foo\", "bar", r"foo\bar");
3476 tp!("foo//", "bar", r"foo//bar");
3477 tp!(r"foo\\", "bar", r"foo\\bar");
3478 tp!("foo/.", "bar", r"foo/.\bar");
3479 tp!("foo./.", "bar", r"foo./.\bar");
3480 tp!(r"foo\.", "bar", r"foo\.\bar");
3481 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3482 tp!("foo", "", "foo\\");
3483 tp!("foo", ".", r"foo\.");
3484 tp!("foo", "..", r"foo\..");
3485 tp!("foo", "/", "/");
3486 tp!("foo", r"\", r"\");
3487 tp!("/foo/bar", "/", "/");
3488 tp!(r"\foo\bar", r"\", r"\");
3489 tp!("/foo/bar", "/baz", "/baz");
3490 tp!("/foo/bar", r"\baz", r"\baz");
3491 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3492 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3494 tp!("c:\\", "windows", "c:\\windows");
3495 tp!("c:", "windows", "c:windows");
3497 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3498 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3499 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3500 tp!("a\\b", "\\c\\d", "\\c\\d");
3501 tp!("a\\b", ".", "a\\b\\.");
3502 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3503 tp!("a\\b", "C:a.txt", "C:a.txt");
3504 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3505 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3506 tp!("C:\\a\\b\\c", "C:d", "C:d");
3507 tp!("C:a\\b\\c", "C:d", "C:d");
3508 tp!("C:", r"a\b\c", r"C:a\b\c");
3509 tp!("C:", r"..\a", r"C:..\a");
3510 tp!("\\\\server\\share\\foo",
3512 "\\\\server\\share\\foo\\bar");
3513 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3514 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3515 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3516 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3517 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3518 tp!("\\\\?\\UNC\\server\\share\\foo",
3520 "\\\\?\\UNC\\server\\share\\foo\\bar");
3521 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3522 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3524 // Note: modified from old path API
3525 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3528 "\\\\?\\UNC\\server\\share",
3529 "\\\\?\\UNC\\server\\share");
3530 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3531 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3532 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3533 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3535 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3542 ($path:expr, $expected:expr, $output:expr) => ( {
3543 let mut actual = PathBuf::from($path);
3544 let output = actual.pop();
3545 assert!(actual.to_str() == Some($expected) && output == $output,
3546 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3547 $path, $expected, $output,
3548 actual.to_str().unwrap(), output);
3553 tp!("/", "/", false);
3554 tp!("foo", "", true);
3556 tp!("/foo", "/", true);
3557 tp!("/foo/bar", "/foo", true);
3558 tp!("foo/bar", "foo", true);
3559 tp!("foo/.", "", true);
3560 tp!("foo//bar", "foo", true);
3563 tp!("a\\b\\c", "a\\b", true);
3564 tp!("\\a", "\\", true);
3565 tp!("\\", "\\", false);
3567 tp!("C:\\a\\b", "C:\\a", true);
3568 tp!("C:\\a", "C:\\", true);
3569 tp!("C:\\", "C:\\", false);
3570 tp!("C:a\\b", "C:a", true);
3571 tp!("C:a", "C:", true);
3572 tp!("C:", "C:", false);
3573 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3574 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3575 tp!("\\\\server\\share", "\\\\server\\share", false);
3576 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3577 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3578 tp!("\\\\?\\a", "\\\\?\\a", false);
3579 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3580 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3581 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3582 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3583 "\\\\?\\UNC\\server\\share\\a",
3585 tp!("\\\\?\\UNC\\server\\share\\a",
3586 "\\\\?\\UNC\\server\\share\\",
3588 tp!("\\\\?\\UNC\\server\\share",
3589 "\\\\?\\UNC\\server\\share",
3591 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3592 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3593 tp!("\\\\.\\a", "\\\\.\\a", false);
3595 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3600 pub fn test_set_file_name() {
3602 ($path:expr, $file:expr, $expected:expr) => ( {
3603 let mut p = PathBuf::from($path);
3604 p.set_file_name($file);
3605 assert!(p.to_str() == Some($expected),
3606 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3607 $path, $file, $expected,
3608 p.to_str().unwrap());
3612 tfn!("foo", "foo", "foo");
3613 tfn!("foo", "bar", "bar");
3614 tfn!("foo", "", "");
3615 tfn!("", "foo", "foo");
3617 tfn!(".", "foo", "./foo");
3618 tfn!("foo/", "bar", "bar");
3619 tfn!("foo/.", "bar", "bar");
3620 tfn!("..", "foo", "../foo");
3621 tfn!("foo/..", "bar", "foo/../bar");
3622 tfn!("/", "foo", "/foo");
3624 tfn!(".", "foo", r".\foo");
3625 tfn!(r"foo\", "bar", r"bar");
3626 tfn!(r"foo\.", "bar", r"bar");
3627 tfn!("..", "foo", r"..\foo");
3628 tfn!(r"foo\..", "bar", r"foo\..\bar");
3629 tfn!(r"\", "foo", r"\foo");
3634 pub fn test_set_extension() {
3636 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3637 let mut p = PathBuf::from($path);
3638 let output = p.set_extension($ext);
3639 assert!(p.to_str() == Some($expected) && output == $output,
3640 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3641 $path, $ext, $expected, $output,
3642 p.to_str().unwrap(), output);
3646 tfe!("foo", "txt", "foo.txt", true);
3647 tfe!("foo.bar", "txt", "foo.txt", true);
3648 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3649 tfe!(".test", "txt", ".test.txt", true);
3650 tfe!("foo.txt", "", "foo", true);
3651 tfe!("foo", "", "foo", true);
3652 tfe!("", "foo", "", false);
3653 tfe!(".", "foo", ".", false);
3654 tfe!("foo/", "bar", "foo.bar", true);
3655 tfe!("foo/.", "bar", "foo.bar", true);
3656 tfe!("..", "foo", "..", false);
3657 tfe!("foo/..", "bar", "foo/..", false);
3658 tfe!("/", "foo", "/", false);
3662 fn test_eq_recievers() {
3665 let borrowed: &Path = Path::new("foo/bar");
3666 let mut owned: PathBuf = PathBuf::new();
3669 let borrowed_cow: Cow<Path> = borrowed.into();
3670 let owned_cow: Cow<Path> = owned.clone().into();
3673 ($($current:expr),+) => {
3675 assert_eq!($current, borrowed);
3676 assert_eq!($current, owned);
3677 assert_eq!($current, borrowed_cow);
3678 assert_eq!($current, owned_cow);
3683 t!(borrowed, owned, borrowed_cow, owned_cow);
3687 pub fn test_compare() {
3688 use hash::{Hash, Hasher};
3689 use collections::hash_map::DefaultHasher;
3691 fn hash<T: Hash>(t: T) -> u64 {
3692 let mut s = DefaultHasher::new();
3698 ($path1:expr, $path2:expr, eq: $eq:expr,
3699 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3700 relative_from: $relative_from:expr) => ({
3701 let path1 = Path::new($path1);
3702 let path2 = Path::new($path2);
3704 let eq = path1 == path2;
3705 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3706 $path1, $path2, $eq, eq);
3707 assert!($eq == (hash(path1) == hash(path2)),
3708 "{:?} == {:?}, expected {:?}, got {} and {}",
3709 $path1, $path2, $eq, hash(path1), hash(path2));
3711 let starts_with = path1.starts_with(path2);
3712 assert!(starts_with == $starts_with,
3713 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3714 $starts_with, starts_with);
3716 let ends_with = path1.ends_with(path2);
3717 assert!(ends_with == $ends_with,
3718 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3719 $ends_with, ends_with);
3721 let relative_from = path1.strip_prefix(path2)
3722 .map(|p| p.to_str().unwrap())
3724 let exp: Option<&str> = $relative_from;
3725 assert!(relative_from == exp,
3726 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3727 $path1, $path2, exp, relative_from);
3735 relative_from: Some("")
3742 relative_from: Some("foo")
3756 relative_from: Some("")
3763 relative_from: Some("")
3766 tc!("foo/bar", "foo",
3770 relative_from: Some("bar")
3773 tc!("foo/bar/baz", "foo/bar",
3777 relative_from: Some("baz")
3780 tc!("foo/bar", "foo/bar/baz",
3787 tc!("./foo/bar/", ".",
3791 relative_from: Some("foo/bar")
3795 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3796 r"c:\src\rust\cargo-test\test",
3800 relative_from: Some("Cargo.toml")
3803 tc!(r"c:\foo", r"C:\foo",
3807 relative_from: Some("")
3813 fn test_components_debug() {
3814 let path = Path::new("/tmp");
3816 let mut components = path.components();
3818 let expected = "Components([RootDir, Normal(\"tmp\")])";
3819 let actual = format!("{:?}", components);
3820 assert_eq!(expected, actual);
3822 let _ = components.next().unwrap();
3823 let expected = "Components([Normal(\"tmp\")])";
3824 let actual = format!("{:?}", components);
3825 assert_eq!(expected, actual);
3827 let _ = components.next().unwrap();
3828 let expected = "Components([])";
3829 let actual = format!("{:?}", components);
3830 assert_eq!(expected, actual);
3835 fn test_iter_debug() {
3836 let path = Path::new("/tmp");
3838 let mut iter = path.iter();
3840 let expected = "Iter([\"/\", \"tmp\"])";
3841 let actual = format!("{:?}", iter);
3842 assert_eq!(expected, actual);
3844 let _ = iter.next().unwrap();
3845 let expected = "Iter([\"tmp\"])";
3846 let actual = format!("{:?}", iter);
3847 assert_eq!(expected, actual);
3849 let _ = iter.next().unwrap();
3850 let expected = "Iter([])";
3851 let actual = format!("{:?}", iter);
3852 assert_eq!(expected, actual);
3857 let orig: &str = "some/sort/of/path";
3858 let path = Path::new(orig);
3859 let boxed: Box<Path> = Box::from(path);
3860 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
3861 assert_eq!(path, &*boxed);
3862 assert_eq!(&*boxed, &*path_buf);
3863 assert_eq!(&*path_buf, path);
3867 fn test_clone_into() {
3868 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
3869 let path = Path::new("short");
3870 path.clone_into(&mut path_buf);
3871 assert_eq!(path, path_buf);
3872 assert!(path_buf.into_os_string().capacity() >= 15);