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 = "default_for_pathbuf", since = "1.16.0")]
1269 impl Default for PathBuf {
1270 fn default() -> Self {
1275 #[stable(feature = "cow_from_path", since = "1.6.0")]
1276 impl<'a> From<&'a Path> for Cow<'a, Path> {
1278 fn from(s: &'a Path) -> Cow<'a, Path> {
1283 #[stable(feature = "cow_from_path", since = "1.6.0")]
1284 impl<'a> From<PathBuf> for Cow<'a, Path> {
1286 fn from(s: PathBuf) -> Cow<'a, Path> {
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 impl ToOwned for Path {
1293 type Owned = PathBuf;
1294 fn to_owned(&self) -> PathBuf {
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl cmp::PartialEq for PathBuf {
1301 fn eq(&self, other: &PathBuf) -> bool {
1302 self.components() == other.components()
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl Hash for PathBuf {
1308 fn hash<H: Hasher>(&self, h: &mut H) {
1309 self.as_path().hash(h)
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl cmp::Eq for PathBuf {}
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl cmp::PartialOrd for PathBuf {
1318 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1319 self.components().partial_cmp(other.components())
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl cmp::Ord for PathBuf {
1325 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1326 self.components().cmp(other.components())
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl AsRef<OsStr> for PathBuf {
1332 fn as_ref(&self) -> &OsStr {
1337 /// A slice of a path (akin to [`str`]).
1339 /// This type supports a number of operations for inspecting a path, including
1340 /// breaking the path into its components (separated by `/` or `\`, depending on
1341 /// the platform), extracting the file name, determining whether the path is
1342 /// absolute, and so on.
1344 /// This is an *unsized* type, meaning that it must always be used behind a
1345 /// pointer like `&` or [`Box`]. For an owned version of this type,
1346 /// see [`PathBuf`].
1348 /// [`str`]: ../primitive.str.html
1349 /// [`Box`]: ../boxed/struct.Box.html
1350 /// [`PathBuf`]: struct.PathBuf.html
1352 /// More details about the overall approach can be found in
1353 /// the module documentation.
1358 /// use std::path::Path;
1359 /// use std::ffi::OsStr;
1361 /// let path = Path::new("/tmp/foo/bar.txt");
1363 /// let parent = path.parent();
1364 /// assert_eq!(parent, Some(Path::new("/tmp/foo")));
1366 /// let file_stem = path.file_stem();
1367 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1369 /// let extension = path.extension();
1370 /// assert_eq!(extension, Some(OsStr::new("txt")));
1372 #[stable(feature = "rust1", since = "1.0.0")]
1377 /// An error returned from the [`Path::strip_prefix`] method indicating that the
1378 /// prefix was not found in `self`.
1380 /// [`Path::strip_prefix`]: struct.Path.html#method.strip_prefix
1381 #[derive(Debug, Clone, PartialEq, Eq)]
1382 #[stable(since = "1.7.0", feature = "strip_prefix")]
1383 pub struct StripPrefixError(());
1386 // The following (private!) function allows construction of a path from a u8
1387 // slice, which is only safe when it is known to follow the OsStr encoding.
1388 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1389 Path::new(u8_slice_as_os_str(s))
1391 // The following (private!) function reveals the byte encoding used for OsStr.
1392 fn as_u8_slice(&self) -> &[u8] {
1393 os_str_as_u8_slice(&self.inner)
1396 /// Directly wrap a string slice as a `Path` slice.
1398 /// This is a cost-free conversion.
1403 /// use std::path::Path;
1405 /// Path::new("foo.txt");
1408 /// You can create `Path`s from `String`s, or even other `Path`s:
1411 /// use std::path::Path;
1413 /// let string = String::from("foo.txt");
1414 /// let from_string = Path::new(&string);
1415 /// let from_path = Path::new(&from_string);
1416 /// assert_eq!(from_string, from_path);
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1420 unsafe { mem::transmute(s.as_ref()) }
1423 /// Yields the underlying [`OsStr`] slice.
1425 /// [`OsStr`]: ../ffi/struct.OsStr.html
1430 /// use std::path::Path;
1432 /// let os_str = Path::new("foo.txt").as_os_str();
1433 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub fn as_os_str(&self) -> &OsStr {
1440 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1442 /// This conversion may entail doing a check for UTF-8 validity.
1444 /// [`&str`]: ../primitive.str.html
1449 /// use std::path::Path;
1451 /// let path = Path::new("foo.txt");
1452 /// assert_eq!(path.to_str(), Some("foo.txt"));
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 pub fn to_str(&self) -> Option<&str> {
1459 /// Converts a `Path` to a [`Cow<str>`].
1461 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1463 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1467 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1470 /// use std::path::Path;
1472 /// let path = Path::new("foo.txt");
1473 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1476 /// Had `os_str` contained invalid unicode, the `to_string_lossy` call might
1477 /// have returned `"fo�.txt"`.
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 pub fn to_string_lossy(&self) -> Cow<str> {
1480 self.inner.to_string_lossy()
1483 /// Converts a `Path` to an owned [`PathBuf`].
1485 /// [`PathBuf`]: struct.PathBuf.html
1490 /// use std::path::Path;
1492 /// let path_buf = Path::new("foo.txt").to_path_buf();
1493 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 pub fn to_path_buf(&self) -> PathBuf {
1497 PathBuf::from(self.inner.to_os_string())
1500 /// A path is *absolute* if it is independent of the current directory.
1502 /// * On Unix, a path is absolute if it starts with the root, so
1503 /// `is_absolute` and `has_root` are equivalent.
1505 /// * On Windows, a path is absolute if it has a prefix and starts with the
1506 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1511 /// use std::path::Path;
1513 /// assert!(!Path::new("foo.txt").is_absolute());
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 #[allow(deprecated)]
1517 pub fn is_absolute(&self) -> bool {
1518 // FIXME: Remove target_os = "redox" and allow Redox prefixes
1519 self.has_root() && (cfg!(unix) || cfg!(target_os = "redox") || self.prefix().is_some())
1522 /// A path is *relative* if it is not absolute.
1527 /// use std::path::Path;
1529 /// assert!(Path::new("foo.txt").is_relative());
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 pub fn is_relative(&self) -> bool {
1536 fn prefix(&self) -> Option<Prefix> {
1537 self.components().prefix
1540 /// A path has a root if the body of the path begins with the directory separator.
1542 /// * On Unix, a path has a root if it begins with `/`.
1544 /// * On Windows, a path has a root if it:
1545 /// * has no prefix and begins with a separator, e.g. `\\windows`
1546 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1547 /// * has any non-disk prefix, e.g. `\\server\share`
1552 /// use std::path::Path;
1554 /// assert!(Path::new("/etc/passwd").has_root());
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 pub fn has_root(&self) -> bool {
1558 self.components().has_root()
1561 /// The path without its final component, if any.
1563 /// Returns [`None`] if the path terminates in a root or prefix.
1565 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1570 /// use std::path::Path;
1572 /// let path = Path::new("/foo/bar");
1573 /// let parent = path.parent().unwrap();
1574 /// assert_eq!(parent, Path::new("/foo"));
1576 /// let grand_parent = parent.parent().unwrap();
1577 /// assert_eq!(grand_parent, Path::new("/"));
1578 /// assert_eq!(grand_parent.parent(), None);
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 pub fn parent(&self) -> Option<&Path> {
1582 let mut comps = self.components();
1583 let comp = comps.next_back();
1586 Component::Normal(_) |
1588 Component::ParentDir => Some(comps.as_path()),
1594 /// The final component of the path, if it is a normal file.
1596 /// If the path terminates in `..`, `file_name` will return [`None`].
1598 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1603 /// use std::path::Path;
1604 /// use std::ffi::OsStr;
1606 /// let path = Path::new("foo.txt");
1607 /// let os_str = OsStr::new("foo.txt");
1609 /// assert_eq!(Some(os_str), path.file_name());
1612 /// # Other examples
1615 /// use std::path::Path;
1616 /// use std::ffi::OsStr;
1618 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1619 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1620 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 pub fn file_name(&self) -> Option<&OsStr> {
1624 self.components().next_back().and_then(|p| {
1626 Component::Normal(p) => Some(p.as_ref()),
1632 /// Returns a path that, when joined onto `base`, yields `self`.
1636 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1637 /// returns `false`), returns [`Err`].
1639 /// [`starts_with`]: #method.starts_with
1640 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1645 /// use std::path::Path;
1647 /// let path = Path::new("/test/haha/foo.txt");
1649 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1650 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1651 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1653 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1654 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1655 -> Result<&'a Path, StripPrefixError>
1656 where P: AsRef<Path>
1658 self._strip_prefix(base.as_ref())
1661 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1662 -> Result<&'a Path, StripPrefixError> {
1663 iter_after(self.components(), base.components())
1664 .map(|c| c.as_path())
1665 .ok_or(StripPrefixError(()))
1668 /// Determines whether `base` is a prefix of `self`.
1670 /// Only considers whole path components to match.
1675 /// use std::path::Path;
1677 /// let path = Path::new("/etc/passwd");
1679 /// assert!(path.starts_with("/etc"));
1681 /// assert!(!path.starts_with("/e"));
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1685 self._starts_with(base.as_ref())
1688 fn _starts_with(&self, base: &Path) -> bool {
1689 iter_after(self.components(), base.components()).is_some()
1692 /// Determines whether `child` is a suffix of `self`.
1694 /// Only considers whole path components to match.
1699 /// use std::path::Path;
1701 /// let path = Path::new("/etc/passwd");
1703 /// assert!(path.ends_with("passwd"));
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1707 self._ends_with(child.as_ref())
1710 fn _ends_with(&self, child: &Path) -> bool {
1711 iter_after(self.components().rev(), child.components().rev()).is_some()
1714 /// Extracts the stem (non-extension) portion of [`self.file_name()`].
1716 /// [`self.file_name()`]: struct.Path.html#method.file_name
1720 /// * [`None`], if there is no file name;
1721 /// * The entire file name if there is no embedded `.`;
1722 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1723 /// * Otherwise, the portion of the file name before the final `.`
1725 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1730 /// use std::path::Path;
1732 /// let path = Path::new("foo.rs");
1734 /// assert_eq!("foo", path.file_stem().unwrap());
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 pub fn file_stem(&self) -> Option<&OsStr> {
1738 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1741 /// Extracts the extension of [`self.file_name()`], if possible.
1743 /// The extension is:
1745 /// * [`None`], if there is no file name;
1746 /// * [`None`], if there is no embedded `.`;
1747 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1748 /// * Otherwise, the portion of the file name after the final `.`
1750 /// [`self.file_name()`]: struct.Path.html#method.file_name
1751 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1756 /// use std::path::Path;
1758 /// let path = Path::new("foo.rs");
1760 /// assert_eq!("rs", path.extension().unwrap());
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 pub fn extension(&self) -> Option<&OsStr> {
1764 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1767 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1769 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1771 /// [`PathBuf`]: struct.PathBuf.html
1772 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1777 /// use std::path::{Path, PathBuf};
1779 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1783 self._join(path.as_ref())
1786 fn _join(&self, path: &Path) -> PathBuf {
1787 let mut buf = self.to_path_buf();
1792 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1794 /// See [`PathBuf::set_file_name`] for more details.
1796 /// [`PathBuf`]: struct.PathBuf.html
1797 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1802 /// use std::path::{Path, PathBuf};
1804 /// let path = Path::new("/tmp/foo.txt");
1805 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1809 self._with_file_name(file_name.as_ref())
1812 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1813 let mut buf = self.to_path_buf();
1814 buf.set_file_name(file_name);
1818 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
1820 /// See [`PathBuf::set_extension`] for more details.
1822 /// [`PathBuf`]: struct.PathBuf.html
1823 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
1828 /// use std::path::{Path, PathBuf};
1830 /// let path = Path::new("foo.rs");
1831 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1835 self._with_extension(extension.as_ref())
1838 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1839 let mut buf = self.to_path_buf();
1840 buf.set_extension(extension);
1844 /// Produce an iterator over the components of the path.
1849 /// use std::path::{Path, Component};
1850 /// use std::ffi::OsStr;
1852 /// let mut components = Path::new("/tmp/foo.txt").components();
1854 /// assert_eq!(components.next(), Some(Component::RootDir));
1855 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1856 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1857 /// assert_eq!(components.next(), None)
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 pub fn components(&self) -> Components {
1861 let prefix = parse_prefix(self.as_os_str());
1863 path: self.as_u8_slice(),
1865 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1866 front: State::Prefix,
1871 /// Produce an iterator over the path's components viewed as [`OsStr`] slices.
1873 /// [`OsStr`]: ../ffi/struct.OsStr.html
1878 /// use std::path::{self, Path};
1879 /// use std::ffi::OsStr;
1881 /// let mut it = Path::new("/tmp/foo.txt").iter();
1882 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1883 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1884 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1885 /// assert_eq!(it.next(), None)
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 pub fn iter(&self) -> Iter {
1889 Iter { inner: self.components() }
1892 /// Returns an object that implements [`Display`] for safely printing paths
1893 /// that may contain non-Unicode data.
1895 /// [`Display`]: ../fmt/trait.Display.html
1900 /// use std::path::Path;
1902 /// let path = Path::new("/tmp/foo.rs");
1904 /// println!("{}", path.display());
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 pub fn display(&self) -> Display {
1908 Display { path: self }
1911 /// Query the file system to get information about a file, directory, etc.
1913 /// This function will traverse symbolic links to query information about the
1914 /// destination file.
1916 /// This is an alias to [`fs::metadata`].
1918 /// [`fs::metadata`]: ../fs/fn.metadata.html
1923 /// use std::path::Path;
1925 /// let path = Path::new("/Minas/tirith");
1926 /// let metadata = path.metadata().expect("metadata call failed");
1927 /// println!("{:?}", metadata.file_type());
1929 #[stable(feature = "path_ext", since = "1.5.0")]
1930 pub fn metadata(&self) -> io::Result<fs::Metadata> {
1934 /// Query the metadata about a file without following symlinks.
1936 /// This is an alias to [`fs::symlink_metadata`].
1938 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
1943 /// use std::path::Path;
1945 /// let path = Path::new("/Minas/tirith");
1946 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
1947 /// println!("{:?}", metadata.file_type());
1949 #[stable(feature = "path_ext", since = "1.5.0")]
1950 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1951 fs::symlink_metadata(self)
1954 /// Returns the canonical form of the path with all intermediate components
1955 /// normalized and symbolic links resolved.
1957 /// This is an alias to [`fs::canonicalize`].
1959 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
1964 /// use std::path::{Path, PathBuf};
1966 /// let path = Path::new("/foo/test/../test/bar.rs");
1967 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
1969 #[stable(feature = "path_ext", since = "1.5.0")]
1970 pub fn canonicalize(&self) -> io::Result<PathBuf> {
1971 fs::canonicalize(self)
1974 /// Reads a symbolic link, returning the file that the link points to.
1976 /// This is an alias to [`fs::read_link`].
1978 /// [`fs::read_link`]: ../fs/fn.read_link.html
1983 /// use std::path::Path;
1985 /// let path = Path::new("/laputa/sky_castle.rs");
1986 /// let path_link = path.read_link().expect("read_link call failed");
1988 #[stable(feature = "path_ext", since = "1.5.0")]
1989 pub fn read_link(&self) -> io::Result<PathBuf> {
1993 /// Returns an iterator over the entries within a directory.
1995 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
1996 /// errors may be encountered after an iterator is initially constructed.
1998 /// This is an alias to [`fs::read_dir`].
2000 /// [`io::Result`]: ../io/type.Result.html
2001 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2002 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2007 /// use std::path::Path;
2009 /// let path = Path::new("/laputa");
2010 /// for entry in path.read_dir().expect("read_dir call failed") {
2011 /// if let Ok(entry) = entry {
2012 /// println!("{:?}", entry.path());
2016 #[stable(feature = "path_ext", since = "1.5.0")]
2017 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2021 /// Returns whether the path points at an existing entity.
2023 /// This function will traverse symbolic links to query information about the
2024 /// destination file. In case of broken symbolic links this will return `false`.
2029 /// use std::path::Path;
2030 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2032 #[stable(feature = "path_ext", since = "1.5.0")]
2033 pub fn exists(&self) -> bool {
2034 fs::metadata(self).is_ok()
2037 /// Returns whether the path is pointing at a regular file.
2039 /// This function will traverse symbolic links to query information about the
2040 /// destination file. In case of broken symbolic links this will return `false`.
2045 /// use std::path::Path;
2046 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2047 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2049 #[stable(feature = "path_ext", since = "1.5.0")]
2050 pub fn is_file(&self) -> bool {
2051 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2054 /// Returns whether the path is pointing at a directory.
2056 /// This function will traverse symbolic links to query information about the
2057 /// destination file. In case of broken symbolic links this will return `false`.
2062 /// use std::path::Path;
2063 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2064 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2066 #[stable(feature = "path_ext", since = "1.5.0")]
2067 pub fn is_dir(&self) -> bool {
2068 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl AsRef<OsStr> for Path {
2074 fn as_ref(&self) -> &OsStr {
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 impl fmt::Debug for Path {
2081 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2082 self.inner.fmt(formatter)
2086 /// Helper struct for safely printing paths with `format!()` and `{}`
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 pub struct Display<'a> {
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl<'a> fmt::Debug for Display<'a> {
2094 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2095 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 impl<'a> fmt::Display for Display<'a> {
2101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2102 fmt::Display::fmt(&self.path.to_string_lossy(), f)
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl cmp::PartialEq for Path {
2108 fn eq(&self, other: &Path) -> bool {
2109 self.components().eq(other.components())
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 impl Hash for Path {
2115 fn hash<H: Hasher>(&self, h: &mut H) {
2116 for component in self.components() {
2122 #[stable(feature = "rust1", since = "1.0.0")]
2123 impl cmp::Eq for Path {}
2125 #[stable(feature = "rust1", since = "1.0.0")]
2126 impl cmp::PartialOrd for Path {
2127 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2128 self.components().partial_cmp(other.components())
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl cmp::Ord for Path {
2134 fn cmp(&self, other: &Path) -> cmp::Ordering {
2135 self.components().cmp(other.components())
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 impl AsRef<Path> for Path {
2141 fn as_ref(&self) -> &Path {
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl AsRef<Path> for OsStr {
2148 fn as_ref(&self) -> &Path {
2153 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2154 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2155 fn as_ref(&self) -> &Path {
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl AsRef<Path> for OsString {
2162 fn as_ref(&self) -> &Path {
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 impl AsRef<Path> for str {
2169 fn as_ref(&self) -> &Path {
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 impl AsRef<Path> for String {
2176 fn as_ref(&self) -> &Path {
2181 #[stable(feature = "rust1", since = "1.0.0")]
2182 impl AsRef<Path> for PathBuf {
2183 fn as_ref(&self) -> &Path {
2188 #[stable(feature = "path_into_iter", since = "1.6.0")]
2189 impl<'a> IntoIterator for &'a PathBuf {
2190 type Item = &'a OsStr;
2191 type IntoIter = Iter<'a>;
2192 fn into_iter(self) -> Iter<'a> { self.iter() }
2195 #[stable(feature = "path_into_iter", since = "1.6.0")]
2196 impl<'a> IntoIterator for &'a Path {
2197 type Item = &'a OsStr;
2198 type IntoIter = Iter<'a>;
2199 fn into_iter(self) -> Iter<'a> { self.iter() }
2202 macro_rules! impl_cmp {
2203 ($lhs:ty, $rhs: ty) => {
2204 #[stable(feature = "partialeq_path", since = "1.6.0")]
2205 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2207 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2210 #[stable(feature = "partialeq_path", since = "1.6.0")]
2211 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2213 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2216 #[stable(feature = "cmp_path", since = "1.8.0")]
2217 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2219 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2220 <Path as PartialOrd>::partial_cmp(self, other)
2224 #[stable(feature = "cmp_path", since = "1.8.0")]
2225 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2227 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2228 <Path as PartialOrd>::partial_cmp(self, other)
2234 impl_cmp!(PathBuf, Path);
2235 impl_cmp!(PathBuf, &'a Path);
2236 impl_cmp!(Cow<'a, Path>, Path);
2237 impl_cmp!(Cow<'a, Path>, &'b Path);
2238 impl_cmp!(Cow<'a, Path>, PathBuf);
2240 macro_rules! impl_cmp_os_str {
2241 ($lhs:ty, $rhs: ty) => {
2242 #[stable(feature = "cmp_path", since = "1.8.0")]
2243 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2245 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2248 #[stable(feature = "cmp_path", since = "1.8.0")]
2249 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2251 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2254 #[stable(feature = "cmp_path", since = "1.8.0")]
2255 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2257 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2258 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2262 #[stable(feature = "cmp_path", since = "1.8.0")]
2263 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2265 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2266 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2272 impl_cmp_os_str!(PathBuf, OsStr);
2273 impl_cmp_os_str!(PathBuf, &'a OsStr);
2274 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2275 impl_cmp_os_str!(PathBuf, OsString);
2276 impl_cmp_os_str!(Path, OsStr);
2277 impl_cmp_os_str!(Path, &'a OsStr);
2278 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2279 impl_cmp_os_str!(Path, OsString);
2280 impl_cmp_os_str!(&'a Path, OsStr);
2281 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2282 impl_cmp_os_str!(&'a Path, OsString);
2283 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2284 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2285 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2287 #[stable(since = "1.7.0", feature = "strip_prefix")]
2288 impl fmt::Display for StripPrefixError {
2289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2290 self.description().fmt(f)
2294 #[stable(since = "1.7.0", feature = "strip_prefix")]
2295 impl Error for StripPrefixError {
2296 fn description(&self) -> &str { "prefix not found" }
2304 ($path:expr, iter: $iter:expr) => (
2306 let path = Path::new($path);
2308 // Forward iteration
2309 let comps = path.iter()
2310 .map(|p| p.to_string_lossy().into_owned())
2311 .collect::<Vec<String>>();
2312 let exp: &[&str] = &$iter;
2313 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2314 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2317 // Reverse iteration
2318 let comps = Path::new($path).iter().rev()
2319 .map(|p| p.to_string_lossy().into_owned())
2320 .collect::<Vec<String>>();
2321 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2322 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2327 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2329 let path = Path::new($path);
2331 let act_root = path.has_root();
2332 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2333 $has_root, act_root);
2335 let act_abs = path.is_absolute();
2336 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2337 $is_absolute, act_abs);
2341 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2343 let path = Path::new($path);
2345 let parent = path.parent().map(|p| p.to_str().unwrap());
2346 let exp_parent: Option<&str> = $parent;
2347 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2348 exp_parent, parent);
2350 let file = path.file_name().map(|p| p.to_str().unwrap());
2351 let exp_file: Option<&str> = $file;
2352 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2357 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2359 let path = Path::new($path);
2361 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2362 let exp_stem: Option<&str> = $file_stem;
2363 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2366 let ext = path.extension().map(|p| p.to_str().unwrap());
2367 let exp_ext: Option<&str> = $extension;
2368 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2373 ($path:expr, iter: $iter:expr,
2374 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2375 parent: $parent:expr, file_name: $file:expr,
2376 file_stem: $file_stem:expr, extension: $extension:expr) => (
2378 t!($path, iter: $iter);
2379 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2380 t!($path, parent: $parent, file_name: $file);
2381 t!($path, file_stem: $file_stem, extension: $extension);
2390 let static_path = Path::new("/home/foo");
2391 let static_cow_path: Cow<'static, Path> = static_path.into();
2392 let pathbuf = PathBuf::from("/home/foo");
2395 let path: &Path = &pathbuf;
2396 let borrowed_cow_path: Cow<Path> = path.into();
2398 assert_eq!(static_cow_path, borrowed_cow_path);
2401 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2403 assert_eq!(static_cow_path, owned_cow_path);
2408 pub fn test_decompositions_unix() {
2424 file_name: Some("foo"),
2425 file_stem: Some("foo"),
2444 file_name: Some("foo"),
2445 file_stem: Some("foo"),
2454 file_name: Some("foo"),
2455 file_stem: Some("foo"),
2464 file_name: Some("foo"),
2465 file_stem: Some("foo"),
2470 iter: ["foo", "bar"],
2473 parent: Some("foo"),
2474 file_name: Some("bar"),
2475 file_stem: Some("bar"),
2480 iter: ["/", "foo", "bar"],
2483 parent: Some("/foo"),
2484 file_name: Some("bar"),
2485 file_stem: Some("bar"),
2494 file_name: Some("foo"),
2495 file_stem: Some("foo"),
2500 iter: ["/", "foo", "bar"],
2503 parent: Some("///foo"),
2504 file_name: Some("bar"),
2505 file_stem: Some("bar"),
2544 file_name: Some("foo"),
2545 file_stem: Some("foo"),
2550 iter: ["foo", ".."],
2553 parent: Some("foo"),
2564 file_name: Some("foo"),
2565 file_stem: Some("foo"),
2570 iter: ["foo", "bar"],
2573 parent: Some("foo"),
2574 file_name: Some("bar"),
2575 file_stem: Some("bar"),
2580 iter: ["foo", ".."],
2583 parent: Some("foo"),
2590 iter: ["foo", "..", "bar"],
2593 parent: Some("foo/.."),
2594 file_name: Some("bar"),
2595 file_stem: Some("bar"),
2604 file_name: Some("a"),
2605 file_stem: Some("a"),
2634 file_name: Some("b"),
2635 file_stem: Some("b"),
2644 file_name: Some("b"),
2645 file_stem: Some("b"),
2654 file_name: Some("b"),
2655 file_stem: Some("b"),
2660 iter: ["a", "b", "c"],
2663 parent: Some("a/b"),
2664 file_name: Some("c"),
2665 file_stem: Some("c"),
2674 file_name: Some(".foo"),
2675 file_stem: Some(".foo"),
2682 pub fn test_decompositions_windows() {
2698 file_name: Some("foo"),
2699 file_stem: Some("foo"),
2754 iter: ["\\", "foo"],
2758 file_name: Some("foo"),
2759 file_stem: Some("foo"),
2768 file_name: Some("foo"),
2769 file_stem: Some("foo"),
2774 iter: ["\\", "foo"],
2778 file_name: Some("foo"),
2779 file_stem: Some("foo"),
2784 iter: ["foo", "bar"],
2787 parent: Some("foo"),
2788 file_name: Some("bar"),
2789 file_stem: Some("bar"),
2794 iter: ["\\", "foo", "bar"],
2797 parent: Some("/foo"),
2798 file_name: Some("bar"),
2799 file_stem: Some("bar"),
2804 iter: ["\\", "foo"],
2808 file_name: Some("foo"),
2809 file_stem: Some("foo"),
2814 iter: ["\\", "foo", "bar"],
2817 parent: Some("///foo"),
2818 file_name: Some("bar"),
2819 file_stem: Some("bar"),
2858 file_name: Some("foo"),
2859 file_stem: Some("foo"),
2864 iter: ["foo", ".."],
2867 parent: Some("foo"),
2878 file_name: Some("foo"),
2879 file_stem: Some("foo"),
2884 iter: ["foo", "bar"],
2887 parent: Some("foo"),
2888 file_name: Some("bar"),
2889 file_stem: Some("bar"),
2894 iter: ["foo", ".."],
2897 parent: Some("foo"),
2904 iter: ["foo", "..", "bar"],
2907 parent: Some("foo/.."),
2908 file_name: Some("bar"),
2909 file_stem: Some("bar"),
2918 file_name: Some("a"),
2919 file_stem: Some("a"),
2948 file_name: Some("b"),
2949 file_stem: Some("b"),
2958 file_name: Some("b"),
2959 file_stem: Some("b"),
2968 file_name: Some("b"),
2969 file_stem: Some("b"),
2974 iter: ["a", "b", "c"],
2977 parent: Some("a/b"),
2978 file_name: Some("c"),
2979 file_stem: Some("c"),
2983 iter: ["a", "b", "c"],
2986 parent: Some("a\\b"),
2987 file_name: Some("c"),
2988 file_stem: Some("c"),
2997 file_name: Some("a"),
2998 file_stem: Some("a"),
3003 iter: ["c:", "\\", "foo.txt"],
3006 parent: Some("c:\\"),
3007 file_name: Some("foo.txt"),
3008 file_stem: Some("foo"),
3009 extension: Some("txt")
3012 t!("\\\\server\\share\\foo.txt",
3013 iter: ["\\\\server\\share", "\\", "foo.txt"],
3016 parent: Some("\\\\server\\share\\"),
3017 file_name: Some("foo.txt"),
3018 file_stem: Some("foo"),
3019 extension: Some("txt")
3022 t!("\\\\server\\share",
3023 iter: ["\\\\server\\share", "\\"],
3033 iter: ["\\", "server"],
3037 file_name: Some("server"),
3038 file_stem: Some("server"),
3042 t!("\\\\?\\bar\\foo.txt",
3043 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3046 parent: Some("\\\\?\\bar\\"),
3047 file_name: Some("foo.txt"),
3048 file_stem: Some("foo"),
3049 extension: Some("txt")
3053 iter: ["\\\\?\\bar"],
3072 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3073 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3076 parent: Some("\\\\?\\UNC\\server\\share\\"),
3077 file_name: Some("foo.txt"),
3078 file_stem: Some("foo"),
3079 extension: Some("txt")
3082 t!("\\\\?\\UNC\\server",
3083 iter: ["\\\\?\\UNC\\server"],
3093 iter: ["\\\\?\\UNC\\"],
3102 t!("\\\\?\\C:\\foo.txt",
3103 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3106 parent: Some("\\\\?\\C:\\"),
3107 file_name: Some("foo.txt"),
3108 file_stem: Some("foo"),
3109 extension: Some("txt")
3114 iter: ["\\\\?\\C:", "\\"],
3125 iter: ["\\\\?\\C:"],
3135 t!("\\\\?\\foo/bar",
3136 iter: ["\\\\?\\foo/bar"],
3147 iter: ["\\\\?\\C:/foo"],
3157 t!("\\\\.\\foo\\bar",
3158 iter: ["\\\\.\\foo", "\\", "bar"],
3161 parent: Some("\\\\.\\foo\\"),
3162 file_name: Some("bar"),
3163 file_stem: Some("bar"),
3169 iter: ["\\\\.\\foo", "\\"],
3179 t!("\\\\.\\foo/bar",
3180 iter: ["\\\\.\\foo/bar", "\\"],
3190 t!("\\\\.\\foo\\bar/baz",
3191 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3194 parent: Some("\\\\.\\foo\\bar"),
3195 file_name: Some("baz"),
3196 file_stem: Some("baz"),
3202 iter: ["\\\\.\\", "\\"],
3212 iter: ["\\\\?\\a", "\\", "b"],
3215 parent: Some("\\\\?\\a\\"),
3216 file_name: Some("b"),
3217 file_stem: Some("b"),
3223 pub fn test_stem_ext() {
3225 file_stem: Some("foo"),
3230 file_stem: Some("foo"),
3235 file_stem: Some(".foo"),
3240 file_stem: Some("foo"),
3241 extension: Some("txt")
3245 file_stem: Some("foo.bar"),
3246 extension: Some("txt")
3250 file_stem: Some("foo.bar"),
3271 pub fn test_push() {
3273 ($path:expr, $push:expr, $expected:expr) => ( {
3274 let mut actual = PathBuf::from($path);
3276 assert!(actual.to_str() == Some($expected),
3277 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3278 $push, $path, $expected, actual.to_str().unwrap());
3283 tp!("", "foo", "foo");
3284 tp!("foo", "bar", "foo/bar");
3285 tp!("foo/", "bar", "foo/bar");
3286 tp!("foo//", "bar", "foo//bar");
3287 tp!("foo/.", "bar", "foo/./bar");
3288 tp!("foo./.", "bar", "foo././bar");
3289 tp!("foo", "", "foo/");
3290 tp!("foo", ".", "foo/.");
3291 tp!("foo", "..", "foo/..");
3292 tp!("foo", "/", "/");
3293 tp!("/foo/bar", "/", "/");
3294 tp!("/foo/bar", "/baz", "/baz");
3295 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3297 tp!("", "foo", "foo");
3298 tp!("foo", "bar", r"foo\bar");
3299 tp!("foo/", "bar", r"foo/bar");
3300 tp!(r"foo\", "bar", r"foo\bar");
3301 tp!("foo//", "bar", r"foo//bar");
3302 tp!(r"foo\\", "bar", r"foo\\bar");
3303 tp!("foo/.", "bar", r"foo/.\bar");
3304 tp!("foo./.", "bar", r"foo./.\bar");
3305 tp!(r"foo\.", "bar", r"foo\.\bar");
3306 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3307 tp!("foo", "", "foo\\");
3308 tp!("foo", ".", r"foo\.");
3309 tp!("foo", "..", r"foo\..");
3310 tp!("foo", "/", "/");
3311 tp!("foo", r"\", r"\");
3312 tp!("/foo/bar", "/", "/");
3313 tp!(r"\foo\bar", r"\", r"\");
3314 tp!("/foo/bar", "/baz", "/baz");
3315 tp!("/foo/bar", r"\baz", r"\baz");
3316 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3317 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3319 tp!("c:\\", "windows", "c:\\windows");
3320 tp!("c:", "windows", "c:windows");
3322 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3323 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3324 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3325 tp!("a\\b", "\\c\\d", "\\c\\d");
3326 tp!("a\\b", ".", "a\\b\\.");
3327 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3328 tp!("a\\b", "C:a.txt", "C:a.txt");
3329 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3330 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3331 tp!("C:\\a\\b\\c", "C:d", "C:d");
3332 tp!("C:a\\b\\c", "C:d", "C:d");
3333 tp!("C:", r"a\b\c", r"C:a\b\c");
3334 tp!("C:", r"..\a", r"C:..\a");
3335 tp!("\\\\server\\share\\foo",
3337 "\\\\server\\share\\foo\\bar");
3338 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3339 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3340 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3341 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3342 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3343 tp!("\\\\?\\UNC\\server\\share\\foo",
3345 "\\\\?\\UNC\\server\\share\\foo\\bar");
3346 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3347 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3349 // Note: modified from old path API
3350 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3353 "\\\\?\\UNC\\server\\share",
3354 "\\\\?\\UNC\\server\\share");
3355 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3356 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3357 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3358 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3360 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3367 ($path:expr, $expected:expr, $output:expr) => ( {
3368 let mut actual = PathBuf::from($path);
3369 let output = actual.pop();
3370 assert!(actual.to_str() == Some($expected) && output == $output,
3371 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3372 $path, $expected, $output,
3373 actual.to_str().unwrap(), output);
3378 tp!("/", "/", false);
3379 tp!("foo", "", true);
3381 tp!("/foo", "/", true);
3382 tp!("/foo/bar", "/foo", true);
3383 tp!("foo/bar", "foo", true);
3384 tp!("foo/.", "", true);
3385 tp!("foo//bar", "foo", true);
3388 tp!("a\\b\\c", "a\\b", true);
3389 tp!("\\a", "\\", true);
3390 tp!("\\", "\\", false);
3392 tp!("C:\\a\\b", "C:\\a", true);
3393 tp!("C:\\a", "C:\\", true);
3394 tp!("C:\\", "C:\\", false);
3395 tp!("C:a\\b", "C:a", true);
3396 tp!("C:a", "C:", true);
3397 tp!("C:", "C:", false);
3398 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3399 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3400 tp!("\\\\server\\share", "\\\\server\\share", false);
3401 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3402 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3403 tp!("\\\\?\\a", "\\\\?\\a", false);
3404 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3405 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3406 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3407 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3408 "\\\\?\\UNC\\server\\share\\a",
3410 tp!("\\\\?\\UNC\\server\\share\\a",
3411 "\\\\?\\UNC\\server\\share\\",
3413 tp!("\\\\?\\UNC\\server\\share",
3414 "\\\\?\\UNC\\server\\share",
3416 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3417 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3418 tp!("\\\\.\\a", "\\\\.\\a", false);
3420 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3425 pub fn test_set_file_name() {
3427 ($path:expr, $file:expr, $expected:expr) => ( {
3428 let mut p = PathBuf::from($path);
3429 p.set_file_name($file);
3430 assert!(p.to_str() == Some($expected),
3431 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3432 $path, $file, $expected,
3433 p.to_str().unwrap());
3437 tfn!("foo", "foo", "foo");
3438 tfn!("foo", "bar", "bar");
3439 tfn!("foo", "", "");
3440 tfn!("", "foo", "foo");
3442 tfn!(".", "foo", "./foo");
3443 tfn!("foo/", "bar", "bar");
3444 tfn!("foo/.", "bar", "bar");
3445 tfn!("..", "foo", "../foo");
3446 tfn!("foo/..", "bar", "foo/../bar");
3447 tfn!("/", "foo", "/foo");
3449 tfn!(".", "foo", r".\foo");
3450 tfn!(r"foo\", "bar", r"bar");
3451 tfn!(r"foo\.", "bar", r"bar");
3452 tfn!("..", "foo", r"..\foo");
3453 tfn!(r"foo\..", "bar", r"foo\..\bar");
3454 tfn!(r"\", "foo", r"\foo");
3459 pub fn test_set_extension() {
3461 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3462 let mut p = PathBuf::from($path);
3463 let output = p.set_extension($ext);
3464 assert!(p.to_str() == Some($expected) && output == $output,
3465 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3466 $path, $ext, $expected, $output,
3467 p.to_str().unwrap(), output);
3471 tfe!("foo", "txt", "foo.txt", true);
3472 tfe!("foo.bar", "txt", "foo.txt", true);
3473 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3474 tfe!(".test", "txt", ".test.txt", true);
3475 tfe!("foo.txt", "", "foo", true);
3476 tfe!("foo", "", "foo", true);
3477 tfe!("", "foo", "", false);
3478 tfe!(".", "foo", ".", false);
3479 tfe!("foo/", "bar", "foo.bar", true);
3480 tfe!("foo/.", "bar", "foo.bar", true);
3481 tfe!("..", "foo", "..", false);
3482 tfe!("foo/..", "bar", "foo/..", false);
3483 tfe!("/", "foo", "/", false);
3487 fn test_eq_recievers() {
3490 let borrowed: &Path = Path::new("foo/bar");
3491 let mut owned: PathBuf = PathBuf::new();
3494 let borrowed_cow: Cow<Path> = borrowed.into();
3495 let owned_cow: Cow<Path> = owned.clone().into();
3498 ($($current:expr),+) => {
3500 assert_eq!($current, borrowed);
3501 assert_eq!($current, owned);
3502 assert_eq!($current, borrowed_cow);
3503 assert_eq!($current, owned_cow);
3508 t!(borrowed, owned, borrowed_cow, owned_cow);
3512 pub fn test_compare() {
3513 use hash::{Hash, Hasher};
3514 use collections::hash_map::DefaultHasher;
3516 fn hash<T: Hash>(t: T) -> u64 {
3517 let mut s = DefaultHasher::new();
3523 ($path1:expr, $path2:expr, eq: $eq:expr,
3524 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3525 relative_from: $relative_from:expr) => ({
3526 let path1 = Path::new($path1);
3527 let path2 = Path::new($path2);
3529 let eq = path1 == path2;
3530 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3531 $path1, $path2, $eq, eq);
3532 assert!($eq == (hash(path1) == hash(path2)),
3533 "{:?} == {:?}, expected {:?}, got {} and {}",
3534 $path1, $path2, $eq, hash(path1), hash(path2));
3536 let starts_with = path1.starts_with(path2);
3537 assert!(starts_with == $starts_with,
3538 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3539 $starts_with, starts_with);
3541 let ends_with = path1.ends_with(path2);
3542 assert!(ends_with == $ends_with,
3543 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3544 $ends_with, ends_with);
3546 let relative_from = path1.strip_prefix(path2)
3547 .map(|p| p.to_str().unwrap())
3549 let exp: Option<&str> = $relative_from;
3550 assert!(relative_from == exp,
3551 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3552 $path1, $path2, exp, relative_from);
3560 relative_from: Some("")
3567 relative_from: Some("foo")
3581 relative_from: Some("")
3588 relative_from: Some("")
3591 tc!("foo/bar", "foo",
3595 relative_from: Some("bar")
3598 tc!("foo/bar/baz", "foo/bar",
3602 relative_from: Some("baz")
3605 tc!("foo/bar", "foo/bar/baz",
3612 tc!("./foo/bar/", ".",
3616 relative_from: Some("foo/bar")
3620 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3621 r"c:\src\rust\cargo-test\test",
3625 relative_from: Some("Cargo.toml")
3628 tc!(r"c:\foo", r"C:\foo",
3632 relative_from: Some("")
3638 fn test_components_debug() {
3639 let path = Path::new("/tmp");
3641 let mut components = path.components();
3643 let expected = "Components([RootDir, Normal(\"tmp\")])";
3644 let actual = format!("{:?}", components);
3645 assert_eq!(expected, actual);
3647 let _ = components.next().unwrap();
3648 let expected = "Components([Normal(\"tmp\")])";
3649 let actual = format!("{:?}", components);
3650 assert_eq!(expected, actual);
3652 let _ = components.next().unwrap();
3653 let expected = "Components([])";
3654 let actual = format!("{:?}", components);
3655 assert_eq!(expected, actual);
3660 fn test_iter_debug() {
3661 let path = Path::new("/tmp");
3663 let mut iter = path.iter();
3665 let expected = "Iter([\"/\", \"tmp\"])";
3666 let actual = format!("{:?}", iter);
3667 assert_eq!(expected, actual);
3669 let _ = iter.next().unwrap();
3670 let expected = "Iter([\"tmp\"])";
3671 let actual = format!("{:?}", iter);
3672 assert_eq!(expected, actual);
3674 let _ = iter.next().unwrap();
3675 let expected = "Iter([])";
3676 let actual = format!("{:?}", iter);
3677 assert_eq!(expected, actual);