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.
20 //! Path manipulation includes both parsing components from slices and building
23 //! To parse a path, you can create a [`Path`] slice from a [`str`]
24 //! slice and start asking questions:
27 //! use std::path::Path;
28 //! use std::ffi::OsStr;
30 //! let path = Path::new("/tmp/foo/bar.txt");
32 //! let parent = path.parent();
33 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
35 //! let file_stem = path.file_stem();
36 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
38 //! let extension = path.extension();
39 //! assert_eq!(extension, Some(OsStr::new("txt")));
42 //! To build or modify paths, use [`PathBuf`]:
45 //! use std::path::PathBuf;
47 //! let mut path = PathBuf::from("c:\\");
48 //! path.push("windows");
49 //! path.push("system32");
50 //! path.set_extension("dll");
53 //! ## Path components and normalization
55 //! The path APIs are built around the notion of "components", which roughly
56 //! correspond to the substrings between path separators (`/` and, on Windows,
57 //! `\`). The APIs for path parsing are largely specified in terms of the path's
58 //! components, so it's important to clearly understand how those are
61 //! A path can always be reconstructed into an *equivalent* path by
62 //! putting together its components via `push`. Syntactically, the
63 //! paths may differ by the normalization described below.
65 //! ### Component types
67 //! Components come in several types:
69 //! * Normal components are the default: standard references to files or
70 //! directories. The path `a/b` has two normal components, `a` and `b`.
72 //! * Current directory components represent the `.` character. For example,
73 //! `./a` has a current directory component and a normal component `a`.
75 //! * The root directory component represents a separator that designates
76 //! starting from root. For example, `/a/b` has a root directory component
77 //! followed by normal components `a` and `b`.
79 //! On Windows, an additional component type comes into play:
81 //! * Prefix components, of which there is a large variety. For example, `C:`
82 //! and `\\server\share` are prefixes. The path `C:windows` has a prefix
83 //! component `C:` and a normal component `windows`; the path `C:\windows` has a
84 //! prefix component `C:`, a root directory component, and a normal component
89 //! Aside from splitting on the separator(s), there is a small amount of
92 //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
95 //! * Occurrences of `.` are normalized away, *except* if they are at
96 //! the beginning of the path (in which case they are often meaningful
97 //! in terms of path searching). So, for example, `a/./b`, `a/b/`,
98 //! `/a/b/.` and `a/b` all have components `a` and `b`, but `./a/b`
99 //! has a leading current directory component.
101 //! No other normalization takes place by default. In particular,
102 //! `a/c` and `a/b/../c` are distinct, to account for the possibility
103 //! that `b` is a symbolic link (so its parent isn't `a`). Further
104 //! normalization is possible to build on top of the components APIs,
105 //! and will be included in this library in the near future.
107 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
108 //! [`Path`]: ../../std/path/struct.Path.html
109 //! [`String`]: ../../std/string/struct.String.html
110 //! [`str`]: ../../std/primitive.str.html
111 //! [`OsString`]: ../../std/ffi/struct.OsString.html
112 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
114 #![stable(feature = "rust1", since = "1.0.0")]
117 use borrow::{Borrow, Cow};
122 use hash::{Hash, Hasher};
124 use iter::{self, FusedIterator};
126 use ops::{self, Deref};
128 use ffi::{OsStr, OsString};
130 use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
132 ////////////////////////////////////////////////////////////////////////////////
134 ////////////////////////////////////////////////////////////////////////////////
136 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
137 // taking advantage of the fact that OsStr always encodes ASCII characters
138 // as-is. Eventually, this transmutation should be replaced by direct uses of
139 // OsStr APIs for parsing, but it will take a while for those to become
142 ////////////////////////////////////////////////////////////////////////////////
144 ////////////////////////////////////////////////////////////////////////////////
146 /// Path prefixes (Windows only).
148 /// Windows uses a variety of path styles, including references to drive
149 /// volumes (like `C:`), network shared folders (like `\\server\share`) and
150 /// others. In addition, some path prefixes are "verbatim", in which case
151 /// `/` is *not* treated as a separator and essentially no normalization is
153 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub enum Prefix<'a> {
156 /// Prefix `\\?\`, together with the given component immediately following it.
157 #[stable(feature = "rust1", since = "1.0.0")]
158 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
160 /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
161 #[stable(feature = "rust1", since = "1.0.0")]
163 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
164 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
167 /// Prefix like `\\?\C:\`, for the given drive letter
168 #[stable(feature = "rust1", since = "1.0.0")]
169 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
171 /// Prefix `\\.\`, together with the given component immediately following it.
172 #[stable(feature = "rust1", since = "1.0.0")]
173 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
175 /// Prefix `\\server\share`, with the given "server" and "share" components.
176 #[stable(feature = "rust1", since = "1.0.0")]
178 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
179 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
182 /// Prefix `C:` for the given disk drive.
183 #[stable(feature = "rust1", since = "1.0.0")]
184 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
187 impl<'a> Prefix<'a> {
189 fn len(&self) -> usize {
191 fn os_str_len(s: &OsStr) -> usize {
192 os_str_as_u8_slice(s).len()
195 Verbatim(x) => 4 + os_str_len(x),
196 VerbatimUNC(x, y) => {
198 if os_str_len(y) > 0 {
204 VerbatimDisk(_) => 6,
207 if os_str_len(y) > 0 {
213 DeviceNS(x) => 4 + os_str_len(x),
219 /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
221 #[stable(feature = "rust1", since = "1.0.0")]
222 pub fn is_verbatim(&self) -> bool {
225 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
231 fn is_drive(&self) -> bool {
233 Prefix::Disk(_) => true,
239 fn has_implicit_root(&self) -> bool {
244 ////////////////////////////////////////////////////////////////////////////////
245 // Exposed parsing helpers
246 ////////////////////////////////////////////////////////////////////////////////
248 /// Determines whether the character is one of the permitted path
249 /// separators for the current platform.
256 /// assert!(path::is_separator('/'));
257 /// assert!(!path::is_separator('❤'));
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn is_separator(c: char) -> bool {
261 c.is_ascii() && is_sep_byte(c as u8)
264 /// The primary separator of path components for the current platform.
266 /// For example, `/` on Unix and `\` on Windows.
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
270 ////////////////////////////////////////////////////////////////////////////////
272 ////////////////////////////////////////////////////////////////////////////////
274 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
275 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
276 // `iter` after having exhausted `prefix`.
277 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
278 where I: Iterator<Item = A> + Clone,
279 J: Iterator<Item = A>,
283 let mut iter_next = iter.clone();
284 match (iter_next.next(), prefix.next()) {
285 (Some(ref x), Some(ref y)) if x == y => (),
286 (Some(_), Some(_)) => return None,
287 (Some(_), None) => return Some(iter),
288 (None, None) => return Some(iter),
289 (None, Some(_)) => return None,
295 // See note at the top of this module to understand why these are used:
296 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
297 unsafe { mem::transmute(s) }
299 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
303 ////////////////////////////////////////////////////////////////////////////////
304 // Cross-platform, iterator-independent parsing
305 ////////////////////////////////////////////////////////////////////////////////
307 /// Says whether the first byte after the prefix is a separator.
308 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
309 let path = if let Some(p) = prefix {
314 !path.is_empty() && is_sep_byte(path[0])
317 // basic workhorse for splitting stem and extension
318 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
320 if os_str_as_u8_slice(file) == b".." {
321 return (Some(file), None);
324 // The unsafety here stems from converting between &OsStr and &[u8]
325 // and back. This is safe to do because (1) we only look at ASCII
326 // contents of the encoding and (2) new &OsStr values are produced
327 // only from ASCII-bounded slices of existing &OsStr values.
329 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
330 let after = iter.next();
331 let before = iter.next();
332 if before == Some(b"") {
335 (before.map(|s| u8_slice_as_os_str(s)),
336 after.map(|s| u8_slice_as_os_str(s)))
341 ////////////////////////////////////////////////////////////////////////////////
342 // The core iterators
343 ////////////////////////////////////////////////////////////////////////////////
345 /// Component parsing works by a double-ended state machine; the cursors at the
346 /// front and back of the path each keep track of what parts of the path have
347 /// been consumed so far.
349 /// Going front to back, a path is made up of a prefix, a starting
350 /// directory component, and a body (of normal components)
351 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
354 StartDir = 1, // / or . or nothing
355 Body = 2, // foo/bar/baz
359 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
361 /// Does not occur on Unix.
362 #[stable(feature = "rust1", since = "1.0.0")]
363 #[derive(Copy, Clone, Eq, Debug)]
364 pub struct PrefixComponent<'a> {
365 /// The prefix as an unparsed `OsStr` slice.
368 /// The parsed prefix data.
372 impl<'a> PrefixComponent<'a> {
373 /// The parsed prefix data.
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn kind(&self) -> Prefix<'a> {
379 /// The raw `OsStr` slice for this prefix.
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn as_os_str(&self) -> &'a OsStr {
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
388 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
389 cmp::PartialEq::eq(&self.parsed, &other.parsed)
393 #[stable(feature = "rust1", since = "1.0.0")]
394 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
395 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
396 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl<'a> cmp::Ord for PrefixComponent<'a> {
402 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
403 cmp::Ord::cmp(&self.parsed, &other.parsed)
407 #[stable(feature = "rust1", since = "1.0.0")]
408 impl<'a> Hash for PrefixComponent<'a> {
409 fn hash<H: Hasher>(&self, h: &mut H) {
414 /// A single component of a path.
416 /// See the module documentation for an in-depth explanation of components and
417 /// their role in the API.
419 /// This `enum` is created from iterating over the [`path::Components`]
425 /// use std::path::{Component, Path};
427 /// let path = Path::new("/tmp/foo/bar.txt");
428 /// let components = path.components().collect::<Vec<_>>();
429 /// assert_eq!(&components, &[
430 /// Component::RootDir,
431 /// Component::Normal("tmp".as_ref()),
432 /// Component::Normal("foo".as_ref()),
433 /// Component::Normal("bar.txt".as_ref()),
437 /// [`path::Components`]: struct.Components.html
438 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub enum Component<'a> {
441 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
443 /// Does not occur on Unix.
444 #[stable(feature = "rust1", since = "1.0.0")]
446 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
449 /// The root directory component, appears after any prefix and before anything else
450 #[stable(feature = "rust1", since = "1.0.0")]
453 /// A reference to the current directory, i.e. `.`
454 #[stable(feature = "rust1", since = "1.0.0")]
457 /// A reference to the parent directory, i.e. `..`
458 #[stable(feature = "rust1", since = "1.0.0")]
461 /// A normal component, i.e. `a` and `b` in `a/b`
462 #[stable(feature = "rust1", since = "1.0.0")]
463 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
466 impl<'a> Component<'a> {
467 /// Extracts the underlying `OsStr` slice.
472 /// use std::path::Path;
474 /// let path = Path::new("./tmp/foo/bar.txt");
475 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
476 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn as_os_str(self) -> &'a OsStr {
481 Component::Prefix(p) => p.as_os_str(),
482 Component::RootDir => OsStr::new(MAIN_SEP_STR),
483 Component::CurDir => OsStr::new("."),
484 Component::ParentDir => OsStr::new(".."),
485 Component::Normal(path) => path,
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl<'a> AsRef<OsStr> for Component<'a> {
492 fn as_ref(&self) -> &OsStr {
497 /// The core iterator giving the components of a path.
499 /// See the module documentation for an in-depth explanation of components and
500 /// their role in the API.
502 /// This `struct` is created by the [`path::Path::components`] method.
507 /// use std::path::Path;
509 /// let path = Path::new("/tmp/foo/bar.txt");
511 /// for component in path.components() {
512 /// println!("{:?}", component);
516 /// [`path::Path::components`]: struct.Path.html#method.components
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub struct Components<'a> {
520 // The path left to parse components from
523 // The prefix as it was originally parsed, if any
524 prefix: Option<Prefix<'a>>,
526 // true if path *physically* has a root separator; for most Windows
527 // prefixes, it may have a "logical" rootseparator for the purposes of
528 // normalization, e.g. \\server\share == \\server\share\.
529 has_physical_root: bool,
531 // The iterator is double-ended, and these two states keep track of what has
532 // been produced from either end
537 /// An iterator over the components of a path, as [`OsStr`] slices.
539 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub struct Iter<'a> {
543 inner: Components<'a>,
546 #[stable(feature = "path_components_debug", since = "1.13.0")]
547 impl<'a> fmt::Debug for Components<'a> {
548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549 struct DebugHelper<'a>(&'a Path);
551 impl<'a> fmt::Debug for DebugHelper<'a> {
552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
554 .entries(self.0.components())
559 f.debug_tuple("Components")
560 .field(&DebugHelper(self.as_path()))
565 impl<'a> Components<'a> {
566 // how long is the prefix, if any?
568 fn prefix_len(&self) -> usize {
569 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
573 fn prefix_verbatim(&self) -> bool {
574 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
577 /// how much of the prefix is left from the point of view of iteration?
579 fn prefix_remaining(&self) -> usize {
580 if self.front == State::Prefix {
587 // Given the iteration so far, how much of the pre-State::Body path is left?
589 fn len_before_body(&self) -> usize {
590 let root = if self.front <= State::StartDir && self.has_physical_root {
595 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
600 self.prefix_remaining() + root + cur_dir
603 // is the iteration complete?
605 fn finished(&self) -> bool {
606 self.front == State::Done || self.back == State::Done || self.front > self.back
610 fn is_sep_byte(&self, b: u8) -> bool {
611 if self.prefix_verbatim() {
618 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
623 /// use std::path::Path;
625 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
626 /// components.next();
627 /// components.next();
629 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn as_path(&self) -> &'a Path {
633 let mut comps = self.clone();
634 if comps.front == State::Body {
637 if comps.back == State::Body {
640 unsafe { Path::from_u8_slice(comps.path) }
643 /// Is the *original* path rooted?
644 fn has_root(&self) -> bool {
645 if self.has_physical_root {
648 if let Some(p) = self.prefix {
649 if p.has_implicit_root() {
656 /// Should the normalized path include a leading . ?
657 fn include_cur_dir(&self) -> bool {
661 let mut iter = self.path[self.prefix_len()..].iter();
662 match (iter.next(), iter.next()) {
663 (Some(&b'.'), None) => true,
664 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
669 // parse a given byte sequence into the corresponding path component
670 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
672 b"." if self.prefix_verbatim() => Some(Component::CurDir),
673 b"." => None, // . components are normalized away, except at
674 // the beginning of a path, which is treated
675 // separately via `include_cur_dir`
676 b".." => Some(Component::ParentDir),
678 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
682 // parse a component from the left, saying how many bytes to consume to
683 // remove the component
684 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
685 debug_assert!(self.front == State::Body);
686 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
687 None => (0, self.path),
688 Some(i) => (1, &self.path[..i]),
690 (comp.len() + extra, self.parse_single_component(comp))
693 // parse a component from the right, saying how many bytes to consume to
694 // remove the component
695 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
696 debug_assert!(self.back == State::Body);
697 let start = self.len_before_body();
698 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
699 None => (0, &self.path[start..]),
700 Some(i) => (1, &self.path[start + i + 1..]),
702 (comp.len() + extra, self.parse_single_component(comp))
705 // trim away repeated separators (i.e. empty components) on the left
706 fn trim_left(&mut self) {
707 while !self.path.is_empty() {
708 let (size, comp) = self.parse_next_component();
712 self.path = &self.path[size..];
717 // trim away repeated separators (i.e. empty components) on the right
718 fn trim_right(&mut self) {
719 while self.path.len() > self.len_before_body() {
720 let (size, comp) = self.parse_next_component_back();
724 self.path = &self.path[..self.path.len() - size];
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<'a> AsRef<Path> for Components<'a> {
732 fn as_ref(&self) -> &Path {
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<'a> AsRef<OsStr> for Components<'a> {
739 fn as_ref(&self) -> &OsStr {
740 self.as_path().as_os_str()
744 #[stable(feature = "path_iter_debug", since = "1.13.0")]
745 impl<'a> fmt::Debug for Iter<'a> {
746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747 struct DebugHelper<'a>(&'a Path);
749 impl<'a> fmt::Debug for DebugHelper<'a> {
750 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
752 .entries(self.0.iter())
757 f.debug_tuple("Iter")
758 .field(&DebugHelper(self.as_path()))
764 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
765 #[stable(feature = "rust1", since = "1.0.0")]
766 pub fn as_path(&self) -> &'a Path {
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl<'a> AsRef<Path> for Iter<'a> {
773 fn as_ref(&self) -> &Path {
778 #[stable(feature = "rust1", since = "1.0.0")]
779 impl<'a> AsRef<OsStr> for Iter<'a> {
780 fn as_ref(&self) -> &OsStr {
781 self.as_path().as_os_str()
785 #[stable(feature = "rust1", since = "1.0.0")]
786 impl<'a> Iterator for Iter<'a> {
787 type Item = &'a OsStr;
789 fn next(&mut self) -> Option<&'a OsStr> {
790 self.inner.next().map(Component::as_os_str)
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl<'a> DoubleEndedIterator for Iter<'a> {
796 fn next_back(&mut self) -> Option<&'a OsStr> {
797 self.inner.next_back().map(Component::as_os_str)
801 #[unstable(feature = "fused", issue = "35602")]
802 impl<'a> FusedIterator for Iter<'a> {}
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl<'a> Iterator for Components<'a> {
806 type Item = Component<'a>;
808 fn next(&mut self) -> Option<Component<'a>> {
809 while !self.finished() {
811 State::Prefix if self.prefix_len() > 0 => {
812 self.front = State::StartDir;
813 debug_assert!(self.prefix_len() <= self.path.len());
814 let raw = &self.path[..self.prefix_len()];
815 self.path = &self.path[self.prefix_len()..];
816 return Some(Component::Prefix(PrefixComponent {
817 raw: unsafe { u8_slice_as_os_str(raw) },
818 parsed: self.prefix.unwrap(),
822 self.front = State::StartDir;
825 self.front = State::Body;
826 if self.has_physical_root {
827 debug_assert!(!self.path.is_empty());
828 self.path = &self.path[1..];
829 return Some(Component::RootDir);
830 } else if let Some(p) = self.prefix {
831 if p.has_implicit_root() && !p.is_verbatim() {
832 return Some(Component::RootDir);
834 } else if self.include_cur_dir() {
835 debug_assert!(!self.path.is_empty());
836 self.path = &self.path[1..];
837 return Some(Component::CurDir);
840 State::Body if !self.path.is_empty() => {
841 let (size, comp) = self.parse_next_component();
842 self.path = &self.path[size..];
848 self.front = State::Done;
850 State::Done => unreachable!(),
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<'a> DoubleEndedIterator for Components<'a> {
859 fn next_back(&mut self) -> Option<Component<'a>> {
860 while !self.finished() {
862 State::Body if self.path.len() > self.len_before_body() => {
863 let (size, comp) = self.parse_next_component_back();
864 self.path = &self.path[..self.path.len() - size];
870 self.back = State::StartDir;
873 self.back = State::Prefix;
874 if self.has_physical_root {
875 self.path = &self.path[..self.path.len() - 1];
876 return Some(Component::RootDir);
877 } else if let Some(p) = self.prefix {
878 if p.has_implicit_root() && !p.is_verbatim() {
879 return Some(Component::RootDir);
881 } else if self.include_cur_dir() {
882 self.path = &self.path[..self.path.len() - 1];
883 return Some(Component::CurDir);
886 State::Prefix if self.prefix_len() > 0 => {
887 self.back = State::Done;
888 return Some(Component::Prefix(PrefixComponent {
889 raw: unsafe { u8_slice_as_os_str(self.path) },
890 parsed: self.prefix.unwrap(),
894 self.back = State::Done;
897 State::Done => unreachable!(),
904 #[unstable(feature = "fused", issue = "35602")]
905 impl<'a> FusedIterator for Components<'a> {}
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<'a> cmp::PartialEq for Components<'a> {
909 fn eq(&self, other: &Components<'a>) -> bool {
910 Iterator::eq(self.clone(), other.clone())
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<'a> cmp::Eq for Components<'a> {}
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<'a> cmp::PartialOrd for Components<'a> {
919 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
920 Iterator::partial_cmp(self.clone(), other.clone())
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<'a> cmp::Ord for Components<'a> {
926 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
927 Iterator::cmp(self.clone(), other.clone())
931 ////////////////////////////////////////////////////////////////////////////////
932 // Basic types and traits
933 ////////////////////////////////////////////////////////////////////////////////
935 /// An owned, mutable path (akin to [`String`]).
937 /// This type provides methods like [`push`] and [`set_extension`] that mutate
938 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
939 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
941 /// [`String`]: ../string/struct.String.html
942 /// [`Path`]: struct.Path.html
943 /// [`push`]: struct.PathBuf.html#method.push
944 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
945 /// [`Deref`]: ../ops/trait.Deref.html
947 /// More details about the overall approach can be found in
948 /// the module documentation.
953 /// use std::path::PathBuf;
955 /// let mut path = PathBuf::from("c:\\");
956 /// path.push("windows");
957 /// path.push("system32");
958 /// path.set_extension("dll");
961 #[stable(feature = "rust1", since = "1.0.0")]
967 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
968 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
971 /// Allocates an empty `PathBuf`.
976 /// use std::path::PathBuf;
978 /// let path = PathBuf::new();
980 #[stable(feature = "rust1", since = "1.0.0")]
981 pub fn new() -> PathBuf {
982 PathBuf { inner: OsString::new() }
985 /// Coerces to a [`Path`] slice.
987 /// [`Path`]: struct.Path.html
992 /// use std::path::{Path, PathBuf};
994 /// let p = PathBuf::from("/test");
995 /// assert_eq!(Path::new("/test"), p.as_path());
997 #[stable(feature = "rust1", since = "1.0.0")]
998 pub fn as_path(&self) -> &Path {
1002 /// Extends `self` with `path`.
1004 /// If `path` is absolute, it replaces the current path.
1008 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1009 /// replaces everything except for the prefix (if any) of `self`.
1010 /// * if `path` has a prefix but no root, it replaces `self`.
1014 /// Pushing a relative path extends the existing path:
1017 /// use std::path::PathBuf;
1019 /// let mut path = PathBuf::from("/tmp");
1020 /// path.push("file.bk");
1021 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1024 /// Pushing an absolute path replaces the existing path:
1027 /// use std::path::PathBuf;
1029 /// let mut path = PathBuf::from("/tmp");
1030 /// path.push("/etc");
1031 /// assert_eq!(path, PathBuf::from("/etc"));
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1035 self._push(path.as_ref())
1038 fn _push(&mut self, path: &Path) {
1039 // in general, a separator is needed if the rightmost byte is not a separator
1040 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1042 // in the special case of `C:` on Windows, do *not* add a separator
1044 let comps = self.components();
1045 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1046 comps.prefix.unwrap().is_drive() {
1051 // absolute `path` replaces `self`
1052 if path.is_absolute() || path.prefix().is_some() {
1053 self.as_mut_vec().truncate(0);
1055 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1056 } else if path.has_root() {
1057 let prefix_len = self.components().prefix_remaining();
1058 self.as_mut_vec().truncate(prefix_len);
1060 // `path` is a pure relative path
1061 } else if need_sep {
1062 self.inner.push(MAIN_SEP_STR);
1065 self.inner.push(path);
1068 /// Truncate `self` to [`self.parent()`].
1070 /// Returns false and does nothing if [`self.file_name()`] is `None`.
1071 /// Otherwise, returns `true`.
1073 /// [`self.parent()`]: struct.PathBuf.html#method.parent
1074 /// [`self.file_name()`]: struct.PathBuf.html#method.file_name
1079 /// use std::path::{Path, PathBuf};
1081 /// let mut p = PathBuf::from("/test/test.rs");
1084 /// assert_eq!(Path::new("/test"), p);
1086 /// assert_eq!(Path::new("/"), p);
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub fn pop(&mut self) -> bool {
1090 match self.parent().map(|p| p.as_u8_slice().len()) {
1092 self.as_mut_vec().truncate(len);
1099 /// Updates [`self.file_name()`] to `file_name`.
1101 /// If [`self.file_name()`] was [`None`], this is equivalent to pushing
1104 /// [`self.file_name()`]: struct.PathBuf.html#method.file_name
1105 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1110 /// use std::path::PathBuf;
1112 /// let mut buf = PathBuf::from("/");
1113 /// assert!(buf.file_name() == None);
1114 /// buf.set_file_name("bar");
1115 /// assert!(buf == PathBuf::from("/bar"));
1116 /// assert!(buf.file_name().is_some());
1117 /// buf.set_file_name("baz.txt");
1118 /// assert!(buf == PathBuf::from("/baz.txt"));
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1122 self._set_file_name(file_name.as_ref())
1125 fn _set_file_name(&mut self, file_name: &OsStr) {
1126 if self.file_name().is_some() {
1127 let popped = self.pop();
1128 debug_assert!(popped);
1130 self.push(file_name);
1133 /// Updates [`self.extension()`] to `extension`.
1135 /// If [`self.file_name()`] is `None`, does nothing and returns `false`.
1137 /// Otherwise, returns `true`; if [`self.extension()`] is [`None`], the
1138 /// extension is added; otherwise it is replaced.
1140 /// [`self.file_name()`]: struct.PathBuf.html#method.file_name
1141 /// [`self.extension()`]: struct.PathBuf.html#method.extension
1142 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1147 /// use std::path::{Path, PathBuf};
1149 /// let mut p = PathBuf::from("/feel/the");
1151 /// p.set_extension("force");
1152 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1154 /// p.set_extension("dark_side");
1155 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1159 self._set_extension(extension.as_ref())
1162 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1163 if self.file_name().is_none() {
1167 let mut stem = match self.file_stem() {
1168 Some(stem) => stem.to_os_string(),
1169 None => OsString::new(),
1172 if !os_str_as_u8_slice(extension).is_empty() {
1174 stem.push(extension);
1176 self.set_file_name(&stem);
1181 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1183 /// [`OsString`]: ../ffi/struct.OsString.html
1188 /// use std::path::PathBuf;
1190 /// let p = PathBuf::from("/the/head");
1191 /// let os_str = p.into_os_string();
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub fn into_os_string(self) -> OsString {
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1201 fn from(s: &'a T) -> PathBuf {
1202 PathBuf::from(s.as_ref().to_os_string())
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 impl From<OsString> for PathBuf {
1208 fn from(s: OsString) -> PathBuf {
1209 PathBuf { inner: s }
1213 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1214 impl From<PathBuf> for OsString {
1215 fn from(path_buf : PathBuf) -> OsString {
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl From<String> for PathBuf {
1222 fn from(s: String) -> PathBuf {
1223 PathBuf::from(OsString::from(s))
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1229 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1230 let mut buf = PathBuf::new();
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1238 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1240 self.push(p.as_ref())
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 impl fmt::Debug for PathBuf {
1247 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1248 fmt::Debug::fmt(&**self, formatter)
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl ops::Deref for PathBuf {
1256 fn deref(&self) -> &Path {
1257 Path::new(&self.inner)
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl Borrow<Path> for PathBuf {
1263 fn borrow(&self) -> &Path {
1268 #[stable(feature = "cow_from_path", since = "1.6.0")]
1269 impl<'a> From<&'a Path> for Cow<'a, Path> {
1271 fn from(s: &'a Path) -> Cow<'a, Path> {
1276 #[stable(feature = "cow_from_path", since = "1.6.0")]
1277 impl<'a> From<PathBuf> for Cow<'a, Path> {
1279 fn from(s: PathBuf) -> Cow<'a, Path> {
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 impl ToOwned for Path {
1286 type Owned = PathBuf;
1287 fn to_owned(&self) -> PathBuf {
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl cmp::PartialEq for PathBuf {
1294 fn eq(&self, other: &PathBuf) -> bool {
1295 self.components() == other.components()
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl Hash for PathBuf {
1301 fn hash<H: Hasher>(&self, h: &mut H) {
1302 self.as_path().hash(h)
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl cmp::Eq for PathBuf {}
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 impl cmp::PartialOrd for PathBuf {
1311 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1312 self.components().partial_cmp(other.components())
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl cmp::Ord for PathBuf {
1318 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1319 self.components().cmp(other.components())
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl AsRef<OsStr> for PathBuf {
1325 fn as_ref(&self) -> &OsStr {
1330 /// A slice of a path (akin to [`str`]).
1332 /// This type supports a number of operations for inspecting a path, including
1333 /// breaking the path into its components (separated by `/` or `\`, depending on
1334 /// the platform), extracting the file name, determining whether the path is
1335 /// absolute, and so on.
1337 /// This is an *unsized* type, meaning that it must always be used behind a
1338 /// pointer like `&` or [`Box`]. For an owned version of this type,
1339 /// see [`PathBuf`].
1341 /// [`str`]: ../primitive.str.html
1342 /// [`Box`]: ../boxed/struct.Box.html
1343 /// [`PathBuf`]: struct.PathBuf.html
1345 /// More details about the overall approach can be found in
1346 /// the module documentation.
1351 /// use std::path::Path;
1352 /// use std::ffi::OsStr;
1354 /// let path = Path::new("/tmp/foo/bar.txt");
1356 /// let parent = path.parent();
1357 /// assert_eq!(parent, Some(Path::new("/tmp/foo")));
1359 /// let file_stem = path.file_stem();
1360 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1362 /// let extension = path.extension();
1363 /// assert_eq!(extension, Some(OsStr::new("txt")));
1365 #[stable(feature = "rust1", since = "1.0.0")]
1370 /// An error returned from the [`Path::strip_prefix`] method indicating that the
1371 /// prefix was not found in `self`.
1373 /// [`Path::strip_prefix`]: struct.Path.html#method.strip_prefix
1374 #[derive(Debug, Clone, PartialEq, Eq)]
1375 #[stable(since = "1.7.0", feature = "strip_prefix")]
1376 pub struct StripPrefixError(());
1379 // The following (private!) function allows construction of a path from a u8
1380 // slice, which is only safe when it is known to follow the OsStr encoding.
1381 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1382 Path::new(u8_slice_as_os_str(s))
1384 // The following (private!) function reveals the byte encoding used for OsStr.
1385 fn as_u8_slice(&self) -> &[u8] {
1386 os_str_as_u8_slice(&self.inner)
1389 /// Directly wrap a string slice as a `Path` slice.
1391 /// This is a cost-free conversion.
1396 /// use std::path::Path;
1398 /// Path::new("foo.txt");
1401 /// You can create `Path`s from `String`s, or even other `Path`s:
1404 /// use std::path::Path;
1406 /// let string = String::from("foo.txt");
1407 /// let from_string = Path::new(&string);
1408 /// let from_path = Path::new(&from_string);
1409 /// assert_eq!(from_string, from_path);
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1413 unsafe { mem::transmute(s.as_ref()) }
1416 /// Yields the underlying [`OsStr`] slice.
1418 /// [`OsStr`]: ../ffi/struct.OsStr.html
1423 /// use std::path::Path;
1425 /// let os_str = Path::new("foo.txt").as_os_str();
1426 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 pub fn as_os_str(&self) -> &OsStr {
1433 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1435 /// This conversion may entail doing a check for UTF-8 validity.
1437 /// [`&str`]: ../primitive.str.html
1442 /// use std::path::Path;
1444 /// let path = Path::new("foo.txt");
1445 /// assert_eq!(path.to_str(), Some("foo.txt"));
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub fn to_str(&self) -> Option<&str> {
1452 /// Converts a `Path` to a [`Cow<str>`].
1454 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1456 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1460 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1463 /// use std::path::Path;
1465 /// let path = Path::new("foo.txt");
1466 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1469 /// Had `os_str` contained invalid unicode, the `to_string_lossy` call might
1470 /// have returned `"fo�.txt"`.
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 pub fn to_string_lossy(&self) -> Cow<str> {
1473 self.inner.to_string_lossy()
1476 /// Converts a `Path` to an owned [`PathBuf`].
1478 /// [`PathBuf`]: struct.PathBuf.html
1483 /// use std::path::Path;
1485 /// let path_buf = Path::new("foo.txt").to_path_buf();
1486 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 pub fn to_path_buf(&self) -> PathBuf {
1490 PathBuf::from(self.inner.to_os_string())
1493 /// A path is *absolute* if it is independent of the current directory.
1495 /// * On Unix, a path is absolute if it starts with the root, so
1496 /// `is_absolute` and `has_root` are equivalent.
1498 /// * On Windows, a path is absolute if it has a prefix and starts with the
1499 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1504 /// use std::path::Path;
1506 /// assert!(!Path::new("foo.txt").is_absolute());
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 #[allow(deprecated)]
1510 pub fn is_absolute(&self) -> bool {
1511 // FIXME: Remove target_os = "redox" and allow Redox prefixes
1512 self.has_root() && (cfg!(unix) || cfg!(target_os = "redox") || self.prefix().is_some())
1515 /// A path is *relative* if it is not absolute.
1520 /// use std::path::Path;
1522 /// assert!(Path::new("foo.txt").is_relative());
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 pub fn is_relative(&self) -> bool {
1529 fn prefix(&self) -> Option<Prefix> {
1530 self.components().prefix
1533 /// A path has a root if the body of the path begins with the directory separator.
1535 /// * On Unix, a path has a root if it begins with `/`.
1537 /// * On Windows, a path has a root if it:
1538 /// * has no prefix and begins with a separator, e.g. `\\windows`
1539 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1540 /// * has any non-disk prefix, e.g. `\\server\share`
1545 /// use std::path::Path;
1547 /// assert!(Path::new("/etc/passwd").has_root());
1549 #[stable(feature = "rust1", since = "1.0.0")]
1550 pub fn has_root(&self) -> bool {
1551 self.components().has_root()
1554 /// The path without its final component, if any.
1556 /// Returns [`None`] if the path terminates in a root or prefix.
1558 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1563 /// use std::path::Path;
1565 /// let path = Path::new("/foo/bar");
1566 /// let parent = path.parent().unwrap();
1567 /// assert_eq!(parent, Path::new("/foo"));
1569 /// let grand_parent = parent.parent().unwrap();
1570 /// assert_eq!(grand_parent, Path::new("/"));
1571 /// assert_eq!(grand_parent.parent(), None);
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 pub fn parent(&self) -> Option<&Path> {
1575 let mut comps = self.components();
1576 let comp = comps.next_back();
1579 Component::Normal(_) |
1581 Component::ParentDir => Some(comps.as_path()),
1587 /// The final component of the path, if it is a normal file.
1589 /// If the path terminates in `..`, `file_name` will return [`None`].
1591 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1596 /// use std::path::Path;
1597 /// use std::ffi::OsStr;
1599 /// let path = Path::new("foo.txt");
1600 /// let os_str = OsStr::new("foo.txt");
1602 /// assert_eq!(Some(os_str), path.file_name());
1605 /// # Other examples
1608 /// use std::path::Path;
1609 /// use std::ffi::OsStr;
1611 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1612 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1613 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 pub fn file_name(&self) -> Option<&OsStr> {
1617 self.components().next_back().and_then(|p| {
1619 Component::Normal(p) => Some(p.as_ref()),
1625 /// Returns a path that, when joined onto `base`, yields `self`.
1629 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1630 /// returns `false`), returns [`Err`].
1632 /// [`starts_with`]: #method.starts_with
1633 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1638 /// use std::path::Path;
1640 /// let path = Path::new("/test/haha/foo.txt");
1642 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1643 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1644 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1646 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1647 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1648 -> Result<&'a Path, StripPrefixError>
1649 where P: AsRef<Path>
1651 self._strip_prefix(base.as_ref())
1654 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1655 -> Result<&'a Path, StripPrefixError> {
1656 iter_after(self.components(), base.components())
1657 .map(|c| c.as_path())
1658 .ok_or(StripPrefixError(()))
1661 /// Determines whether `base` is a prefix of `self`.
1663 /// Only considers whole path components to match.
1668 /// use std::path::Path;
1670 /// let path = Path::new("/etc/passwd");
1672 /// assert!(path.starts_with("/etc"));
1674 /// assert!(!path.starts_with("/e"));
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1678 self._starts_with(base.as_ref())
1681 fn _starts_with(&self, base: &Path) -> bool {
1682 iter_after(self.components(), base.components()).is_some()
1685 /// Determines whether `child` is a suffix of `self`.
1687 /// Only considers whole path components to match.
1692 /// use std::path::Path;
1694 /// let path = Path::new("/etc/passwd");
1696 /// assert!(path.ends_with("passwd"));
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1700 self._ends_with(child.as_ref())
1703 fn _ends_with(&self, child: &Path) -> bool {
1704 iter_after(self.components().rev(), child.components().rev()).is_some()
1707 /// Extracts the stem (non-extension) portion of [`self.file_name()`].
1709 /// [`self.file_name()`]: struct.Path.html#method.file_name
1713 /// * [`None`], if there is no file name;
1714 /// * The entire file name if there is no embedded `.`;
1715 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1716 /// * Otherwise, the portion of the file name before the final `.`
1718 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1723 /// use std::path::Path;
1725 /// let path = Path::new("foo.rs");
1727 /// assert_eq!("foo", path.file_stem().unwrap());
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 pub fn file_stem(&self) -> Option<&OsStr> {
1731 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1734 /// Extracts the extension of [`self.file_name()`], if possible.
1736 /// The extension is:
1738 /// * [`None`], if there is no file name;
1739 /// * [`None`], if there is no embedded `.`;
1740 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1741 /// * Otherwise, the portion of the file name after the final `.`
1743 /// [`self.file_name()`]: struct.Path.html#method.file_name
1744 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1749 /// use std::path::Path;
1751 /// let path = Path::new("foo.rs");
1753 /// assert_eq!("rs", path.extension().unwrap());
1755 #[stable(feature = "rust1", since = "1.0.0")]
1756 pub fn extension(&self) -> Option<&OsStr> {
1757 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1760 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1762 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1764 /// [`PathBuf`]: struct.PathBuf.html
1765 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1770 /// use std::path::{Path, PathBuf};
1772 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1776 self._join(path.as_ref())
1779 fn _join(&self, path: &Path) -> PathBuf {
1780 let mut buf = self.to_path_buf();
1785 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1787 /// See [`PathBuf::set_file_name`] for more details.
1789 /// [`PathBuf`]: struct.PathBuf.html
1790 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1795 /// use std::path::{Path, PathBuf};
1797 /// let path = Path::new("/tmp/foo.txt");
1798 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1800 #[stable(feature = "rust1", since = "1.0.0")]
1801 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1802 self._with_file_name(file_name.as_ref())
1805 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1806 let mut buf = self.to_path_buf();
1807 buf.set_file_name(file_name);
1811 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
1813 /// See [`PathBuf::set_extension`] for more details.
1815 /// [`PathBuf`]: struct.PathBuf.html
1816 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
1821 /// use std::path::{Path, PathBuf};
1823 /// let path = Path::new("foo.rs");
1824 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1828 self._with_extension(extension.as_ref())
1831 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1832 let mut buf = self.to_path_buf();
1833 buf.set_extension(extension);
1837 /// Produce an iterator over the components of the path.
1842 /// use std::path::{Path, Component};
1843 /// use std::ffi::OsStr;
1845 /// let mut components = Path::new("/tmp/foo.txt").components();
1847 /// assert_eq!(components.next(), Some(Component::RootDir));
1848 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1849 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1850 /// assert_eq!(components.next(), None)
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 pub fn components(&self) -> Components {
1854 let prefix = parse_prefix(self.as_os_str());
1856 path: self.as_u8_slice(),
1858 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1859 front: State::Prefix,
1864 /// Produce an iterator over the path's components viewed as [`OsStr`] slices.
1866 /// [`OsStr`]: ../ffi/struct.OsStr.html
1871 /// use std::path::{self, Path};
1872 /// use std::ffi::OsStr;
1874 /// let mut it = Path::new("/tmp/foo.txt").iter();
1875 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1876 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1877 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1878 /// assert_eq!(it.next(), None)
1880 #[stable(feature = "rust1", since = "1.0.0")]
1881 pub fn iter(&self) -> Iter {
1882 Iter { inner: self.components() }
1885 /// Returns an object that implements [`Display`] for safely printing paths
1886 /// that may contain non-Unicode data.
1888 /// [`Display`]: ../fmt/trait.Display.html
1893 /// use std::path::Path;
1895 /// let path = Path::new("/tmp/foo.rs");
1897 /// println!("{}", path.display());
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 pub fn display(&self) -> Display {
1901 Display { path: self }
1904 /// Query the file system to get information about a file, directory, etc.
1906 /// This function will traverse symbolic links to query information about the
1907 /// destination file.
1909 /// This is an alias to [`fs::metadata`].
1911 /// [`fs::metadata`]: ../fs/fn.metadata.html
1916 /// use std::path::Path;
1918 /// let path = Path::new("/Minas/tirith");
1919 /// let metadata = path.metadata().expect("metadata call failed");
1920 /// println!("{:?}", metadata.file_type());
1922 #[stable(feature = "path_ext", since = "1.5.0")]
1923 pub fn metadata(&self) -> io::Result<fs::Metadata> {
1927 /// Query the metadata about a file without following symlinks.
1929 /// This is an alias to [`fs::symlink_metadata`].
1931 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
1936 /// use std::path::Path;
1938 /// let path = Path::new("/Minas/tirith");
1939 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
1940 /// println!("{:?}", metadata.file_type());
1942 #[stable(feature = "path_ext", since = "1.5.0")]
1943 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1944 fs::symlink_metadata(self)
1947 /// Returns the canonical form of the path with all intermediate components
1948 /// normalized and symbolic links resolved.
1950 /// This is an alias to [`fs::canonicalize`].
1952 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
1957 /// use std::path::{Path, PathBuf};
1959 /// let path = Path::new("/foo/test/../test/bar.rs");
1960 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
1962 #[stable(feature = "path_ext", since = "1.5.0")]
1963 pub fn canonicalize(&self) -> io::Result<PathBuf> {
1964 fs::canonicalize(self)
1967 /// Reads a symbolic link, returning the file that the link points to.
1969 /// This is an alias to [`fs::read_link`].
1971 /// [`fs::read_link`]: ../fs/fn.read_link.html
1976 /// use std::path::Path;
1978 /// let path = Path::new("/laputa/sky_castle.rs");
1979 /// let path_link = path.read_link().expect("read_link call failed");
1981 #[stable(feature = "path_ext", since = "1.5.0")]
1982 pub fn read_link(&self) -> io::Result<PathBuf> {
1986 /// Returns an iterator over the entries within a directory.
1988 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
1989 /// errors may be encountered after an iterator is initially constructed.
1991 /// This is an alias to [`fs::read_dir`].
1993 /// [`io::Result`]: ../io/type.Result.html
1994 /// [`DirEntry`]: ../fs/struct.DirEntry.html
1995 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2000 /// use std::path::Path;
2002 /// let path = Path::new("/laputa");
2003 /// for entry in path.read_dir().expect("read_dir call failed") {
2004 /// if let Ok(entry) = entry {
2005 /// println!("{:?}", entry.path());
2009 #[stable(feature = "path_ext", since = "1.5.0")]
2010 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2014 /// Returns whether the path points at an existing entity.
2016 /// This function will traverse symbolic links to query information about the
2017 /// destination file. In case of broken symbolic links this will return `false`.
2022 /// use std::path::Path;
2023 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2025 #[stable(feature = "path_ext", since = "1.5.0")]
2026 pub fn exists(&self) -> bool {
2027 fs::metadata(self).is_ok()
2030 /// Returns whether the path is pointing at a regular file.
2032 /// This function will traverse symbolic links to query information about the
2033 /// destination file. In case of broken symbolic links this will return `false`.
2038 /// use std::path::Path;
2039 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2040 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2042 #[stable(feature = "path_ext", since = "1.5.0")]
2043 pub fn is_file(&self) -> bool {
2044 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2047 /// Returns whether the path is pointing at a directory.
2049 /// This function will traverse symbolic links to query information about the
2050 /// destination file. In case of broken symbolic links this will return `false`.
2055 /// use std::path::Path;
2056 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2057 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2059 #[stable(feature = "path_ext", since = "1.5.0")]
2060 pub fn is_dir(&self) -> bool {
2061 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 impl AsRef<OsStr> for Path {
2067 fn as_ref(&self) -> &OsStr {
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl fmt::Debug for Path {
2074 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2075 self.inner.fmt(formatter)
2079 /// Helper struct for safely printing paths with `format!()` and `{}`
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 pub struct Display<'a> {
2085 #[stable(feature = "rust1", since = "1.0.0")]
2086 impl<'a> fmt::Debug for Display<'a> {
2087 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2088 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl<'a> fmt::Display for Display<'a> {
2094 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2095 fmt::Display::fmt(&self.path.to_string_lossy(), f)
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 impl cmp::PartialEq for Path {
2101 fn eq(&self, other: &Path) -> bool {
2102 self.components().eq(other.components())
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl Hash for Path {
2108 fn hash<H: Hasher>(&self, h: &mut H) {
2109 for component in self.components() {
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 impl cmp::Eq for Path {}
2118 #[stable(feature = "rust1", since = "1.0.0")]
2119 impl cmp::PartialOrd for Path {
2120 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2121 self.components().partial_cmp(other.components())
2125 #[stable(feature = "rust1", since = "1.0.0")]
2126 impl cmp::Ord for Path {
2127 fn cmp(&self, other: &Path) -> cmp::Ordering {
2128 self.components().cmp(other.components())
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl AsRef<Path> for Path {
2134 fn as_ref(&self) -> &Path {
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 impl AsRef<Path> for OsStr {
2141 fn as_ref(&self) -> &Path {
2146 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2147 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2148 fn as_ref(&self) -> &Path {
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 impl AsRef<Path> for OsString {
2155 fn as_ref(&self) -> &Path {
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl AsRef<Path> for str {
2162 fn as_ref(&self) -> &Path {
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 impl AsRef<Path> for String {
2169 fn as_ref(&self) -> &Path {
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 impl AsRef<Path> for PathBuf {
2176 fn as_ref(&self) -> &Path {
2181 #[stable(feature = "path_into_iter", since = "1.6.0")]
2182 impl<'a> IntoIterator for &'a PathBuf {
2183 type Item = &'a OsStr;
2184 type IntoIter = Iter<'a>;
2185 fn into_iter(self) -> Iter<'a> { self.iter() }
2188 #[stable(feature = "path_into_iter", since = "1.6.0")]
2189 impl<'a> IntoIterator for &'a Path {
2190 type Item = &'a OsStr;
2191 type IntoIter = Iter<'a>;
2192 fn into_iter(self) -> Iter<'a> { self.iter() }
2195 macro_rules! impl_cmp {
2196 ($lhs:ty, $rhs: ty) => {
2197 #[stable(feature = "partialeq_path", since = "1.6.0")]
2198 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2200 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2203 #[stable(feature = "partialeq_path", since = "1.6.0")]
2204 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2206 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2209 #[stable(feature = "cmp_path", since = "1.8.0")]
2210 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2212 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2213 <Path as PartialOrd>::partial_cmp(self, other)
2217 #[stable(feature = "cmp_path", since = "1.8.0")]
2218 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2220 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2221 <Path as PartialOrd>::partial_cmp(self, other)
2227 impl_cmp!(PathBuf, Path);
2228 impl_cmp!(PathBuf, &'a Path);
2229 impl_cmp!(Cow<'a, Path>, Path);
2230 impl_cmp!(Cow<'a, Path>, &'b Path);
2231 impl_cmp!(Cow<'a, Path>, PathBuf);
2233 macro_rules! impl_cmp_os_str {
2234 ($lhs:ty, $rhs: ty) => {
2235 #[stable(feature = "cmp_path", since = "1.8.0")]
2236 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2238 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2241 #[stable(feature = "cmp_path", since = "1.8.0")]
2242 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2244 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2247 #[stable(feature = "cmp_path", since = "1.8.0")]
2248 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2250 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2251 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2255 #[stable(feature = "cmp_path", since = "1.8.0")]
2256 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2258 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2259 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2265 impl_cmp_os_str!(PathBuf, OsStr);
2266 impl_cmp_os_str!(PathBuf, &'a OsStr);
2267 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2268 impl_cmp_os_str!(PathBuf, OsString);
2269 impl_cmp_os_str!(Path, OsStr);
2270 impl_cmp_os_str!(Path, &'a OsStr);
2271 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2272 impl_cmp_os_str!(Path, OsString);
2273 impl_cmp_os_str!(&'a Path, OsStr);
2274 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2275 impl_cmp_os_str!(&'a Path, OsString);
2276 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2277 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2278 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2280 #[stable(since = "1.7.0", feature = "strip_prefix")]
2281 impl fmt::Display for StripPrefixError {
2282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2283 self.description().fmt(f)
2287 #[stable(since = "1.7.0", feature = "strip_prefix")]
2288 impl Error for StripPrefixError {
2289 fn description(&self) -> &str { "prefix not found" }
2297 ($path:expr, iter: $iter:expr) => (
2299 let path = Path::new($path);
2301 // Forward iteration
2302 let comps = path.iter()
2303 .map(|p| p.to_string_lossy().into_owned())
2304 .collect::<Vec<String>>();
2305 let exp: &[&str] = &$iter;
2306 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2307 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2310 // Reverse iteration
2311 let comps = Path::new($path).iter().rev()
2312 .map(|p| p.to_string_lossy().into_owned())
2313 .collect::<Vec<String>>();
2314 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2315 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2320 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2322 let path = Path::new($path);
2324 let act_root = path.has_root();
2325 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2326 $has_root, act_root);
2328 let act_abs = path.is_absolute();
2329 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2330 $is_absolute, act_abs);
2334 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2336 let path = Path::new($path);
2338 let parent = path.parent().map(|p| p.to_str().unwrap());
2339 let exp_parent: Option<&str> = $parent;
2340 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2341 exp_parent, parent);
2343 let file = path.file_name().map(|p| p.to_str().unwrap());
2344 let exp_file: Option<&str> = $file;
2345 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2350 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2352 let path = Path::new($path);
2354 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2355 let exp_stem: Option<&str> = $file_stem;
2356 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2359 let ext = path.extension().map(|p| p.to_str().unwrap());
2360 let exp_ext: Option<&str> = $extension;
2361 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2366 ($path:expr, iter: $iter:expr,
2367 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2368 parent: $parent:expr, file_name: $file:expr,
2369 file_stem: $file_stem:expr, extension: $extension:expr) => (
2371 t!($path, iter: $iter);
2372 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2373 t!($path, parent: $parent, file_name: $file);
2374 t!($path, file_stem: $file_stem, extension: $extension);
2383 let static_path = Path::new("/home/foo");
2384 let static_cow_path: Cow<'static, Path> = static_path.into();
2385 let pathbuf = PathBuf::from("/home/foo");
2388 let path: &Path = &pathbuf;
2389 let borrowed_cow_path: Cow<Path> = path.into();
2391 assert_eq!(static_cow_path, borrowed_cow_path);
2394 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2396 assert_eq!(static_cow_path, owned_cow_path);
2401 pub fn test_decompositions_unix() {
2417 file_name: Some("foo"),
2418 file_stem: Some("foo"),
2437 file_name: Some("foo"),
2438 file_stem: Some("foo"),
2447 file_name: Some("foo"),
2448 file_stem: Some("foo"),
2457 file_name: Some("foo"),
2458 file_stem: Some("foo"),
2463 iter: ["foo", "bar"],
2466 parent: Some("foo"),
2467 file_name: Some("bar"),
2468 file_stem: Some("bar"),
2473 iter: ["/", "foo", "bar"],
2476 parent: Some("/foo"),
2477 file_name: Some("bar"),
2478 file_stem: Some("bar"),
2487 file_name: Some("foo"),
2488 file_stem: Some("foo"),
2493 iter: ["/", "foo", "bar"],
2496 parent: Some("///foo"),
2497 file_name: Some("bar"),
2498 file_stem: Some("bar"),
2537 file_name: Some("foo"),
2538 file_stem: Some("foo"),
2543 iter: ["foo", ".."],
2546 parent: Some("foo"),
2557 file_name: Some("foo"),
2558 file_stem: Some("foo"),
2563 iter: ["foo", "bar"],
2566 parent: Some("foo"),
2567 file_name: Some("bar"),
2568 file_stem: Some("bar"),
2573 iter: ["foo", ".."],
2576 parent: Some("foo"),
2583 iter: ["foo", "..", "bar"],
2586 parent: Some("foo/.."),
2587 file_name: Some("bar"),
2588 file_stem: Some("bar"),
2597 file_name: Some("a"),
2598 file_stem: Some("a"),
2627 file_name: Some("b"),
2628 file_stem: Some("b"),
2637 file_name: Some("b"),
2638 file_stem: Some("b"),
2647 file_name: Some("b"),
2648 file_stem: Some("b"),
2653 iter: ["a", "b", "c"],
2656 parent: Some("a/b"),
2657 file_name: Some("c"),
2658 file_stem: Some("c"),
2667 file_name: Some(".foo"),
2668 file_stem: Some(".foo"),
2675 pub fn test_decompositions_windows() {
2691 file_name: Some("foo"),
2692 file_stem: Some("foo"),
2747 iter: ["\\", "foo"],
2751 file_name: Some("foo"),
2752 file_stem: Some("foo"),
2761 file_name: Some("foo"),
2762 file_stem: Some("foo"),
2767 iter: ["\\", "foo"],
2771 file_name: Some("foo"),
2772 file_stem: Some("foo"),
2777 iter: ["foo", "bar"],
2780 parent: Some("foo"),
2781 file_name: Some("bar"),
2782 file_stem: Some("bar"),
2787 iter: ["\\", "foo", "bar"],
2790 parent: Some("/foo"),
2791 file_name: Some("bar"),
2792 file_stem: Some("bar"),
2797 iter: ["\\", "foo"],
2801 file_name: Some("foo"),
2802 file_stem: Some("foo"),
2807 iter: ["\\", "foo", "bar"],
2810 parent: Some("///foo"),
2811 file_name: Some("bar"),
2812 file_stem: Some("bar"),
2851 file_name: Some("foo"),
2852 file_stem: Some("foo"),
2857 iter: ["foo", ".."],
2860 parent: Some("foo"),
2871 file_name: Some("foo"),
2872 file_stem: Some("foo"),
2877 iter: ["foo", "bar"],
2880 parent: Some("foo"),
2881 file_name: Some("bar"),
2882 file_stem: Some("bar"),
2887 iter: ["foo", ".."],
2890 parent: Some("foo"),
2897 iter: ["foo", "..", "bar"],
2900 parent: Some("foo/.."),
2901 file_name: Some("bar"),
2902 file_stem: Some("bar"),
2911 file_name: Some("a"),
2912 file_stem: Some("a"),
2941 file_name: Some("b"),
2942 file_stem: Some("b"),
2951 file_name: Some("b"),
2952 file_stem: Some("b"),
2961 file_name: Some("b"),
2962 file_stem: Some("b"),
2967 iter: ["a", "b", "c"],
2970 parent: Some("a/b"),
2971 file_name: Some("c"),
2972 file_stem: Some("c"),
2976 iter: ["a", "b", "c"],
2979 parent: Some("a\\b"),
2980 file_name: Some("c"),
2981 file_stem: Some("c"),
2990 file_name: Some("a"),
2991 file_stem: Some("a"),
2996 iter: ["c:", "\\", "foo.txt"],
2999 parent: Some("c:\\"),
3000 file_name: Some("foo.txt"),
3001 file_stem: Some("foo"),
3002 extension: Some("txt")
3005 t!("\\\\server\\share\\foo.txt",
3006 iter: ["\\\\server\\share", "\\", "foo.txt"],
3009 parent: Some("\\\\server\\share\\"),
3010 file_name: Some("foo.txt"),
3011 file_stem: Some("foo"),
3012 extension: Some("txt")
3015 t!("\\\\server\\share",
3016 iter: ["\\\\server\\share", "\\"],
3026 iter: ["\\", "server"],
3030 file_name: Some("server"),
3031 file_stem: Some("server"),
3035 t!("\\\\?\\bar\\foo.txt",
3036 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3039 parent: Some("\\\\?\\bar\\"),
3040 file_name: Some("foo.txt"),
3041 file_stem: Some("foo"),
3042 extension: Some("txt")
3046 iter: ["\\\\?\\bar"],
3065 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3066 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3069 parent: Some("\\\\?\\UNC\\server\\share\\"),
3070 file_name: Some("foo.txt"),
3071 file_stem: Some("foo"),
3072 extension: Some("txt")
3075 t!("\\\\?\\UNC\\server",
3076 iter: ["\\\\?\\UNC\\server"],
3086 iter: ["\\\\?\\UNC\\"],
3095 t!("\\\\?\\C:\\foo.txt",
3096 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3099 parent: Some("\\\\?\\C:\\"),
3100 file_name: Some("foo.txt"),
3101 file_stem: Some("foo"),
3102 extension: Some("txt")
3107 iter: ["\\\\?\\C:", "\\"],
3118 iter: ["\\\\?\\C:"],
3128 t!("\\\\?\\foo/bar",
3129 iter: ["\\\\?\\foo/bar"],
3140 iter: ["\\\\?\\C:/foo"],
3150 t!("\\\\.\\foo\\bar",
3151 iter: ["\\\\.\\foo", "\\", "bar"],
3154 parent: Some("\\\\.\\foo\\"),
3155 file_name: Some("bar"),
3156 file_stem: Some("bar"),
3162 iter: ["\\\\.\\foo", "\\"],
3172 t!("\\\\.\\foo/bar",
3173 iter: ["\\\\.\\foo/bar", "\\"],
3183 t!("\\\\.\\foo\\bar/baz",
3184 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3187 parent: Some("\\\\.\\foo\\bar"),
3188 file_name: Some("baz"),
3189 file_stem: Some("baz"),
3195 iter: ["\\\\.\\", "\\"],
3205 iter: ["\\\\?\\a", "\\", "b"],
3208 parent: Some("\\\\?\\a\\"),
3209 file_name: Some("b"),
3210 file_stem: Some("b"),
3216 pub fn test_stem_ext() {
3218 file_stem: Some("foo"),
3223 file_stem: Some("foo"),
3228 file_stem: Some(".foo"),
3233 file_stem: Some("foo"),
3234 extension: Some("txt")
3238 file_stem: Some("foo.bar"),
3239 extension: Some("txt")
3243 file_stem: Some("foo.bar"),
3264 pub fn test_push() {
3266 ($path:expr, $push:expr, $expected:expr) => ( {
3267 let mut actual = PathBuf::from($path);
3269 assert!(actual.to_str() == Some($expected),
3270 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3271 $push, $path, $expected, actual.to_str().unwrap());
3276 tp!("", "foo", "foo");
3277 tp!("foo", "bar", "foo/bar");
3278 tp!("foo/", "bar", "foo/bar");
3279 tp!("foo//", "bar", "foo//bar");
3280 tp!("foo/.", "bar", "foo/./bar");
3281 tp!("foo./.", "bar", "foo././bar");
3282 tp!("foo", "", "foo/");
3283 tp!("foo", ".", "foo/.");
3284 tp!("foo", "..", "foo/..");
3285 tp!("foo", "/", "/");
3286 tp!("/foo/bar", "/", "/");
3287 tp!("/foo/bar", "/baz", "/baz");
3288 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3290 tp!("", "foo", "foo");
3291 tp!("foo", "bar", r"foo\bar");
3292 tp!("foo/", "bar", r"foo/bar");
3293 tp!(r"foo\", "bar", r"foo\bar");
3294 tp!("foo//", "bar", r"foo//bar");
3295 tp!(r"foo\\", "bar", r"foo\\bar");
3296 tp!("foo/.", "bar", r"foo/.\bar");
3297 tp!("foo./.", "bar", r"foo./.\bar");
3298 tp!(r"foo\.", "bar", r"foo\.\bar");
3299 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3300 tp!("foo", "", "foo\\");
3301 tp!("foo", ".", r"foo\.");
3302 tp!("foo", "..", r"foo\..");
3303 tp!("foo", "/", "/");
3304 tp!("foo", r"\", r"\");
3305 tp!("/foo/bar", "/", "/");
3306 tp!(r"\foo\bar", r"\", r"\");
3307 tp!("/foo/bar", "/baz", "/baz");
3308 tp!("/foo/bar", r"\baz", r"\baz");
3309 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3310 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3312 tp!("c:\\", "windows", "c:\\windows");
3313 tp!("c:", "windows", "c:windows");
3315 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3316 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3317 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3318 tp!("a\\b", "\\c\\d", "\\c\\d");
3319 tp!("a\\b", ".", "a\\b\\.");
3320 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3321 tp!("a\\b", "C:a.txt", "C:a.txt");
3322 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3323 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3324 tp!("C:\\a\\b\\c", "C:d", "C:d");
3325 tp!("C:a\\b\\c", "C:d", "C:d");
3326 tp!("C:", r"a\b\c", r"C:a\b\c");
3327 tp!("C:", r"..\a", r"C:..\a");
3328 tp!("\\\\server\\share\\foo",
3330 "\\\\server\\share\\foo\\bar");
3331 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3332 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3333 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3334 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3335 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3336 tp!("\\\\?\\UNC\\server\\share\\foo",
3338 "\\\\?\\UNC\\server\\share\\foo\\bar");
3339 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3340 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3342 // Note: modified from old path API
3343 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3346 "\\\\?\\UNC\\server\\share",
3347 "\\\\?\\UNC\\server\\share");
3348 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3349 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3350 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3351 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3353 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3360 ($path:expr, $expected:expr, $output:expr) => ( {
3361 let mut actual = PathBuf::from($path);
3362 let output = actual.pop();
3363 assert!(actual.to_str() == Some($expected) && output == $output,
3364 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3365 $path, $expected, $output,
3366 actual.to_str().unwrap(), output);
3371 tp!("/", "/", false);
3372 tp!("foo", "", true);
3374 tp!("/foo", "/", true);
3375 tp!("/foo/bar", "/foo", true);
3376 tp!("foo/bar", "foo", true);
3377 tp!("foo/.", "", true);
3378 tp!("foo//bar", "foo", true);
3381 tp!("a\\b\\c", "a\\b", true);
3382 tp!("\\a", "\\", true);
3383 tp!("\\", "\\", false);
3385 tp!("C:\\a\\b", "C:\\a", true);
3386 tp!("C:\\a", "C:\\", true);
3387 tp!("C:\\", "C:\\", false);
3388 tp!("C:a\\b", "C:a", true);
3389 tp!("C:a", "C:", true);
3390 tp!("C:", "C:", false);
3391 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3392 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3393 tp!("\\\\server\\share", "\\\\server\\share", false);
3394 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3395 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3396 tp!("\\\\?\\a", "\\\\?\\a", false);
3397 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3398 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3399 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3400 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3401 "\\\\?\\UNC\\server\\share\\a",
3403 tp!("\\\\?\\UNC\\server\\share\\a",
3404 "\\\\?\\UNC\\server\\share\\",
3406 tp!("\\\\?\\UNC\\server\\share",
3407 "\\\\?\\UNC\\server\\share",
3409 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3410 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3411 tp!("\\\\.\\a", "\\\\.\\a", false);
3413 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3418 pub fn test_set_file_name() {
3420 ($path:expr, $file:expr, $expected:expr) => ( {
3421 let mut p = PathBuf::from($path);
3422 p.set_file_name($file);
3423 assert!(p.to_str() == Some($expected),
3424 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3425 $path, $file, $expected,
3426 p.to_str().unwrap());
3430 tfn!("foo", "foo", "foo");
3431 tfn!("foo", "bar", "bar");
3432 tfn!("foo", "", "");
3433 tfn!("", "foo", "foo");
3435 tfn!(".", "foo", "./foo");
3436 tfn!("foo/", "bar", "bar");
3437 tfn!("foo/.", "bar", "bar");
3438 tfn!("..", "foo", "../foo");
3439 tfn!("foo/..", "bar", "foo/../bar");
3440 tfn!("/", "foo", "/foo");
3442 tfn!(".", "foo", r".\foo");
3443 tfn!(r"foo\", "bar", r"bar");
3444 tfn!(r"foo\.", "bar", r"bar");
3445 tfn!("..", "foo", r"..\foo");
3446 tfn!(r"foo\..", "bar", r"foo\..\bar");
3447 tfn!(r"\", "foo", r"\foo");
3452 pub fn test_set_extension() {
3454 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3455 let mut p = PathBuf::from($path);
3456 let output = p.set_extension($ext);
3457 assert!(p.to_str() == Some($expected) && output == $output,
3458 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3459 $path, $ext, $expected, $output,
3460 p.to_str().unwrap(), output);
3464 tfe!("foo", "txt", "foo.txt", true);
3465 tfe!("foo.bar", "txt", "foo.txt", true);
3466 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3467 tfe!(".test", "txt", ".test.txt", true);
3468 tfe!("foo.txt", "", "foo", true);
3469 tfe!("foo", "", "foo", true);
3470 tfe!("", "foo", "", false);
3471 tfe!(".", "foo", ".", false);
3472 tfe!("foo/", "bar", "foo.bar", true);
3473 tfe!("foo/.", "bar", "foo.bar", true);
3474 tfe!("..", "foo", "..", false);
3475 tfe!("foo/..", "bar", "foo/..", false);
3476 tfe!("/", "foo", "/", false);
3480 fn test_eq_recievers() {
3483 let borrowed: &Path = Path::new("foo/bar");
3484 let mut owned: PathBuf = PathBuf::new();
3487 let borrowed_cow: Cow<Path> = borrowed.into();
3488 let owned_cow: Cow<Path> = owned.clone().into();
3491 ($($current:expr),+) => {
3493 assert_eq!($current, borrowed);
3494 assert_eq!($current, owned);
3495 assert_eq!($current, borrowed_cow);
3496 assert_eq!($current, owned_cow);
3501 t!(borrowed, owned, borrowed_cow, owned_cow);
3505 pub fn test_compare() {
3506 use hash::{Hash, Hasher};
3507 use collections::hash_map::DefaultHasher;
3509 fn hash<T: Hash>(t: T) -> u64 {
3510 let mut s = DefaultHasher::new();
3516 ($path1:expr, $path2:expr, eq: $eq:expr,
3517 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3518 relative_from: $relative_from:expr) => ({
3519 let path1 = Path::new($path1);
3520 let path2 = Path::new($path2);
3522 let eq = path1 == path2;
3523 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3524 $path1, $path2, $eq, eq);
3525 assert!($eq == (hash(path1) == hash(path2)),
3526 "{:?} == {:?}, expected {:?}, got {} and {}",
3527 $path1, $path2, $eq, hash(path1), hash(path2));
3529 let starts_with = path1.starts_with(path2);
3530 assert!(starts_with == $starts_with,
3531 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3532 $starts_with, starts_with);
3534 let ends_with = path1.ends_with(path2);
3535 assert!(ends_with == $ends_with,
3536 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3537 $ends_with, ends_with);
3539 let relative_from = path1.strip_prefix(path2)
3540 .map(|p| p.to_str().unwrap())
3542 let exp: Option<&str> = $relative_from;
3543 assert!(relative_from == exp,
3544 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3545 $path1, $path2, exp, relative_from);
3553 relative_from: Some("")
3560 relative_from: Some("foo")
3574 relative_from: Some("")
3581 relative_from: Some("")
3584 tc!("foo/bar", "foo",
3588 relative_from: Some("bar")
3591 tc!("foo/bar/baz", "foo/bar",
3595 relative_from: Some("baz")
3598 tc!("foo/bar", "foo/bar/baz",
3605 tc!("./foo/bar/", ".",
3609 relative_from: Some("foo/bar")
3613 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3614 r"c:\src\rust\cargo-test\test",
3618 relative_from: Some("Cargo.toml")
3621 tc!(r"c:\foo", r"C:\foo",
3625 relative_from: Some("")
3631 fn test_components_debug() {
3632 let path = Path::new("/tmp");
3634 let mut components = path.components();
3636 let expected = "Components([RootDir, Normal(\"tmp\")])";
3637 let actual = format!("{:?}", components);
3638 assert_eq!(expected, actual);
3640 let _ = components.next().unwrap();
3641 let expected = "Components([Normal(\"tmp\")])";
3642 let actual = format!("{:?}", components);
3643 assert_eq!(expected, actual);
3645 let _ = components.next().unwrap();
3646 let expected = "Components([])";
3647 let actual = format!("{:?}", components);
3648 assert_eq!(expected, actual);
3653 fn test_iter_debug() {
3654 let path = Path::new("/tmp");
3656 let mut iter = path.iter();
3658 let expected = "Iter([\"/\", \"tmp\"])";
3659 let actual = format!("{:?}", iter);
3660 assert_eq!(expected, actual);
3662 let _ = iter.next().unwrap();
3663 let expected = "Iter([\"tmp\"])";
3664 let actual = format!("{:?}", iter);
3665 assert_eq!(expected, actual);
3667 let _ = iter.next().unwrap();
3668 let expected = "Iter([])";
3669 let actual = format!("{:?}", iter);
3670 assert_eq!(expected, actual);