1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Cross-platform path manipulation.
13 //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
14 //! and [`str`]), for working with paths abstractly. These types are thin wrappers
15 //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
16 //! on strings according to the local platform's path syntax.
18 //! Paths can be parsed into [`Component`]s by iterating over the structure
19 //! returned by the [`components`] method on [`Path`]. [`Component`]s roughly
20 //! correspond to the substrings between path separators (`/` or `\`). You can
21 //! reconstruct an equivalent path from components with the [`push`] method on
22 //! [`PathBuf`]; note that the paths may differ syntactically by the
23 //! normalization described in the documentation for the [`components`] method.
27 //! Path manipulation includes both parsing components from slices and building
30 //! To parse a path, you can create a [`Path`] slice from a [`str`]
31 //! slice and start asking questions:
34 //! use std::path::Path;
35 //! use std::ffi::OsStr;
37 //! let path = Path::new("/tmp/foo/bar.txt");
39 //! let parent = path.parent();
40 //! assert_eq!(parent, Some(Path::new("/tmp/foo")));
42 //! let file_stem = path.file_stem();
43 //! assert_eq!(file_stem, Some(OsStr::new("bar")));
45 //! let extension = path.extension();
46 //! assert_eq!(extension, Some(OsStr::new("txt")));
49 //! To build or modify paths, use [`PathBuf`]:
52 //! use std::path::PathBuf;
54 //! // This way works...
55 //! let mut path = PathBuf::from("c:\\");
57 //! path.push("windows");
58 //! path.push("system32");
60 //! path.set_extension("dll");
62 //! // ... but push is best used if you don't know everything up
63 //! // front. If you do, this way is better:
64 //! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
67 //! [`Component`]: ../../std/path/enum.Component.html
68 //! [`components`]: ../../std/path/struct.Path.html#method.components
69 //! [`PathBuf`]: ../../std/path/struct.PathBuf.html
70 //! [`Path`]: ../../std/path/struct.Path.html
71 //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
72 //! [`String`]: ../../std/string/struct.String.html
74 //! [`str`]: ../../std/primitive.str.html
75 //! [`OsString`]: ../../std/ffi/struct.OsString.html
76 //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
78 #![stable(feature = "rust1", since = "1.0.0")]
81 use borrow::{Borrow, Cow};
86 use hash::{Hash, Hasher};
88 use iter::{self, FusedIterator};
90 use ops::{self, Deref};
92 use ffi::{OsStr, OsString};
94 use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
96 ////////////////////////////////////////////////////////////////////////////////
98 ////////////////////////////////////////////////////////////////////////////////
100 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
101 // taking advantage of the fact that OsStr always encodes ASCII characters
102 // as-is. Eventually, this transmutation should be replaced by direct uses of
103 // OsStr APIs for parsing, but it will take a while for those to become
106 ////////////////////////////////////////////////////////////////////////////////
108 ////////////////////////////////////////////////////////////////////////////////
110 /// Windows path prefixes, e.g. `C:` or `\\server\share`.
112 /// Windows uses a variety of path prefix styles, including references to drive
113 /// volumes (like `C:`), network shared folders (like `\\server\share`), and
114 /// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with
115 /// `\\?\`), in which case `/` is *not* treated as a separator and essentially
116 /// no normalization is performed.
121 /// use std::path::{Component, Path, Prefix};
122 /// use std::path::Prefix::*;
123 /// use std::ffi::OsStr;
125 /// fn get_path_prefix(s: &str) -> Prefix {
126 /// let path = Path::new(s);
127 /// match path.components().next().unwrap() {
128 /// Component::Prefix(prefix_component) => prefix_component.kind(),
133 /// # if cfg!(windows) {
134 /// assert_eq!(Verbatim(OsStr::new("pictures")),
135 /// get_path_prefix(r"\\?\pictures\kittens"));
136 /// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")),
137 /// get_path_prefix(r"\\?\UNC\server\share"));
138 /// assert_eq!(VerbatimDisk('C' as u8), get_path_prefix(r"\\?\c:\"));
139 /// assert_eq!(DeviceNS(OsStr::new("BrainInterface")),
140 /// get_path_prefix(r"\\.\BrainInterface"));
141 /// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")),
142 /// get_path_prefix(r"\\server\share"));
143 /// assert_eq!(Disk('C' as u8), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
146 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub enum Prefix<'a> {
149 /// Verbatim prefix, e.g. `\\?\cat_pics`.
151 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
153 #[stable(feature = "rust1", since = "1.0.0")]
154 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
156 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
157 /// e.g. `\\?\UNC\server\share`.
159 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
160 /// server's hostname and a share name.
161 #[stable(feature = "rust1", since = "1.0.0")]
163 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
164 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
167 /// Verbatim disk prefix, e.g. `\\?\C:\`.
169 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
170 /// drive letter and `:\`.
171 #[stable(feature = "rust1", since = "1.0.0")]
172 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
174 /// Device namespace prefix, e.g. `\\.\COM42`.
176 /// Device namespace prefixes consist of `\\.\` immediately followed by the
178 #[stable(feature = "rust1", since = "1.0.0")]
179 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
181 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
182 /// `\\server\share`.
184 /// UNC prefixes consist of the server's hostname and a share name.
185 #[stable(feature = "rust1", since = "1.0.0")]
187 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
188 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
191 /// Prefix `C:` for the given disk drive.
192 #[stable(feature = "rust1", since = "1.0.0")]
193 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
196 impl<'a> Prefix<'a> {
198 fn len(&self) -> usize {
200 fn os_str_len(s: &OsStr) -> usize {
201 os_str_as_u8_slice(s).len()
204 Verbatim(x) => 4 + os_str_len(x),
205 VerbatimUNC(x, y) => {
207 if os_str_len(y) > 0 {
213 VerbatimDisk(_) => 6,
216 if os_str_len(y) > 0 {
222 DeviceNS(x) => 4 + os_str_len(x),
228 /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
233 /// use std::path::Prefix::*;
234 /// use std::ffi::OsStr;
236 /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim());
237 /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
238 /// assert!(VerbatimDisk('C' as u8).is_verbatim());
239 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
240 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
241 /// assert!(!Disk('C' as u8).is_verbatim());
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn is_verbatim(&self) -> bool {
248 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
254 fn is_drive(&self) -> bool {
256 Prefix::Disk(_) => true,
262 fn has_implicit_root(&self) -> bool {
267 ////////////////////////////////////////////////////////////////////////////////
268 // Exposed parsing helpers
269 ////////////////////////////////////////////////////////////////////////////////
271 /// Determines whether the character is one of the permitted path
272 /// separators for the current platform.
279 /// assert!(path::is_separator('/'));
280 /// assert!(!path::is_separator('❤'));
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn is_separator(c: char) -> bool {
284 c.is_ascii() && is_sep_byte(c as u8)
287 /// The primary separator of path components for the current platform.
289 /// For example, `/` on Unix and `\` on Windows.
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP;
293 ////////////////////////////////////////////////////////////////////////////////
295 ////////////////////////////////////////////////////////////////////////////////
297 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
298 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
299 // `iter` after having exhausted `prefix`.
300 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
301 where I: Iterator<Item = A> + Clone,
302 J: Iterator<Item = A>,
306 let mut iter_next = iter.clone();
307 match (iter_next.next(), prefix.next()) {
308 (Some(ref x), Some(ref y)) if x == y => (),
309 (Some(_), Some(_)) => return None,
310 (Some(_), None) => return Some(iter),
311 (None, None) => return Some(iter),
312 (None, Some(_)) => return None,
318 // See note at the top of this module to understand why these are used:
319 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
320 unsafe { mem::transmute(s) }
322 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
326 ////////////////////////////////////////////////////////////////////////////////
327 // Cross-platform, iterator-independent parsing
328 ////////////////////////////////////////////////////////////////////////////////
330 /// Says whether the first byte after the prefix is a separator.
331 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
332 let path = if let Some(p) = prefix {
337 !path.is_empty() && is_sep_byte(path[0])
340 // basic workhorse for splitting stem and extension
341 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
343 if os_str_as_u8_slice(file) == b".." {
344 return (Some(file), None);
347 // The unsafety here stems from converting between &OsStr and &[u8]
348 // and back. This is safe to do because (1) we only look at ASCII
349 // contents of the encoding and (2) new &OsStr values are produced
350 // only from ASCII-bounded slices of existing &OsStr values.
352 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
353 let after = iter.next();
354 let before = iter.next();
355 if before == Some(b"") {
358 (before.map(|s| u8_slice_as_os_str(s)),
359 after.map(|s| u8_slice_as_os_str(s)))
364 ////////////////////////////////////////////////////////////////////////////////
365 // The core iterators
366 ////////////////////////////////////////////////////////////////////////////////
368 /// Component parsing works by a double-ended state machine; the cursors at the
369 /// front and back of the path each keep track of what parts of the path have
370 /// been consumed so far.
372 /// Going front to back, a path is made up of a prefix, a starting
373 /// directory component, and a body (of normal components)
374 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
377 StartDir = 1, // / or . or nothing
378 Body = 2, // foo/bar/baz
382 /// A structure wrapping a Windows path prefix as well as its unparsed string
385 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
386 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
387 /// returned by [`as_os_str`].
389 /// Instances of this `struct` can be obtained by matching against the
390 /// [`Prefix` variant] on [`Component`].
392 /// Does not occur on Unix.
397 /// # if cfg!(windows) {
398 /// use std::path::{Component, Path, Prefix};
399 /// use std::ffi::OsStr;
401 /// let path = Path::new(r"c:\you\later\");
402 /// match path.components().next().unwrap() {
403 /// Component::Prefix(prefix_component) => {
404 /// assert_eq!(Prefix::Disk('C' as u8), prefix_component.kind());
405 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
407 /// _ => unreachable!(),
412 /// [`as_os_str`]: #method.as_os_str
413 /// [`Component`]: enum.Component.html
414 /// [`kind`]: #method.kind
415 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
416 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
417 /// [`Prefix`]: enum.Prefix.html
418 #[stable(feature = "rust1", since = "1.0.0")]
419 #[derive(Copy, Clone, Eq, Debug)]
420 pub struct PrefixComponent<'a> {
421 /// The prefix as an unparsed `OsStr` slice.
424 /// The parsed prefix data.
428 impl<'a> PrefixComponent<'a> {
429 /// Returns the parsed prefix data.
431 /// See [`Prefix`]'s documentation for more information on the different
432 /// kinds of prefixes.
434 /// [`Prefix`]: enum.Prefix.html
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn kind(&self) -> Prefix<'a> {
440 /// Returns the raw [`OsStr`] slice for this prefix.
442 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn as_os_str(&self) -> &'a OsStr {
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
451 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
452 cmp::PartialEq::eq(&self.parsed, &other.parsed)
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
458 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
459 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl<'a> cmp::Ord for PrefixComponent<'a> {
465 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
466 cmp::Ord::cmp(&self.parsed, &other.parsed)
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<'a> Hash for PrefixComponent<'a> {
472 fn hash<H: Hasher>(&self, h: &mut H) {
477 /// A single component of a path.
479 /// A `Component` roughtly corresponds to a substring between path separators
482 /// This `enum` is created by iterating over [`Components`], which in turn is
483 /// created by the [`components`][`Path::components`] method on [`Path`].
488 /// use std::path::{Component, Path};
490 /// let path = Path::new("/tmp/foo/bar.txt");
491 /// let components = path.components().collect::<Vec<_>>();
492 /// assert_eq!(&components, &[
493 /// Component::RootDir,
494 /// Component::Normal("tmp".as_ref()),
495 /// Component::Normal("foo".as_ref()),
496 /// Component::Normal("bar.txt".as_ref()),
500 /// [`Components`]: struct.Components.html
501 /// [`Path`]: struct.Path.html
502 /// [`Path::components`]: struct.Path.html#method.components
503 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub enum Component<'a> {
506 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
508 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
511 /// Does not occur on Unix.
513 /// [`Prefix`]: enum.Prefix.html
514 #[stable(feature = "rust1", since = "1.0.0")]
516 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
519 /// The root directory component, appears after any prefix and before anything else.
521 /// It represents a separator that designates that a path starts from root.
522 #[stable(feature = "rust1", since = "1.0.0")]
525 /// A reference to the current directory, i.e. `.`.
526 #[stable(feature = "rust1", since = "1.0.0")]
529 /// A reference to the parent directory, i.e. `..`.
530 #[stable(feature = "rust1", since = "1.0.0")]
533 /// A normal component, e.g. `a` and `b` in `a/b`.
535 /// This variant is the most common one, it represents references to files
537 #[stable(feature = "rust1", since = "1.0.0")]
538 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
541 impl<'a> Component<'a> {
542 /// Extracts the underlying [`OsStr`] slice.
547 /// use std::path::Path;
549 /// let path = Path::new("./tmp/foo/bar.txt");
550 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
551 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
554 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub fn as_os_str(self) -> &'a OsStr {
558 Component::Prefix(p) => p.as_os_str(),
559 Component::RootDir => OsStr::new(MAIN_SEP_STR),
560 Component::CurDir => OsStr::new("."),
561 Component::ParentDir => OsStr::new(".."),
562 Component::Normal(path) => path,
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl<'a> AsRef<OsStr> for Component<'a> {
569 fn as_ref(&self) -> &OsStr {
574 /// An interator over the [`Component`]s of a [`Path`].
576 /// This `struct` is created by the [`components`] method on [`Path`].
577 /// See its documentation for more.
582 /// use std::path::Path;
584 /// let path = Path::new("/tmp/foo/bar.txt");
586 /// for component in path.components() {
587 /// println!("{:?}", component);
591 /// [`Component`]: enum.Component.html
592 /// [`components`]: struct.Path.html#method.components
593 /// [`Path`]: struct.Path.html
595 #[stable(feature = "rust1", since = "1.0.0")]
596 pub struct Components<'a> {
597 // The path left to parse components from
600 // The prefix as it was originally parsed, if any
601 prefix: Option<Prefix<'a>>,
603 // true if path *physically* has a root separator; for most Windows
604 // prefixes, it may have a "logical" rootseparator for the purposes of
605 // normalization, e.g. \\server\share == \\server\share\.
606 has_physical_root: bool,
608 // The iterator is double-ended, and these two states keep track of what has
609 // been produced from either end
614 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
616 /// This `struct` is created by the [`iter`] method on [`Path`].
617 /// See its documentation for more.
619 /// [`Component`]: enum.Component.html
620 /// [`iter`]: struct.Path.html#method.iter
621 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
622 /// [`Path`]: struct.Path.html
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub struct Iter<'a> {
626 inner: Components<'a>,
629 #[stable(feature = "path_components_debug", since = "1.13.0")]
630 impl<'a> fmt::Debug for Components<'a> {
631 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
632 struct DebugHelper<'a>(&'a Path);
634 impl<'a> fmt::Debug for DebugHelper<'a> {
635 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637 .entries(self.0.components())
642 f.debug_tuple("Components")
643 .field(&DebugHelper(self.as_path()))
648 impl<'a> Components<'a> {
649 // how long is the prefix, if any?
651 fn prefix_len(&self) -> usize {
652 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
656 fn prefix_verbatim(&self) -> bool {
657 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
660 /// how much of the prefix is left from the point of view of iteration?
662 fn prefix_remaining(&self) -> usize {
663 if self.front == State::Prefix {
670 // Given the iteration so far, how much of the pre-State::Body path is left?
672 fn len_before_body(&self) -> usize {
673 let root = if self.front <= State::StartDir && self.has_physical_root {
678 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
683 self.prefix_remaining() + root + cur_dir
686 // is the iteration complete?
688 fn finished(&self) -> bool {
689 self.front == State::Done || self.back == State::Done || self.front > self.back
693 fn is_sep_byte(&self, b: u8) -> bool {
694 if self.prefix_verbatim() {
701 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
706 /// use std::path::Path;
708 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
709 /// components.next();
710 /// components.next();
712 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn as_path(&self) -> &'a Path {
716 let mut comps = self.clone();
717 if comps.front == State::Body {
720 if comps.back == State::Body {
723 unsafe { Path::from_u8_slice(comps.path) }
726 /// Is the *original* path rooted?
727 fn has_root(&self) -> bool {
728 if self.has_physical_root {
731 if let Some(p) = self.prefix {
732 if p.has_implicit_root() {
739 /// Should the normalized path include a leading . ?
740 fn include_cur_dir(&self) -> bool {
744 let mut iter = self.path[self.prefix_len()..].iter();
745 match (iter.next(), iter.next()) {
746 (Some(&b'.'), None) => true,
747 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
752 // parse a given byte sequence into the corresponding path component
753 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
755 b"." if self.prefix_verbatim() => Some(Component::CurDir),
756 b"." => None, // . components are normalized away, except at
757 // the beginning of a path, which is treated
758 // separately via `include_cur_dir`
759 b".." => Some(Component::ParentDir),
761 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
765 // parse a component from the left, saying how many bytes to consume to
766 // remove the component
767 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
768 debug_assert!(self.front == State::Body);
769 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
770 None => (0, self.path),
771 Some(i) => (1, &self.path[..i]),
773 (comp.len() + extra, self.parse_single_component(comp))
776 // parse a component from the right, saying how many bytes to consume to
777 // remove the component
778 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
779 debug_assert!(self.back == State::Body);
780 let start = self.len_before_body();
781 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
782 None => (0, &self.path[start..]),
783 Some(i) => (1, &self.path[start + i + 1..]),
785 (comp.len() + extra, self.parse_single_component(comp))
788 // trim away repeated separators (i.e. empty components) on the left
789 fn trim_left(&mut self) {
790 while !self.path.is_empty() {
791 let (size, comp) = self.parse_next_component();
795 self.path = &self.path[size..];
800 // trim away repeated separators (i.e. empty components) on the right
801 fn trim_right(&mut self) {
802 while self.path.len() > self.len_before_body() {
803 let (size, comp) = self.parse_next_component_back();
807 self.path = &self.path[..self.path.len() - size];
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl<'a> AsRef<Path> for Components<'a> {
815 fn as_ref(&self) -> &Path {
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<'a> AsRef<OsStr> for Components<'a> {
822 fn as_ref(&self) -> &OsStr {
823 self.as_path().as_os_str()
827 #[stable(feature = "path_iter_debug", since = "1.13.0")]
828 impl<'a> fmt::Debug for Iter<'a> {
829 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
830 struct DebugHelper<'a>(&'a Path);
832 impl<'a> fmt::Debug for DebugHelper<'a> {
833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
835 .entries(self.0.iter())
840 f.debug_tuple("Iter")
841 .field(&DebugHelper(self.as_path()))
847 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
852 /// use std::path::Path;
854 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
858 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
860 #[stable(feature = "rust1", since = "1.0.0")]
861 pub fn as_path(&self) -> &'a Path {
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a> AsRef<Path> for Iter<'a> {
868 fn as_ref(&self) -> &Path {
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<'a> AsRef<OsStr> for Iter<'a> {
875 fn as_ref(&self) -> &OsStr {
876 self.as_path().as_os_str()
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl<'a> Iterator for Iter<'a> {
882 type Item = &'a OsStr;
884 fn next(&mut self) -> Option<&'a OsStr> {
885 self.inner.next().map(Component::as_os_str)
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<'a> DoubleEndedIterator for Iter<'a> {
891 fn next_back(&mut self) -> Option<&'a OsStr> {
892 self.inner.next_back().map(Component::as_os_str)
896 #[unstable(feature = "fused", issue = "35602")]
897 impl<'a> FusedIterator for Iter<'a> {}
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl<'a> Iterator for Components<'a> {
901 type Item = Component<'a>;
903 fn next(&mut self) -> Option<Component<'a>> {
904 while !self.finished() {
906 State::Prefix if self.prefix_len() > 0 => {
907 self.front = State::StartDir;
908 debug_assert!(self.prefix_len() <= self.path.len());
909 let raw = &self.path[..self.prefix_len()];
910 self.path = &self.path[self.prefix_len()..];
911 return Some(Component::Prefix(PrefixComponent {
912 raw: unsafe { u8_slice_as_os_str(raw) },
913 parsed: self.prefix.unwrap(),
917 self.front = State::StartDir;
920 self.front = State::Body;
921 if self.has_physical_root {
922 debug_assert!(!self.path.is_empty());
923 self.path = &self.path[1..];
924 return Some(Component::RootDir);
925 } else if let Some(p) = self.prefix {
926 if p.has_implicit_root() && !p.is_verbatim() {
927 return Some(Component::RootDir);
929 } else if self.include_cur_dir() {
930 debug_assert!(!self.path.is_empty());
931 self.path = &self.path[1..];
932 return Some(Component::CurDir);
935 State::Body if !self.path.is_empty() => {
936 let (size, comp) = self.parse_next_component();
937 self.path = &self.path[size..];
943 self.front = State::Done;
945 State::Done => unreachable!(),
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a> DoubleEndedIterator for Components<'a> {
954 fn next_back(&mut self) -> Option<Component<'a>> {
955 while !self.finished() {
957 State::Body if self.path.len() > self.len_before_body() => {
958 let (size, comp) = self.parse_next_component_back();
959 self.path = &self.path[..self.path.len() - size];
965 self.back = State::StartDir;
968 self.back = State::Prefix;
969 if self.has_physical_root {
970 self.path = &self.path[..self.path.len() - 1];
971 return Some(Component::RootDir);
972 } else if let Some(p) = self.prefix {
973 if p.has_implicit_root() && !p.is_verbatim() {
974 return Some(Component::RootDir);
976 } else if self.include_cur_dir() {
977 self.path = &self.path[..self.path.len() - 1];
978 return Some(Component::CurDir);
981 State::Prefix if self.prefix_len() > 0 => {
982 self.back = State::Done;
983 return Some(Component::Prefix(PrefixComponent {
984 raw: unsafe { u8_slice_as_os_str(self.path) },
985 parsed: self.prefix.unwrap(),
989 self.back = State::Done;
992 State::Done => unreachable!(),
999 #[unstable(feature = "fused", issue = "35602")]
1000 impl<'a> FusedIterator for Components<'a> {}
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl<'a> cmp::PartialEq for Components<'a> {
1004 fn eq(&self, other: &Components<'a>) -> bool {
1005 Iterator::eq(self.clone(), other.clone())
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 impl<'a> cmp::Eq for Components<'a> {}
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<'a> cmp::PartialOrd for Components<'a> {
1014 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1015 Iterator::partial_cmp(self.clone(), other.clone())
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 impl<'a> cmp::Ord for Components<'a> {
1021 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
1022 Iterator::cmp(self.clone(), other.clone())
1026 ////////////////////////////////////////////////////////////////////////////////
1027 // Basic types and traits
1028 ////////////////////////////////////////////////////////////////////////////////
1030 /// An owned, mutable path (akin to [`String`]).
1032 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1033 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1034 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1036 /// [`String`]: ../string/struct.String.html
1037 /// [`Path`]: struct.Path.html
1038 /// [`push`]: struct.PathBuf.html#method.push
1039 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1040 /// [`Deref`]: ../ops/trait.Deref.html
1042 /// More details about the overall approach can be found in
1043 /// the module documentation.
1047 /// You can use [`push`] to build up a `PathBuf` from
1051 /// use std::path::PathBuf;
1053 /// let mut path = PathBuf::new();
1055 /// path.push(r"C:\");
1056 /// path.push("windows");
1057 /// path.push("system32");
1059 /// path.set_extension("dll");
1062 /// However, [`push`] is best used for dynamic situations. This is a better way
1063 /// to do this when you know all of the components ahead of time:
1066 /// use std::path::PathBuf;
1068 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1071 /// We can still do better than this! Since these are all strings, we can use
1075 /// use std::path::PathBuf;
1077 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1080 /// Which method works best depends on what kind of situation you're in.
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 pub struct PathBuf {
1088 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1089 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1092 /// Allocates an empty `PathBuf`.
1097 /// use std::path::PathBuf;
1099 /// let path = PathBuf::new();
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 pub fn new() -> PathBuf {
1103 PathBuf { inner: OsString::new() }
1106 /// Coerces to a [`Path`] slice.
1108 /// [`Path`]: struct.Path.html
1113 /// use std::path::{Path, PathBuf};
1115 /// let p = PathBuf::from("/test");
1116 /// assert_eq!(Path::new("/test"), p.as_path());
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub fn as_path(&self) -> &Path {
1123 /// Extends `self` with `path`.
1125 /// If `path` is absolute, it replaces the current path.
1129 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1130 /// replaces everything except for the prefix (if any) of `self`.
1131 /// * if `path` has a prefix but no root, it replaces `self`.
1135 /// Pushing a relative path extends the existing path:
1138 /// use std::path::PathBuf;
1140 /// let mut path = PathBuf::from("/tmp");
1141 /// path.push("file.bk");
1142 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1145 /// Pushing an absolute path replaces the existing path:
1148 /// use std::path::PathBuf;
1150 /// let mut path = PathBuf::from("/tmp");
1151 /// path.push("/etc");
1152 /// assert_eq!(path, PathBuf::from("/etc"));
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1156 self._push(path.as_ref())
1159 fn _push(&mut self, path: &Path) {
1160 // in general, a separator is needed if the rightmost byte is not a separator
1161 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1163 // in the special case of `C:` on Windows, do *not* add a separator
1165 let comps = self.components();
1166 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1167 comps.prefix.unwrap().is_drive() {
1172 // absolute `path` replaces `self`
1173 if path.is_absolute() || path.prefix().is_some() {
1174 self.as_mut_vec().truncate(0);
1176 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1177 } else if path.has_root() {
1178 let prefix_len = self.components().prefix_remaining();
1179 self.as_mut_vec().truncate(prefix_len);
1181 // `path` is a pure relative path
1182 } else if need_sep {
1183 self.inner.push(MAIN_SEP_STR);
1186 self.inner.push(path);
1189 /// Truncate `self` to [`self.parent`].
1191 /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1192 /// Otherwise, returns `true`.
1194 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1195 /// [`self.parent`]: struct.PathBuf.html#method.parent
1196 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1201 /// use std::path::{Path, PathBuf};
1203 /// let mut p = PathBuf::from("/test/test.rs");
1206 /// assert_eq!(Path::new("/test"), p);
1208 /// assert_eq!(Path::new("/"), p);
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 pub fn pop(&mut self) -> bool {
1212 match self.parent().map(|p| p.as_u8_slice().len()) {
1214 self.as_mut_vec().truncate(len);
1221 /// Updates [`self.file_name`] to `file_name`.
1223 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1226 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1227 /// `file_name`. The new path will be a sibling of the original path.
1228 /// (That is, it will have the same parent.)
1230 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1231 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1232 /// [`pop`]: struct.PathBuf.html#method.pop
1237 /// use std::path::PathBuf;
1239 /// let mut buf = PathBuf::from("/");
1240 /// assert!(buf.file_name() == None);
1241 /// buf.set_file_name("bar");
1242 /// assert!(buf == PathBuf::from("/bar"));
1243 /// assert!(buf.file_name().is_some());
1244 /// buf.set_file_name("baz.txt");
1245 /// assert!(buf == PathBuf::from("/baz.txt"));
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1249 self._set_file_name(file_name.as_ref())
1252 fn _set_file_name(&mut self, file_name: &OsStr) {
1253 if self.file_name().is_some() {
1254 let popped = self.pop();
1255 debug_assert!(popped);
1257 self.push(file_name);
1260 /// Updates [`self.extension`] to `extension`.
1262 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1263 /// returns `true` and updates the extension otherwise.
1265 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1268 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1269 /// [`self.extension`]: struct.PathBuf.html#method.extension
1270 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1275 /// use std::path::{Path, PathBuf};
1277 /// let mut p = PathBuf::from("/feel/the");
1279 /// p.set_extension("force");
1280 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1282 /// p.set_extension("dark_side");
1283 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1287 self._set_extension(extension.as_ref())
1290 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1291 if self.file_name().is_none() {
1295 let mut stem = match self.file_stem() {
1296 Some(stem) => stem.to_os_string(),
1297 None => OsString::new(),
1300 if !os_str_as_u8_slice(extension).is_empty() {
1302 stem.push(extension);
1304 self.set_file_name(&stem);
1309 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1311 /// [`OsString`]: ../ffi/struct.OsString.html
1316 /// use std::path::PathBuf;
1318 /// let p = PathBuf::from("/the/head");
1319 /// let os_str = p.into_os_string();
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 pub fn into_os_string(self) -> OsString {
1326 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1328 /// [`Box`]: ../../std/boxed/struct.Box.html
1329 /// [`Path`]: struct.Path.html
1330 #[unstable(feature = "into_boxed_path", issue = "40380")]
1331 pub fn into_boxed_path(self) -> Box<Path> {
1332 unsafe { mem::transmute(self.inner.into_boxed_os_str()) }
1336 #[stable(feature = "box_from_path", since = "1.17.0")]
1337 impl<'a> From<&'a Path> for Box<Path> {
1338 fn from(path: &'a Path) -> Box<Path> {
1339 let boxed: Box<OsStr> = path.inner.into();
1340 unsafe { mem::transmute(boxed) }
1344 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1345 impl From<Box<Path>> for PathBuf {
1346 fn from(boxed: Box<Path>) -> PathBuf {
1347 boxed.into_path_buf()
1351 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1352 impl From<PathBuf> for Box<Path> {
1353 fn from(p: PathBuf) -> Box<Path> {
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1360 fn from(s: &'a T) -> PathBuf {
1361 PathBuf::from(s.as_ref().to_os_string())
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl From<OsString> for PathBuf {
1367 fn from(s: OsString) -> PathBuf {
1368 PathBuf { inner: s }
1372 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1373 impl From<PathBuf> for OsString {
1374 fn from(path_buf : PathBuf) -> OsString {
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl From<String> for PathBuf {
1381 fn from(s: String) -> PathBuf {
1382 PathBuf::from(OsString::from(s))
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1388 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1389 let mut buf = PathBuf::new();
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1397 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1399 self.push(p.as_ref())
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 impl fmt::Debug for PathBuf {
1406 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1407 fmt::Debug::fmt(&**self, formatter)
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl ops::Deref for PathBuf {
1415 fn deref(&self) -> &Path {
1416 Path::new(&self.inner)
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl Borrow<Path> for PathBuf {
1422 fn borrow(&self) -> &Path {
1427 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1428 impl Default for PathBuf {
1429 fn default() -> Self {
1434 #[stable(feature = "cow_from_path", since = "1.6.0")]
1435 impl<'a> From<&'a Path> for Cow<'a, Path> {
1437 fn from(s: &'a Path) -> Cow<'a, Path> {
1442 #[stable(feature = "cow_from_path", since = "1.6.0")]
1443 impl<'a> From<PathBuf> for Cow<'a, Path> {
1445 fn from(s: PathBuf) -> Cow<'a, Path> {
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 impl ToOwned for Path {
1452 type Owned = PathBuf;
1453 fn to_owned(&self) -> PathBuf {
1456 fn clone_into(&self, target: &mut PathBuf) {
1457 self.inner.clone_into(&mut target.inner);
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl cmp::PartialEq for PathBuf {
1463 fn eq(&self, other: &PathBuf) -> bool {
1464 self.components() == other.components()
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 impl Hash for PathBuf {
1470 fn hash<H: Hasher>(&self, h: &mut H) {
1471 self.as_path().hash(h)
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl cmp::Eq for PathBuf {}
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl cmp::PartialOrd for PathBuf {
1480 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1481 self.components().partial_cmp(other.components())
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl cmp::Ord for PathBuf {
1487 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1488 self.components().cmp(other.components())
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl AsRef<OsStr> for PathBuf {
1494 fn as_ref(&self) -> &OsStr {
1499 /// A slice of a path (akin to [`str`]).
1501 /// This type supports a number of operations for inspecting a path, including
1502 /// breaking the path into its components (separated by `/` or `\`, depending on
1503 /// the platform), extracting the file name, determining whether the path is
1504 /// absolute, and so on.
1506 /// This is an *unsized* type, meaning that it must always be used behind a
1507 /// pointer like `&` or [`Box`]. For an owned version of this type,
1508 /// see [`PathBuf`].
1510 /// [`str`]: ../primitive.str.html
1511 /// [`Box`]: ../boxed/struct.Box.html
1512 /// [`PathBuf`]: struct.PathBuf.html
1514 /// More details about the overall approach can be found in
1515 /// the module documentation.
1520 /// use std::path::Path;
1521 /// use std::ffi::OsStr;
1523 /// let path = Path::new("/tmp/foo/bar.txt");
1525 /// let parent = path.parent();
1526 /// assert_eq!(parent, Some(Path::new("/tmp/foo")));
1528 /// let file_stem = path.file_stem();
1529 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1531 /// let extension = path.extension();
1532 /// assert_eq!(extension, Some(OsStr::new("txt")));
1534 #[stable(feature = "rust1", since = "1.0.0")]
1539 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1542 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1543 /// See its documentation for more.
1545 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1546 /// [`Path`]: struct.Path.html
1547 #[derive(Debug, Clone, PartialEq, Eq)]
1548 #[stable(since = "1.7.0", feature = "strip_prefix")]
1549 pub struct StripPrefixError(());
1552 // The following (private!) function allows construction of a path from a u8
1553 // slice, which is only safe when it is known to follow the OsStr encoding.
1554 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1555 Path::new(u8_slice_as_os_str(s))
1557 // The following (private!) function reveals the byte encoding used for OsStr.
1558 fn as_u8_slice(&self) -> &[u8] {
1559 os_str_as_u8_slice(&self.inner)
1562 /// Directly wraps a string slice as a `Path` slice.
1564 /// This is a cost-free conversion.
1569 /// use std::path::Path;
1571 /// Path::new("foo.txt");
1574 /// You can create `Path`s from `String`s, or even other `Path`s:
1577 /// use std::path::Path;
1579 /// let string = String::from("foo.txt");
1580 /// let from_string = Path::new(&string);
1581 /// let from_path = Path::new(&from_string);
1582 /// assert_eq!(from_string, from_path);
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1586 unsafe { mem::transmute(s.as_ref()) }
1589 /// Yields the underlying [`OsStr`] slice.
1591 /// [`OsStr`]: ../ffi/struct.OsStr.html
1596 /// use std::path::Path;
1598 /// let os_str = Path::new("foo.txt").as_os_str();
1599 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 pub fn as_os_str(&self) -> &OsStr {
1606 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1608 /// This conversion may entail doing a check for UTF-8 validity.
1610 /// [`&str`]: ../primitive.str.html
1615 /// use std::path::Path;
1617 /// let path = Path::new("foo.txt");
1618 /// assert_eq!(path.to_str(), Some("foo.txt"));
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 pub fn to_str(&self) -> Option<&str> {
1625 /// Converts a `Path` to a [`Cow<str>`].
1627 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1629 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1633 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1636 /// use std::path::Path;
1638 /// let path = Path::new("foo.txt");
1639 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1642 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1643 /// have returned `"fo�.txt"`.
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn to_string_lossy(&self) -> Cow<str> {
1646 self.inner.to_string_lossy()
1649 /// Converts a `Path` to an owned [`PathBuf`].
1651 /// [`PathBuf`]: struct.PathBuf.html
1656 /// use std::path::Path;
1658 /// let path_buf = Path::new("foo.txt").to_path_buf();
1659 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 pub fn to_path_buf(&self) -> PathBuf {
1663 PathBuf::from(self.inner.to_os_string())
1666 /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
1667 /// the current directory.
1669 /// * On Unix, a path is absolute if it starts with the root, so
1670 /// `is_absolute` and [`has_root`] are equivalent.
1672 /// * On Windows, a path is absolute if it has a prefix and starts with the
1673 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1678 /// use std::path::Path;
1680 /// assert!(!Path::new("foo.txt").is_absolute());
1683 /// [`has_root`]: #method.has_root
1684 #[stable(feature = "rust1", since = "1.0.0")]
1685 #[allow(deprecated)]
1686 pub fn is_absolute(&self) -> bool {
1687 // FIXME: Remove target_os = "redox" and allow Redox prefixes
1688 self.has_root() && (cfg!(unix) || cfg!(target_os = "redox") || self.prefix().is_some())
1691 /// Return `false` if the `Path` is relative, i.e. not absolute.
1693 /// See [`is_absolute`]'s documentation for more details.
1698 /// use std::path::Path;
1700 /// assert!(Path::new("foo.txt").is_relative());
1703 /// [`is_absolute`]: #method.is_absolute
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub fn is_relative(&self) -> bool {
1709 fn prefix(&self) -> Option<Prefix> {
1710 self.components().prefix
1713 /// Returns `true` if the `Path` has a root.
1715 /// * On Unix, a path has a root if it begins with `/`.
1717 /// * On Windows, a path has a root if it:
1718 /// * has no prefix and begins with a separator, e.g. `\\windows`
1719 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1720 /// * has any non-disk prefix, e.g. `\\server\share`
1725 /// use std::path::Path;
1727 /// assert!(Path::new("/etc/passwd").has_root());
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 pub fn has_root(&self) -> bool {
1731 self.components().has_root()
1734 /// Returns the `Path` without its final component, if there is one.
1736 /// Returns [`None`] if the path terminates in a root or prefix.
1738 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1743 /// use std::path::Path;
1745 /// let path = Path::new("/foo/bar");
1746 /// let parent = path.parent().unwrap();
1747 /// assert_eq!(parent, Path::new("/foo"));
1749 /// let grand_parent = parent.parent().unwrap();
1750 /// assert_eq!(grand_parent, Path::new("/"));
1751 /// assert_eq!(grand_parent.parent(), None);
1753 #[stable(feature = "rust1", since = "1.0.0")]
1754 pub fn parent(&self) -> Option<&Path> {
1755 let mut comps = self.components();
1756 let comp = comps.next_back();
1759 Component::Normal(_) |
1761 Component::ParentDir => Some(comps.as_path()),
1767 /// Returns the final component of the `Path`, if there is one.
1769 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1770 /// is the directory name.
1772 /// Returns [`None`] If the path terminates in `..`.
1774 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1779 /// use std::path::Path;
1780 /// use std::ffi::OsStr;
1782 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1783 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1784 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1785 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1786 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1787 /// assert_eq!(None, Path::new("/").file_name());
1789 #[stable(feature = "rust1", since = "1.0.0")]
1790 pub fn file_name(&self) -> Option<&OsStr> {
1791 self.components().next_back().and_then(|p| {
1793 Component::Normal(p) => Some(p.as_ref()),
1799 /// Returns a path that, when joined onto `base`, yields `self`.
1803 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1804 /// returns `false`), returns [`Err`].
1806 /// [`starts_with`]: #method.starts_with
1807 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1812 /// use std::path::Path;
1814 /// let path = Path::new("/test/haha/foo.txt");
1816 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1817 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1818 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1820 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1821 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1822 -> Result<&'a Path, StripPrefixError>
1823 where P: AsRef<Path>
1825 self._strip_prefix(base.as_ref())
1828 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1829 -> Result<&'a Path, StripPrefixError> {
1830 iter_after(self.components(), base.components())
1831 .map(|c| c.as_path())
1832 .ok_or(StripPrefixError(()))
1835 /// Determines whether `base` is a prefix of `self`.
1837 /// Only considers whole path components to match.
1842 /// use std::path::Path;
1844 /// let path = Path::new("/etc/passwd");
1846 /// assert!(path.starts_with("/etc"));
1848 /// assert!(!path.starts_with("/e"));
1850 #[stable(feature = "rust1", since = "1.0.0")]
1851 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1852 self._starts_with(base.as_ref())
1855 fn _starts_with(&self, base: &Path) -> bool {
1856 iter_after(self.components(), base.components()).is_some()
1859 /// Determines whether `child` is a suffix of `self`.
1861 /// Only considers whole path components to match.
1866 /// use std::path::Path;
1868 /// let path = Path::new("/etc/passwd");
1870 /// assert!(path.ends_with("passwd"));
1872 #[stable(feature = "rust1", since = "1.0.0")]
1873 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1874 self._ends_with(child.as_ref())
1877 fn _ends_with(&self, child: &Path) -> bool {
1878 iter_after(self.components().rev(), child.components().rev()).is_some()
1881 /// Extracts the stem (non-extension) portion of [`self.file_name`].
1883 /// [`self.file_name`]: struct.Path.html#method.file_name
1887 /// * [`None`], if there is no file name;
1888 /// * The entire file name if there is no embedded `.`;
1889 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1890 /// * Otherwise, the portion of the file name before the final `.`
1892 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1897 /// use std::path::Path;
1899 /// let path = Path::new("foo.rs");
1901 /// assert_eq!("foo", path.file_stem().unwrap());
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 pub fn file_stem(&self) -> Option<&OsStr> {
1905 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1908 /// Extracts the extension of [`self.file_name`], if possible.
1910 /// The extension is:
1912 /// * [`None`], if there is no file name;
1913 /// * [`None`], if there is no embedded `.`;
1914 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1915 /// * Otherwise, the portion of the file name after the final `.`
1917 /// [`self.file_name`]: struct.Path.html#method.file_name
1918 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1923 /// use std::path::Path;
1925 /// let path = Path::new("foo.rs");
1927 /// assert_eq!("rs", path.extension().unwrap());
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 pub fn extension(&self) -> Option<&OsStr> {
1931 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1934 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1936 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1938 /// [`PathBuf`]: struct.PathBuf.html
1939 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1944 /// use std::path::{Path, PathBuf};
1946 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1950 self._join(path.as_ref())
1953 fn _join(&self, path: &Path) -> PathBuf {
1954 let mut buf = self.to_path_buf();
1959 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1961 /// See [`PathBuf::set_file_name`] for more details.
1963 /// [`PathBuf`]: struct.PathBuf.html
1964 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1969 /// use std::path::{Path, PathBuf};
1971 /// let path = Path::new("/tmp/foo.txt");
1972 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1974 /// let path = Path::new("/tmp");
1975 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1979 self._with_file_name(file_name.as_ref())
1982 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1983 let mut buf = self.to_path_buf();
1984 buf.set_file_name(file_name);
1988 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
1990 /// See [`PathBuf::set_extension`] for more details.
1992 /// [`PathBuf`]: struct.PathBuf.html
1993 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
1998 /// use std::path::{Path, PathBuf};
2000 /// let path = Path::new("foo.rs");
2001 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2005 self._with_extension(extension.as_ref())
2008 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2009 let mut buf = self.to_path_buf();
2010 buf.set_extension(extension);
2014 /// Produces an iterator over the [`Component`]s of the path.
2016 /// When parsing the path, there is a small amount of normalization:
2018 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2019 /// `a` and `b` as components.
2021 /// * Occurentces of `.` are normalized away, exept if they are at the
2022 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2023 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2024 /// an additional [`CurDir`] component.
2026 /// Note that no other normalization takes place; in particular, `a/c`
2027 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2028 /// is a symbolic link (so its parent isn't `a`).
2033 /// use std::path::{Path, Component};
2034 /// use std::ffi::OsStr;
2036 /// let mut components = Path::new("/tmp/foo.txt").components();
2038 /// assert_eq!(components.next(), Some(Component::RootDir));
2039 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2040 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2041 /// assert_eq!(components.next(), None)
2044 /// [`Component`]: enum.Component.html
2045 /// [`CurDir`]: enum.Component.html#variant.CurDir
2046 #[stable(feature = "rust1", since = "1.0.0")]
2047 pub fn components(&self) -> Components {
2048 let prefix = parse_prefix(self.as_os_str());
2050 path: self.as_u8_slice(),
2052 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
2053 front: State::Prefix,
2058 /// Produces an iterator over the path's components viewed as [`OsStr`]
2061 /// For more information about the particulars of how the path is separated
2062 /// into components, see [`components`].
2064 /// [`components`]: #method.components
2065 /// [`OsStr`]: ../ffi/struct.OsStr.html
2070 /// use std::path::{self, Path};
2071 /// use std::ffi::OsStr;
2073 /// let mut it = Path::new("/tmp/foo.txt").iter();
2074 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2075 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2076 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2077 /// assert_eq!(it.next(), None)
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 pub fn iter(&self) -> Iter {
2081 Iter { inner: self.components() }
2084 /// Returns an object that implements [`Display`] for safely printing paths
2085 /// that may contain non-Unicode data.
2087 /// [`Display`]: ../fmt/trait.Display.html
2092 /// use std::path::Path;
2094 /// let path = Path::new("/tmp/foo.rs");
2096 /// println!("{}", path.display());
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 pub fn display(&self) -> Display {
2100 Display { path: self }
2103 /// Queries the file system to get information about a file, directory, etc.
2105 /// This function will traverse symbolic links to query information about the
2106 /// destination file.
2108 /// This is an alias to [`fs::metadata`].
2110 /// [`fs::metadata`]: ../fs/fn.metadata.html
2115 /// use std::path::Path;
2117 /// let path = Path::new("/Minas/tirith");
2118 /// let metadata = path.metadata().expect("metadata call failed");
2119 /// println!("{:?}", metadata.file_type());
2121 #[stable(feature = "path_ext", since = "1.5.0")]
2122 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2126 /// Queries the metadata about a file without following symlinks.
2128 /// This is an alias to [`fs::symlink_metadata`].
2130 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2135 /// use std::path::Path;
2137 /// let path = Path::new("/Minas/tirith");
2138 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2139 /// println!("{:?}", metadata.file_type());
2141 #[stable(feature = "path_ext", since = "1.5.0")]
2142 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2143 fs::symlink_metadata(self)
2146 /// Returns the canonical form of the path with all intermediate components
2147 /// normalized and symbolic links resolved.
2149 /// This is an alias to [`fs::canonicalize`].
2151 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2156 /// use std::path::{Path, PathBuf};
2158 /// let path = Path::new("/foo/test/../test/bar.rs");
2159 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2161 #[stable(feature = "path_ext", since = "1.5.0")]
2162 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2163 fs::canonicalize(self)
2166 /// Reads a symbolic link, returning the file that the link points to.
2168 /// This is an alias to [`fs::read_link`].
2170 /// [`fs::read_link`]: ../fs/fn.read_link.html
2175 /// use std::path::Path;
2177 /// let path = Path::new("/laputa/sky_castle.rs");
2178 /// let path_link = path.read_link().expect("read_link call failed");
2180 #[stable(feature = "path_ext", since = "1.5.0")]
2181 pub fn read_link(&self) -> io::Result<PathBuf> {
2185 /// Returns an iterator over the entries within a directory.
2187 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2188 /// errors may be encountered after an iterator is initially constructed.
2190 /// This is an alias to [`fs::read_dir`].
2192 /// [`io::Result`]: ../io/type.Result.html
2193 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2194 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2199 /// use std::path::Path;
2201 /// let path = Path::new("/laputa");
2202 /// for entry in path.read_dir().expect("read_dir call failed") {
2203 /// if let Ok(entry) = entry {
2204 /// println!("{:?}", entry.path());
2208 #[stable(feature = "path_ext", since = "1.5.0")]
2209 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2213 /// Returns whether the path points at an existing entity.
2215 /// This function will traverse symbolic links to query information about the
2216 /// destination file. In case of broken symbolic links this will return `false`.
2221 /// use std::path::Path;
2222 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2224 #[stable(feature = "path_ext", since = "1.5.0")]
2225 pub fn exists(&self) -> bool {
2226 fs::metadata(self).is_ok()
2229 /// Returns whether the path is pointing at a regular file.
2231 /// This function will traverse symbolic links to query information about the
2232 /// destination file. In case of broken symbolic links this will return `false`.
2237 /// use std::path::Path;
2238 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2239 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2241 #[stable(feature = "path_ext", since = "1.5.0")]
2242 pub fn is_file(&self) -> bool {
2243 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2246 /// Returns whether the path is pointing at a directory.
2248 /// This function will traverse symbolic links to query information about the
2249 /// destination file. In case of broken symbolic links this will return `false`.
2254 /// use std::path::Path;
2255 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2256 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2258 #[stable(feature = "path_ext", since = "1.5.0")]
2259 pub fn is_dir(&self) -> bool {
2260 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2263 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2266 /// [`Box`]: ../../std/boxed/struct.Box.html
2267 /// [`PathBuf`]: struct.PathBuf.html
2268 #[unstable(feature = "into_boxed_path", issue = "40380")]
2269 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2270 let inner: Box<OsStr> = unsafe { mem::transmute(self) };
2271 PathBuf { inner: OsString::from(inner) }
2275 #[stable(feature = "rust1", since = "1.0.0")]
2276 impl AsRef<OsStr> for Path {
2277 fn as_ref(&self) -> &OsStr {
2282 #[stable(feature = "rust1", since = "1.0.0")]
2283 impl fmt::Debug for Path {
2284 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2285 fmt::Debug::fmt(&self.inner, formatter)
2289 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2291 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2292 /// [`Display`] trait in a way that mitigates that. It is created by the
2293 /// [`display`][`Path::display`] method on [`Path`].
2298 /// use std::path::Path;
2300 /// let path = Path::new("/tmp/foo.rs");
2302 /// println!("{}", path.display());
2305 /// [`Display`]: ../../std/fmt/trait.Display.html
2306 /// [`format!`]: ../../std/macro.format.html
2307 /// [`Path`]: struct.Path.html
2308 /// [`Path::display`]: struct.Path.html#method.display
2309 #[stable(feature = "rust1", since = "1.0.0")]
2310 pub struct Display<'a> {
2314 #[stable(feature = "rust1", since = "1.0.0")]
2315 impl<'a> fmt::Debug for Display<'a> {
2316 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2317 fmt::Debug::fmt(&self.path, f)
2321 #[stable(feature = "rust1", since = "1.0.0")]
2322 impl<'a> fmt::Display for Display<'a> {
2323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2324 self.path.inner.display(f)
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 impl cmp::PartialEq for Path {
2330 fn eq(&self, other: &Path) -> bool {
2331 self.components().eq(other.components())
2335 #[stable(feature = "rust1", since = "1.0.0")]
2336 impl Hash for Path {
2337 fn hash<H: Hasher>(&self, h: &mut H) {
2338 for component in self.components() {
2344 #[stable(feature = "rust1", since = "1.0.0")]
2345 impl cmp::Eq for Path {}
2347 #[stable(feature = "rust1", since = "1.0.0")]
2348 impl cmp::PartialOrd for Path {
2349 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2350 self.components().partial_cmp(other.components())
2354 #[stable(feature = "rust1", since = "1.0.0")]
2355 impl cmp::Ord for Path {
2356 fn cmp(&self, other: &Path) -> cmp::Ordering {
2357 self.components().cmp(other.components())
2361 #[stable(feature = "rust1", since = "1.0.0")]
2362 impl AsRef<Path> for Path {
2363 fn as_ref(&self) -> &Path {
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 impl AsRef<Path> for OsStr {
2370 fn as_ref(&self) -> &Path {
2375 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2376 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2377 fn as_ref(&self) -> &Path {
2382 #[stable(feature = "rust1", since = "1.0.0")]
2383 impl AsRef<Path> for OsString {
2384 fn as_ref(&self) -> &Path {
2389 #[stable(feature = "rust1", since = "1.0.0")]
2390 impl AsRef<Path> for str {
2391 fn as_ref(&self) -> &Path {
2396 #[stable(feature = "rust1", since = "1.0.0")]
2397 impl AsRef<Path> for String {
2398 fn as_ref(&self) -> &Path {
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 impl AsRef<Path> for PathBuf {
2405 fn as_ref(&self) -> &Path {
2410 #[stable(feature = "path_into_iter", since = "1.6.0")]
2411 impl<'a> IntoIterator for &'a PathBuf {
2412 type Item = &'a OsStr;
2413 type IntoIter = Iter<'a>;
2414 fn into_iter(self) -> Iter<'a> { self.iter() }
2417 #[stable(feature = "path_into_iter", since = "1.6.0")]
2418 impl<'a> IntoIterator for &'a Path {
2419 type Item = &'a OsStr;
2420 type IntoIter = Iter<'a>;
2421 fn into_iter(self) -> Iter<'a> { self.iter() }
2424 macro_rules! impl_cmp {
2425 ($lhs:ty, $rhs: ty) => {
2426 #[stable(feature = "partialeq_path", since = "1.6.0")]
2427 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2429 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2432 #[stable(feature = "partialeq_path", since = "1.6.0")]
2433 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2435 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2438 #[stable(feature = "cmp_path", since = "1.8.0")]
2439 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2441 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2442 <Path as PartialOrd>::partial_cmp(self, other)
2446 #[stable(feature = "cmp_path", since = "1.8.0")]
2447 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2449 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2450 <Path as PartialOrd>::partial_cmp(self, other)
2456 impl_cmp!(PathBuf, Path);
2457 impl_cmp!(PathBuf, &'a Path);
2458 impl_cmp!(Cow<'a, Path>, Path);
2459 impl_cmp!(Cow<'a, Path>, &'b Path);
2460 impl_cmp!(Cow<'a, Path>, PathBuf);
2462 macro_rules! impl_cmp_os_str {
2463 ($lhs:ty, $rhs: ty) => {
2464 #[stable(feature = "cmp_path", since = "1.8.0")]
2465 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2467 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2470 #[stable(feature = "cmp_path", since = "1.8.0")]
2471 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2473 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2476 #[stable(feature = "cmp_path", since = "1.8.0")]
2477 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2479 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2480 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2484 #[stable(feature = "cmp_path", since = "1.8.0")]
2485 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2487 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2488 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2494 impl_cmp_os_str!(PathBuf, OsStr);
2495 impl_cmp_os_str!(PathBuf, &'a OsStr);
2496 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2497 impl_cmp_os_str!(PathBuf, OsString);
2498 impl_cmp_os_str!(Path, OsStr);
2499 impl_cmp_os_str!(Path, &'a OsStr);
2500 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2501 impl_cmp_os_str!(Path, OsString);
2502 impl_cmp_os_str!(&'a Path, OsStr);
2503 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2504 impl_cmp_os_str!(&'a Path, OsString);
2505 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2506 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2507 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2509 #[stable(since = "1.7.0", feature = "strip_prefix")]
2510 impl fmt::Display for StripPrefixError {
2511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2512 self.description().fmt(f)
2516 #[stable(since = "1.7.0", feature = "strip_prefix")]
2517 impl Error for StripPrefixError {
2518 fn description(&self) -> &str { "prefix not found" }
2526 ($path:expr, iter: $iter:expr) => (
2528 let path = Path::new($path);
2530 // Forward iteration
2531 let comps = path.iter()
2532 .map(|p| p.to_string_lossy().into_owned())
2533 .collect::<Vec<String>>();
2534 let exp: &[&str] = &$iter;
2535 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2536 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2539 // Reverse iteration
2540 let comps = Path::new($path).iter().rev()
2541 .map(|p| p.to_string_lossy().into_owned())
2542 .collect::<Vec<String>>();
2543 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2544 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2549 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2551 let path = Path::new($path);
2553 let act_root = path.has_root();
2554 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2555 $has_root, act_root);
2557 let act_abs = path.is_absolute();
2558 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2559 $is_absolute, act_abs);
2563 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2565 let path = Path::new($path);
2567 let parent = path.parent().map(|p| p.to_str().unwrap());
2568 let exp_parent: Option<&str> = $parent;
2569 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2570 exp_parent, parent);
2572 let file = path.file_name().map(|p| p.to_str().unwrap());
2573 let exp_file: Option<&str> = $file;
2574 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2579 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2581 let path = Path::new($path);
2583 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2584 let exp_stem: Option<&str> = $file_stem;
2585 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2588 let ext = path.extension().map(|p| p.to_str().unwrap());
2589 let exp_ext: Option<&str> = $extension;
2590 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2595 ($path:expr, iter: $iter:expr,
2596 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2597 parent: $parent:expr, file_name: $file:expr,
2598 file_stem: $file_stem:expr, extension: $extension:expr) => (
2600 t!($path, iter: $iter);
2601 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2602 t!($path, parent: $parent, file_name: $file);
2603 t!($path, file_stem: $file_stem, extension: $extension);
2612 let static_path = Path::new("/home/foo");
2613 let static_cow_path: Cow<'static, Path> = static_path.into();
2614 let pathbuf = PathBuf::from("/home/foo");
2617 let path: &Path = &pathbuf;
2618 let borrowed_cow_path: Cow<Path> = path.into();
2620 assert_eq!(static_cow_path, borrowed_cow_path);
2623 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2625 assert_eq!(static_cow_path, owned_cow_path);
2630 pub fn test_decompositions_unix() {
2646 file_name: Some("foo"),
2647 file_stem: Some("foo"),
2666 file_name: Some("foo"),
2667 file_stem: Some("foo"),
2676 file_name: Some("foo"),
2677 file_stem: Some("foo"),
2686 file_name: Some("foo"),
2687 file_stem: Some("foo"),
2692 iter: ["foo", "bar"],
2695 parent: Some("foo"),
2696 file_name: Some("bar"),
2697 file_stem: Some("bar"),
2702 iter: ["/", "foo", "bar"],
2705 parent: Some("/foo"),
2706 file_name: Some("bar"),
2707 file_stem: Some("bar"),
2716 file_name: Some("foo"),
2717 file_stem: Some("foo"),
2722 iter: ["/", "foo", "bar"],
2725 parent: Some("///foo"),
2726 file_name: Some("bar"),
2727 file_stem: Some("bar"),
2766 file_name: Some("foo"),
2767 file_stem: Some("foo"),
2772 iter: ["foo", ".."],
2775 parent: Some("foo"),
2786 file_name: Some("foo"),
2787 file_stem: Some("foo"),
2792 iter: ["foo", "bar"],
2795 parent: Some("foo"),
2796 file_name: Some("bar"),
2797 file_stem: Some("bar"),
2802 iter: ["foo", ".."],
2805 parent: Some("foo"),
2812 iter: ["foo", "..", "bar"],
2815 parent: Some("foo/.."),
2816 file_name: Some("bar"),
2817 file_stem: Some("bar"),
2826 file_name: Some("a"),
2827 file_stem: Some("a"),
2856 file_name: Some("b"),
2857 file_stem: Some("b"),
2866 file_name: Some("b"),
2867 file_stem: Some("b"),
2876 file_name: Some("b"),
2877 file_stem: Some("b"),
2882 iter: ["a", "b", "c"],
2885 parent: Some("a/b"),
2886 file_name: Some("c"),
2887 file_stem: Some("c"),
2896 file_name: Some(".foo"),
2897 file_stem: Some(".foo"),
2904 pub fn test_decompositions_windows() {
2920 file_name: Some("foo"),
2921 file_stem: Some("foo"),
2976 iter: ["\\", "foo"],
2980 file_name: Some("foo"),
2981 file_stem: Some("foo"),
2990 file_name: Some("foo"),
2991 file_stem: Some("foo"),
2996 iter: ["\\", "foo"],
3000 file_name: Some("foo"),
3001 file_stem: Some("foo"),
3006 iter: ["foo", "bar"],
3009 parent: Some("foo"),
3010 file_name: Some("bar"),
3011 file_stem: Some("bar"),
3016 iter: ["\\", "foo", "bar"],
3019 parent: Some("/foo"),
3020 file_name: Some("bar"),
3021 file_stem: Some("bar"),
3026 iter: ["\\", "foo"],
3030 file_name: Some("foo"),
3031 file_stem: Some("foo"),
3036 iter: ["\\", "foo", "bar"],
3039 parent: Some("///foo"),
3040 file_name: Some("bar"),
3041 file_stem: Some("bar"),
3080 file_name: Some("foo"),
3081 file_stem: Some("foo"),
3086 iter: ["foo", ".."],
3089 parent: Some("foo"),
3100 file_name: Some("foo"),
3101 file_stem: Some("foo"),
3106 iter: ["foo", "bar"],
3109 parent: Some("foo"),
3110 file_name: Some("bar"),
3111 file_stem: Some("bar"),
3116 iter: ["foo", ".."],
3119 parent: Some("foo"),
3126 iter: ["foo", "..", "bar"],
3129 parent: Some("foo/.."),
3130 file_name: Some("bar"),
3131 file_stem: Some("bar"),
3140 file_name: Some("a"),
3141 file_stem: Some("a"),
3170 file_name: Some("b"),
3171 file_stem: Some("b"),
3180 file_name: Some("b"),
3181 file_stem: Some("b"),
3190 file_name: Some("b"),
3191 file_stem: Some("b"),
3196 iter: ["a", "b", "c"],
3199 parent: Some("a/b"),
3200 file_name: Some("c"),
3201 file_stem: Some("c"),
3205 iter: ["a", "b", "c"],
3208 parent: Some("a\\b"),
3209 file_name: Some("c"),
3210 file_stem: Some("c"),
3219 file_name: Some("a"),
3220 file_stem: Some("a"),
3225 iter: ["c:", "\\", "foo.txt"],
3228 parent: Some("c:\\"),
3229 file_name: Some("foo.txt"),
3230 file_stem: Some("foo"),
3231 extension: Some("txt")
3234 t!("\\\\server\\share\\foo.txt",
3235 iter: ["\\\\server\\share", "\\", "foo.txt"],
3238 parent: Some("\\\\server\\share\\"),
3239 file_name: Some("foo.txt"),
3240 file_stem: Some("foo"),
3241 extension: Some("txt")
3244 t!("\\\\server\\share",
3245 iter: ["\\\\server\\share", "\\"],
3255 iter: ["\\", "server"],
3259 file_name: Some("server"),
3260 file_stem: Some("server"),
3264 t!("\\\\?\\bar\\foo.txt",
3265 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3268 parent: Some("\\\\?\\bar\\"),
3269 file_name: Some("foo.txt"),
3270 file_stem: Some("foo"),
3271 extension: Some("txt")
3275 iter: ["\\\\?\\bar"],
3294 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3295 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3298 parent: Some("\\\\?\\UNC\\server\\share\\"),
3299 file_name: Some("foo.txt"),
3300 file_stem: Some("foo"),
3301 extension: Some("txt")
3304 t!("\\\\?\\UNC\\server",
3305 iter: ["\\\\?\\UNC\\server"],
3315 iter: ["\\\\?\\UNC\\"],
3324 t!("\\\\?\\C:\\foo.txt",
3325 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3328 parent: Some("\\\\?\\C:\\"),
3329 file_name: Some("foo.txt"),
3330 file_stem: Some("foo"),
3331 extension: Some("txt")
3336 iter: ["\\\\?\\C:", "\\"],
3347 iter: ["\\\\?\\C:"],
3357 t!("\\\\?\\foo/bar",
3358 iter: ["\\\\?\\foo/bar"],
3369 iter: ["\\\\?\\C:/foo"],
3379 t!("\\\\.\\foo\\bar",
3380 iter: ["\\\\.\\foo", "\\", "bar"],
3383 parent: Some("\\\\.\\foo\\"),
3384 file_name: Some("bar"),
3385 file_stem: Some("bar"),
3391 iter: ["\\\\.\\foo", "\\"],
3401 t!("\\\\.\\foo/bar",
3402 iter: ["\\\\.\\foo/bar", "\\"],
3412 t!("\\\\.\\foo\\bar/baz",
3413 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3416 parent: Some("\\\\.\\foo\\bar"),
3417 file_name: Some("baz"),
3418 file_stem: Some("baz"),
3424 iter: ["\\\\.\\", "\\"],
3434 iter: ["\\\\?\\a", "\\", "b"],
3437 parent: Some("\\\\?\\a\\"),
3438 file_name: Some("b"),
3439 file_stem: Some("b"),
3445 pub fn test_stem_ext() {
3447 file_stem: Some("foo"),
3452 file_stem: Some("foo"),
3457 file_stem: Some(".foo"),
3462 file_stem: Some("foo"),
3463 extension: Some("txt")
3467 file_stem: Some("foo.bar"),
3468 extension: Some("txt")
3472 file_stem: Some("foo.bar"),
3493 pub fn test_push() {
3495 ($path:expr, $push:expr, $expected:expr) => ( {
3496 let mut actual = PathBuf::from($path);
3498 assert!(actual.to_str() == Some($expected),
3499 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3500 $push, $path, $expected, actual.to_str().unwrap());
3505 tp!("", "foo", "foo");
3506 tp!("foo", "bar", "foo/bar");
3507 tp!("foo/", "bar", "foo/bar");
3508 tp!("foo//", "bar", "foo//bar");
3509 tp!("foo/.", "bar", "foo/./bar");
3510 tp!("foo./.", "bar", "foo././bar");
3511 tp!("foo", "", "foo/");
3512 tp!("foo", ".", "foo/.");
3513 tp!("foo", "..", "foo/..");
3514 tp!("foo", "/", "/");
3515 tp!("/foo/bar", "/", "/");
3516 tp!("/foo/bar", "/baz", "/baz");
3517 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3519 tp!("", "foo", "foo");
3520 tp!("foo", "bar", r"foo\bar");
3521 tp!("foo/", "bar", r"foo/bar");
3522 tp!(r"foo\", "bar", r"foo\bar");
3523 tp!("foo//", "bar", r"foo//bar");
3524 tp!(r"foo\\", "bar", r"foo\\bar");
3525 tp!("foo/.", "bar", r"foo/.\bar");
3526 tp!("foo./.", "bar", r"foo./.\bar");
3527 tp!(r"foo\.", "bar", r"foo\.\bar");
3528 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3529 tp!("foo", "", "foo\\");
3530 tp!("foo", ".", r"foo\.");
3531 tp!("foo", "..", r"foo\..");
3532 tp!("foo", "/", "/");
3533 tp!("foo", r"\", r"\");
3534 tp!("/foo/bar", "/", "/");
3535 tp!(r"\foo\bar", r"\", r"\");
3536 tp!("/foo/bar", "/baz", "/baz");
3537 tp!("/foo/bar", r"\baz", r"\baz");
3538 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3539 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3541 tp!("c:\\", "windows", "c:\\windows");
3542 tp!("c:", "windows", "c:windows");
3544 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3545 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3546 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3547 tp!("a\\b", "\\c\\d", "\\c\\d");
3548 tp!("a\\b", ".", "a\\b\\.");
3549 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3550 tp!("a\\b", "C:a.txt", "C:a.txt");
3551 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3552 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3553 tp!("C:\\a\\b\\c", "C:d", "C:d");
3554 tp!("C:a\\b\\c", "C:d", "C:d");
3555 tp!("C:", r"a\b\c", r"C:a\b\c");
3556 tp!("C:", r"..\a", r"C:..\a");
3557 tp!("\\\\server\\share\\foo",
3559 "\\\\server\\share\\foo\\bar");
3560 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3561 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3562 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3563 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3564 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3565 tp!("\\\\?\\UNC\\server\\share\\foo",
3567 "\\\\?\\UNC\\server\\share\\foo\\bar");
3568 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3569 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3571 // Note: modified from old path API
3572 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3575 "\\\\?\\UNC\\server\\share",
3576 "\\\\?\\UNC\\server\\share");
3577 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3578 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3579 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3580 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3582 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3589 ($path:expr, $expected:expr, $output:expr) => ( {
3590 let mut actual = PathBuf::from($path);
3591 let output = actual.pop();
3592 assert!(actual.to_str() == Some($expected) && output == $output,
3593 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3594 $path, $expected, $output,
3595 actual.to_str().unwrap(), output);
3600 tp!("/", "/", false);
3601 tp!("foo", "", true);
3603 tp!("/foo", "/", true);
3604 tp!("/foo/bar", "/foo", true);
3605 tp!("foo/bar", "foo", true);
3606 tp!("foo/.", "", true);
3607 tp!("foo//bar", "foo", true);
3610 tp!("a\\b\\c", "a\\b", true);
3611 tp!("\\a", "\\", true);
3612 tp!("\\", "\\", false);
3614 tp!("C:\\a\\b", "C:\\a", true);
3615 tp!("C:\\a", "C:\\", true);
3616 tp!("C:\\", "C:\\", false);
3617 tp!("C:a\\b", "C:a", true);
3618 tp!("C:a", "C:", true);
3619 tp!("C:", "C:", false);
3620 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3621 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3622 tp!("\\\\server\\share", "\\\\server\\share", false);
3623 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3624 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3625 tp!("\\\\?\\a", "\\\\?\\a", false);
3626 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3627 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3628 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3629 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3630 "\\\\?\\UNC\\server\\share\\a",
3632 tp!("\\\\?\\UNC\\server\\share\\a",
3633 "\\\\?\\UNC\\server\\share\\",
3635 tp!("\\\\?\\UNC\\server\\share",
3636 "\\\\?\\UNC\\server\\share",
3638 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3639 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3640 tp!("\\\\.\\a", "\\\\.\\a", false);
3642 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3647 pub fn test_set_file_name() {
3649 ($path:expr, $file:expr, $expected:expr) => ( {
3650 let mut p = PathBuf::from($path);
3651 p.set_file_name($file);
3652 assert!(p.to_str() == Some($expected),
3653 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3654 $path, $file, $expected,
3655 p.to_str().unwrap());
3659 tfn!("foo", "foo", "foo");
3660 tfn!("foo", "bar", "bar");
3661 tfn!("foo", "", "");
3662 tfn!("", "foo", "foo");
3664 tfn!(".", "foo", "./foo");
3665 tfn!("foo/", "bar", "bar");
3666 tfn!("foo/.", "bar", "bar");
3667 tfn!("..", "foo", "../foo");
3668 tfn!("foo/..", "bar", "foo/../bar");
3669 tfn!("/", "foo", "/foo");
3671 tfn!(".", "foo", r".\foo");
3672 tfn!(r"foo\", "bar", r"bar");
3673 tfn!(r"foo\.", "bar", r"bar");
3674 tfn!("..", "foo", r"..\foo");
3675 tfn!(r"foo\..", "bar", r"foo\..\bar");
3676 tfn!(r"\", "foo", r"\foo");
3681 pub fn test_set_extension() {
3683 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3684 let mut p = PathBuf::from($path);
3685 let output = p.set_extension($ext);
3686 assert!(p.to_str() == Some($expected) && output == $output,
3687 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3688 $path, $ext, $expected, $output,
3689 p.to_str().unwrap(), output);
3693 tfe!("foo", "txt", "foo.txt", true);
3694 tfe!("foo.bar", "txt", "foo.txt", true);
3695 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3696 tfe!(".test", "txt", ".test.txt", true);
3697 tfe!("foo.txt", "", "foo", true);
3698 tfe!("foo", "", "foo", true);
3699 tfe!("", "foo", "", false);
3700 tfe!(".", "foo", ".", false);
3701 tfe!("foo/", "bar", "foo.bar", true);
3702 tfe!("foo/.", "bar", "foo.bar", true);
3703 tfe!("..", "foo", "..", false);
3704 tfe!("foo/..", "bar", "foo/..", false);
3705 tfe!("/", "foo", "/", false);
3709 fn test_eq_recievers() {
3712 let borrowed: &Path = Path::new("foo/bar");
3713 let mut owned: PathBuf = PathBuf::new();
3716 let borrowed_cow: Cow<Path> = borrowed.into();
3717 let owned_cow: Cow<Path> = owned.clone().into();
3720 ($($current:expr),+) => {
3722 assert_eq!($current, borrowed);
3723 assert_eq!($current, owned);
3724 assert_eq!($current, borrowed_cow);
3725 assert_eq!($current, owned_cow);
3730 t!(borrowed, owned, borrowed_cow, owned_cow);
3734 pub fn test_compare() {
3735 use hash::{Hash, Hasher};
3736 use collections::hash_map::DefaultHasher;
3738 fn hash<T: Hash>(t: T) -> u64 {
3739 let mut s = DefaultHasher::new();
3745 ($path1:expr, $path2:expr, eq: $eq:expr,
3746 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3747 relative_from: $relative_from:expr) => ({
3748 let path1 = Path::new($path1);
3749 let path2 = Path::new($path2);
3751 let eq = path1 == path2;
3752 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3753 $path1, $path2, $eq, eq);
3754 assert!($eq == (hash(path1) == hash(path2)),
3755 "{:?} == {:?}, expected {:?}, got {} and {}",
3756 $path1, $path2, $eq, hash(path1), hash(path2));
3758 let starts_with = path1.starts_with(path2);
3759 assert!(starts_with == $starts_with,
3760 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3761 $starts_with, starts_with);
3763 let ends_with = path1.ends_with(path2);
3764 assert!(ends_with == $ends_with,
3765 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3766 $ends_with, ends_with);
3768 let relative_from = path1.strip_prefix(path2)
3769 .map(|p| p.to_str().unwrap())
3771 let exp: Option<&str> = $relative_from;
3772 assert!(relative_from == exp,
3773 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3774 $path1, $path2, exp, relative_from);
3782 relative_from: Some("")
3789 relative_from: Some("foo")
3803 relative_from: Some("")
3810 relative_from: Some("")
3813 tc!("foo/bar", "foo",
3817 relative_from: Some("bar")
3820 tc!("foo/bar/baz", "foo/bar",
3824 relative_from: Some("baz")
3827 tc!("foo/bar", "foo/bar/baz",
3834 tc!("./foo/bar/", ".",
3838 relative_from: Some("foo/bar")
3842 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3843 r"c:\src\rust\cargo-test\test",
3847 relative_from: Some("Cargo.toml")
3850 tc!(r"c:\foo", r"C:\foo",
3854 relative_from: Some("")
3860 fn test_components_debug() {
3861 let path = Path::new("/tmp");
3863 let mut components = path.components();
3865 let expected = "Components([RootDir, Normal(\"tmp\")])";
3866 let actual = format!("{:?}", components);
3867 assert_eq!(expected, actual);
3869 let _ = components.next().unwrap();
3870 let expected = "Components([Normal(\"tmp\")])";
3871 let actual = format!("{:?}", components);
3872 assert_eq!(expected, actual);
3874 let _ = components.next().unwrap();
3875 let expected = "Components([])";
3876 let actual = format!("{:?}", components);
3877 assert_eq!(expected, actual);
3882 fn test_iter_debug() {
3883 let path = Path::new("/tmp");
3885 let mut iter = path.iter();
3887 let expected = "Iter([\"/\", \"tmp\"])";
3888 let actual = format!("{:?}", iter);
3889 assert_eq!(expected, actual);
3891 let _ = iter.next().unwrap();
3892 let expected = "Iter([\"tmp\"])";
3893 let actual = format!("{:?}", iter);
3894 assert_eq!(expected, actual);
3896 let _ = iter.next().unwrap();
3897 let expected = "Iter([])";
3898 let actual = format!("{:?}", iter);
3899 assert_eq!(expected, actual);
3904 let orig: &str = "some/sort/of/path";
3905 let path = Path::new(orig);
3906 let boxed: Box<Path> = Box::from(path);
3907 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
3908 assert_eq!(path, &*boxed);
3909 assert_eq!(&*boxed, &*path_buf);
3910 assert_eq!(&*path_buf, path);
3914 fn test_clone_into() {
3915 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
3916 let path = Path::new("short");
3917 path.clone_into(&mut path_buf);
3918 assert_eq!(path, path_buf);
3919 assert!(path_buf.into_os_string().capacity() >= 15);