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(b'C'), 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(b'C'), 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(b'C').is_verbatim());
239 /// assert!(!DeviceNS(OsStr::new("BrainInterface")).is_verbatim());
240 /// assert!(!UNC(OsStr::new("server"), OsStr::new("share")).is_verbatim());
241 /// assert!(!Disk(b'C').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('/')); // '/' works for both Unix and Windows
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 // Detect scheme on Redox
327 fn has_redox_scheme(s: &[u8]) -> bool {
328 cfg!(target_os = "redox") && s.split(|b| *b == b'/').next().unwrap_or(b"").contains(&b':')
331 ////////////////////////////////////////////////////////////////////////////////
332 // Cross-platform, iterator-independent parsing
333 ////////////////////////////////////////////////////////////////////////////////
335 /// Says whether the first byte after the prefix is a separator.
336 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
337 let path = if let Some(p) = prefix {
342 !path.is_empty() && is_sep_byte(path[0])
345 // basic workhorse for splitting stem and extension
346 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
348 if os_str_as_u8_slice(file) == b".." {
349 return (Some(file), None);
352 // The unsafety here stems from converting between &OsStr and &[u8]
353 // and back. This is safe to do because (1) we only look at ASCII
354 // contents of the encoding and (2) new &OsStr values are produced
355 // only from ASCII-bounded slices of existing &OsStr values.
357 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
358 let after = iter.next();
359 let before = iter.next();
360 if before == Some(b"") {
363 (before.map(|s| u8_slice_as_os_str(s)),
364 after.map(|s| u8_slice_as_os_str(s)))
369 ////////////////////////////////////////////////////////////////////////////////
370 // The core iterators
371 ////////////////////////////////////////////////////////////////////////////////
373 /// Component parsing works by a double-ended state machine; the cursors at the
374 /// front and back of the path each keep track of what parts of the path have
375 /// been consumed so far.
377 /// Going front to back, a path is made up of a prefix, a starting
378 /// directory component, and a body (of normal components)
379 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
382 StartDir = 1, // / or . or nothing
383 Body = 2, // foo/bar/baz
387 /// A structure wrapping a Windows path prefix as well as its unparsed string
390 /// In addition to the parsed [`Prefix`] information returned by [`kind`],
391 /// `PrefixComponent` also holds the raw and unparsed [`OsStr`] slice,
392 /// returned by [`as_os_str`].
394 /// Instances of this `struct` can be obtained by matching against the
395 /// [`Prefix` variant] on [`Component`].
397 /// Does not occur on Unix.
402 /// # if cfg!(windows) {
403 /// use std::path::{Component, Path, Prefix};
404 /// use std::ffi::OsStr;
406 /// let path = Path::new(r"c:\you\later\");
407 /// match path.components().next().unwrap() {
408 /// Component::Prefix(prefix_component) => {
409 /// assert_eq!(Prefix::Disk(b'C'), prefix_component.kind());
410 /// assert_eq!(OsStr::new("c:"), prefix_component.as_os_str());
412 /// _ => unreachable!(),
417 /// [`as_os_str`]: #method.as_os_str
418 /// [`Component`]: enum.Component.html
419 /// [`kind`]: #method.kind
420 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
421 /// [`Prefix` variant]: enum.Component.html#variant.Prefix
422 /// [`Prefix`]: enum.Prefix.html
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[derive(Copy, Clone, Eq, Debug)]
425 pub struct PrefixComponent<'a> {
426 /// The prefix as an unparsed `OsStr` slice.
429 /// The parsed prefix data.
433 impl<'a> PrefixComponent<'a> {
434 /// Returns the parsed prefix data.
436 /// See [`Prefix`]'s documentation for more information on the different
437 /// kinds of prefixes.
439 /// [`Prefix`]: enum.Prefix.html
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn kind(&self) -> Prefix<'a> {
445 /// Returns the raw [`OsStr`] slice for this prefix.
447 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn as_os_str(&self) -> &'a OsStr {
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
456 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
457 cmp::PartialEq::eq(&self.parsed, &other.parsed)
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
463 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
464 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
468 #[stable(feature = "rust1", since = "1.0.0")]
469 impl<'a> cmp::Ord for PrefixComponent<'a> {
470 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
471 cmp::Ord::cmp(&self.parsed, &other.parsed)
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl<'a> Hash for PrefixComponent<'a> {
477 fn hash<H: Hasher>(&self, h: &mut H) {
482 /// A single component of a path.
484 /// A `Component` roughly corresponds to a substring between path separators
487 /// This `enum` is created by iterating over [`Components`], which in turn is
488 /// created by the [`components`][`Path::components`] method on [`Path`].
493 /// use std::path::{Component, Path};
495 /// let path = Path::new("/tmp/foo/bar.txt");
496 /// let components = path.components().collect::<Vec<_>>();
497 /// assert_eq!(&components, &[
498 /// Component::RootDir,
499 /// Component::Normal("tmp".as_ref()),
500 /// Component::Normal("foo".as_ref()),
501 /// Component::Normal("bar.txt".as_ref()),
505 /// [`Components`]: struct.Components.html
506 /// [`Path`]: struct.Path.html
507 /// [`Path::components`]: struct.Path.html#method.components
508 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub enum Component<'a> {
511 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
513 /// There is a large variety of prefix types, see [`Prefix`]'s documentation
516 /// Does not occur on Unix.
518 /// [`Prefix`]: enum.Prefix.html
519 #[stable(feature = "rust1", since = "1.0.0")]
521 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
524 /// The root directory component, appears after any prefix and before anything else.
526 /// It represents a separator that designates that a path starts from root.
527 #[stable(feature = "rust1", since = "1.0.0")]
530 /// A reference to the current directory, i.e. `.`.
531 #[stable(feature = "rust1", since = "1.0.0")]
534 /// A reference to the parent directory, i.e. `..`.
535 #[stable(feature = "rust1", since = "1.0.0")]
538 /// A normal component, e.g. `a` and `b` in `a/b`.
540 /// This variant is the most common one, it represents references to files
542 #[stable(feature = "rust1", since = "1.0.0")]
543 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
546 impl<'a> Component<'a> {
547 /// Extracts the underlying [`OsStr`] slice.
552 /// use std::path::Path;
554 /// let path = Path::new("./tmp/foo/bar.txt");
555 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
556 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
559 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
560 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn as_os_str(self) -> &'a OsStr {
563 Component::Prefix(p) => p.as_os_str(),
564 Component::RootDir => OsStr::new(MAIN_SEP_STR),
565 Component::CurDir => OsStr::new("."),
566 Component::ParentDir => OsStr::new(".."),
567 Component::Normal(path) => path,
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<'a> AsRef<OsStr> for Component<'a> {
574 fn as_ref(&self) -> &OsStr {
579 /// An iterator over the [`Component`]s of a [`Path`].
581 /// This `struct` is created by the [`components`] method on [`Path`].
582 /// See its documentation for more.
587 /// use std::path::Path;
589 /// let path = Path::new("/tmp/foo/bar.txt");
591 /// for component in path.components() {
592 /// println!("{:?}", component);
596 /// [`Component`]: enum.Component.html
597 /// [`components`]: struct.Path.html#method.components
598 /// [`Path`]: struct.Path.html
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub struct Components<'a> {
602 // The path left to parse components from
605 // The prefix as it was originally parsed, if any
606 prefix: Option<Prefix<'a>>,
608 // true if path *physically* has a root separator; for most Windows
609 // prefixes, it may have a "logical" rootseparator for the purposes of
610 // normalization, e.g. \\server\share == \\server\share\.
611 has_physical_root: bool,
613 // The iterator is double-ended, and these two states keep track of what has
614 // been produced from either end
619 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
621 /// This `struct` is created by the [`iter`] method on [`Path`].
622 /// See its documentation for more.
624 /// [`Component`]: enum.Component.html
625 /// [`iter`]: struct.Path.html#method.iter
626 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
627 /// [`Path`]: struct.Path.html
629 #[stable(feature = "rust1", since = "1.0.0")]
630 pub struct Iter<'a> {
631 inner: Components<'a>,
634 #[stable(feature = "path_components_debug", since = "1.13.0")]
635 impl<'a> fmt::Debug for Components<'a> {
636 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637 struct DebugHelper<'a>(&'a Path);
639 impl<'a> fmt::Debug for DebugHelper<'a> {
640 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
642 .entries(self.0.components())
647 f.debug_tuple("Components")
648 .field(&DebugHelper(self.as_path()))
653 impl<'a> Components<'a> {
654 // how long is the prefix, if any?
656 fn prefix_len(&self) -> usize {
657 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
661 fn prefix_verbatim(&self) -> bool {
662 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
665 /// how much of the prefix is left from the point of view of iteration?
667 fn prefix_remaining(&self) -> usize {
668 if self.front == State::Prefix {
675 // Given the iteration so far, how much of the pre-State::Body path is left?
677 fn len_before_body(&self) -> usize {
678 let root = if self.front <= State::StartDir && self.has_physical_root {
683 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
688 self.prefix_remaining() + root + cur_dir
691 // is the iteration complete?
693 fn finished(&self) -> bool {
694 self.front == State::Done || self.back == State::Done || self.front > self.back
698 fn is_sep_byte(&self, b: u8) -> bool {
699 if self.prefix_verbatim() {
706 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
711 /// use std::path::Path;
713 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
714 /// components.next();
715 /// components.next();
717 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn as_path(&self) -> &'a Path {
721 let mut comps = self.clone();
722 if comps.front == State::Body {
725 if comps.back == State::Body {
728 unsafe { Path::from_u8_slice(comps.path) }
731 /// Is the *original* path rooted?
732 fn has_root(&self) -> bool {
733 if self.has_physical_root {
736 if let Some(p) = self.prefix {
737 if p.has_implicit_root() {
744 /// Should the normalized path include a leading . ?
745 fn include_cur_dir(&self) -> bool {
749 let mut iter = self.path[self.prefix_len()..].iter();
750 match (iter.next(), iter.next()) {
751 (Some(&b'.'), None) => true,
752 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
757 // parse a given byte sequence into the corresponding path component
758 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
760 b"." if self.prefix_verbatim() => Some(Component::CurDir),
761 b"." => None, // . components are normalized away, except at
762 // the beginning of a path, which is treated
763 // separately via `include_cur_dir`
764 b".." => Some(Component::ParentDir),
766 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
770 // parse a component from the left, saying how many bytes to consume to
771 // remove the component
772 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
773 debug_assert!(self.front == State::Body);
774 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
775 None => (0, self.path),
776 Some(i) => (1, &self.path[..i]),
778 (comp.len() + extra, self.parse_single_component(comp))
781 // parse a component from the right, saying how many bytes to consume to
782 // remove the component
783 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
784 debug_assert!(self.back == State::Body);
785 let start = self.len_before_body();
786 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
787 None => (0, &self.path[start..]),
788 Some(i) => (1, &self.path[start + i + 1..]),
790 (comp.len() + extra, self.parse_single_component(comp))
793 // trim away repeated separators (i.e. empty components) on the left
794 fn trim_left(&mut self) {
795 while !self.path.is_empty() {
796 let (size, comp) = self.parse_next_component();
800 self.path = &self.path[size..];
805 // trim away repeated separators (i.e. empty components) on the right
806 fn trim_right(&mut self) {
807 while self.path.len() > self.len_before_body() {
808 let (size, comp) = self.parse_next_component_back();
812 self.path = &self.path[..self.path.len() - size];
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl<'a> AsRef<Path> for Components<'a> {
820 fn as_ref(&self) -> &Path {
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<'a> AsRef<OsStr> for Components<'a> {
827 fn as_ref(&self) -> &OsStr {
828 self.as_path().as_os_str()
832 #[stable(feature = "path_iter_debug", since = "1.13.0")]
833 impl<'a> fmt::Debug for Iter<'a> {
834 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
835 struct DebugHelper<'a>(&'a Path);
837 impl<'a> fmt::Debug for DebugHelper<'a> {
838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
840 .entries(self.0.iter())
845 f.debug_tuple("Iter")
846 .field(&DebugHelper(self.as_path()))
852 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
857 /// use std::path::Path;
859 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
863 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
865 #[stable(feature = "rust1", since = "1.0.0")]
866 pub fn as_path(&self) -> &'a Path {
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl<'a> AsRef<Path> for Iter<'a> {
873 fn as_ref(&self) -> &Path {
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<'a> AsRef<OsStr> for Iter<'a> {
880 fn as_ref(&self) -> &OsStr {
881 self.as_path().as_os_str()
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a> Iterator for Iter<'a> {
887 type Item = &'a OsStr;
889 fn next(&mut self) -> Option<&'a OsStr> {
890 self.inner.next().map(Component::as_os_str)
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<'a> DoubleEndedIterator for Iter<'a> {
896 fn next_back(&mut self) -> Option<&'a OsStr> {
897 self.inner.next_back().map(Component::as_os_str)
901 #[unstable(feature = "fused", issue = "35602")]
902 impl<'a> FusedIterator for Iter<'a> {}
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<'a> Iterator for Components<'a> {
906 type Item = Component<'a>;
908 fn next(&mut self) -> Option<Component<'a>> {
909 while !self.finished() {
911 State::Prefix if self.prefix_len() > 0 => {
912 self.front = State::StartDir;
913 debug_assert!(self.prefix_len() <= self.path.len());
914 let raw = &self.path[..self.prefix_len()];
915 self.path = &self.path[self.prefix_len()..];
916 return Some(Component::Prefix(PrefixComponent {
917 raw: unsafe { u8_slice_as_os_str(raw) },
918 parsed: self.prefix.unwrap(),
922 self.front = State::StartDir;
925 self.front = State::Body;
926 if self.has_physical_root {
927 debug_assert!(!self.path.is_empty());
928 self.path = &self.path[1..];
929 return Some(Component::RootDir);
930 } else if let Some(p) = self.prefix {
931 if p.has_implicit_root() && !p.is_verbatim() {
932 return Some(Component::RootDir);
934 } else if self.include_cur_dir() {
935 debug_assert!(!self.path.is_empty());
936 self.path = &self.path[1..];
937 return Some(Component::CurDir);
940 State::Body if !self.path.is_empty() => {
941 let (size, comp) = self.parse_next_component();
942 self.path = &self.path[size..];
948 self.front = State::Done;
950 State::Done => unreachable!(),
957 #[stable(feature = "rust1", since = "1.0.0")]
958 impl<'a> DoubleEndedIterator for Components<'a> {
959 fn next_back(&mut self) -> Option<Component<'a>> {
960 while !self.finished() {
962 State::Body if self.path.len() > self.len_before_body() => {
963 let (size, comp) = self.parse_next_component_back();
964 self.path = &self.path[..self.path.len() - size];
970 self.back = State::StartDir;
973 self.back = State::Prefix;
974 if self.has_physical_root {
975 self.path = &self.path[..self.path.len() - 1];
976 return Some(Component::RootDir);
977 } else if let Some(p) = self.prefix {
978 if p.has_implicit_root() && !p.is_verbatim() {
979 return Some(Component::RootDir);
981 } else if self.include_cur_dir() {
982 self.path = &self.path[..self.path.len() - 1];
983 return Some(Component::CurDir);
986 State::Prefix if self.prefix_len() > 0 => {
987 self.back = State::Done;
988 return Some(Component::Prefix(PrefixComponent {
989 raw: unsafe { u8_slice_as_os_str(self.path) },
990 parsed: self.prefix.unwrap(),
994 self.back = State::Done;
997 State::Done => unreachable!(),
1004 #[unstable(feature = "fused", issue = "35602")]
1005 impl<'a> FusedIterator for Components<'a> {}
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<'a> cmp::PartialEq for Components<'a> {
1009 fn eq(&self, other: &Components<'a>) -> bool {
1010 Iterator::eq(self.clone(), other.clone())
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<'a> cmp::Eq for Components<'a> {}
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl<'a> cmp::PartialOrd for Components<'a> {
1019 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1020 Iterator::partial_cmp(self.clone(), other.clone())
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<'a> cmp::Ord for Components<'a> {
1026 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
1027 Iterator::cmp(self.clone(), other.clone())
1031 ////////////////////////////////////////////////////////////////////////////////
1032 // Basic types and traits
1033 ////////////////////////////////////////////////////////////////////////////////
1035 /// An owned, mutable path (akin to [`String`]).
1037 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1038 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1039 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1041 /// [`String`]: ../string/struct.String.html
1042 /// [`Path`]: struct.Path.html
1043 /// [`push`]: struct.PathBuf.html#method.push
1044 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1045 /// [`Deref`]: ../ops/trait.Deref.html
1047 /// More details about the overall approach can be found in
1048 /// the [module documentation](index.html).
1052 /// You can use [`push`] to build up a `PathBuf` from
1056 /// use std::path::PathBuf;
1058 /// let mut path = PathBuf::new();
1060 /// path.push(r"C:\");
1061 /// path.push("windows");
1062 /// path.push("system32");
1064 /// path.set_extension("dll");
1067 /// However, [`push`] is best used for dynamic situations. This is a better way
1068 /// to do this when you know all of the components ahead of time:
1071 /// use std::path::PathBuf;
1073 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1076 /// We can still do better than this! Since these are all strings, we can use
1080 /// use std::path::PathBuf;
1082 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1085 /// Which method works best depends on what kind of situation you're in.
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub struct PathBuf {
1093 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1094 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1097 /// Allocates an empty `PathBuf`.
1102 /// use std::path::PathBuf;
1104 /// let path = PathBuf::new();
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub fn new() -> PathBuf {
1108 PathBuf { inner: OsString::new() }
1111 /// Coerces to a [`Path`] slice.
1113 /// [`Path`]: struct.Path.html
1118 /// use std::path::{Path, PathBuf};
1120 /// let p = PathBuf::from("/test");
1121 /// assert_eq!(Path::new("/test"), p.as_path());
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 pub fn as_path(&self) -> &Path {
1128 /// Extends `self` with `path`.
1130 /// If `path` is absolute, it replaces the current path.
1134 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1135 /// replaces everything except for the prefix (if any) of `self`.
1136 /// * if `path` has a prefix but no root, it replaces `self`.
1140 /// Pushing a relative path extends the existing path:
1143 /// use std::path::PathBuf;
1145 /// let mut path = PathBuf::from("/tmp");
1146 /// path.push("file.bk");
1147 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1150 /// Pushing an absolute path replaces the existing path:
1153 /// use std::path::PathBuf;
1155 /// let mut path = PathBuf::from("/tmp");
1156 /// path.push("/etc");
1157 /// assert_eq!(path, PathBuf::from("/etc"));
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1161 self._push(path.as_ref())
1164 fn _push(&mut self, path: &Path) {
1165 // in general, a separator is needed if the rightmost byte is not a separator
1166 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1168 // in the special case of `C:` on Windows, do *not* add a separator
1170 let comps = self.components();
1171 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1172 comps.prefix.unwrap().is_drive() {
1177 // absolute `path` replaces `self`
1178 if path.is_absolute() || path.prefix().is_some() {
1179 self.as_mut_vec().truncate(0);
1181 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1182 } else if path.has_root() {
1183 let prefix_len = self.components().prefix_remaining();
1184 self.as_mut_vec().truncate(prefix_len);
1186 // `path` is a pure relative path
1187 } else if need_sep {
1188 self.inner.push(MAIN_SEP_STR);
1191 self.inner.push(path);
1194 /// Truncates `self` to [`self.parent`].
1196 /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1197 /// Otherwise, returns `true`.
1199 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1200 /// [`self.parent`]: struct.PathBuf.html#method.parent
1201 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1206 /// use std::path::{Path, PathBuf};
1208 /// let mut p = PathBuf::from("/test/test.rs");
1211 /// assert_eq!(Path::new("/test"), p);
1213 /// assert_eq!(Path::new("/"), p);
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn pop(&mut self) -> bool {
1217 match self.parent().map(|p| p.as_u8_slice().len()) {
1219 self.as_mut_vec().truncate(len);
1226 /// Updates [`self.file_name`] to `file_name`.
1228 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1231 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1232 /// `file_name`. The new path will be a sibling of the original path.
1233 /// (That is, it will have the same parent.)
1235 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1236 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1237 /// [`pop`]: struct.PathBuf.html#method.pop
1242 /// use std::path::PathBuf;
1244 /// let mut buf = PathBuf::from("/");
1245 /// assert!(buf.file_name() == None);
1246 /// buf.set_file_name("bar");
1247 /// assert!(buf == PathBuf::from("/bar"));
1248 /// assert!(buf.file_name().is_some());
1249 /// buf.set_file_name("baz.txt");
1250 /// assert!(buf == PathBuf::from("/baz.txt"));
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1254 self._set_file_name(file_name.as_ref())
1257 fn _set_file_name(&mut self, file_name: &OsStr) {
1258 if self.file_name().is_some() {
1259 let popped = self.pop();
1260 debug_assert!(popped);
1262 self.push(file_name);
1265 /// Updates [`self.extension`] to `extension`.
1267 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1268 /// returns `true` and updates the extension otherwise.
1270 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1273 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1274 /// [`self.extension`]: struct.PathBuf.html#method.extension
1275 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1280 /// use std::path::{Path, PathBuf};
1282 /// let mut p = PathBuf::from("/feel/the");
1284 /// p.set_extension("force");
1285 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1287 /// p.set_extension("dark_side");
1288 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1292 self._set_extension(extension.as_ref())
1295 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1296 if self.file_name().is_none() {
1300 let mut stem = match self.file_stem() {
1301 Some(stem) => stem.to_os_string(),
1302 None => OsString::new(),
1305 if !os_str_as_u8_slice(extension).is_empty() {
1307 stem.push(extension);
1309 self.set_file_name(&stem);
1314 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1316 /// [`OsString`]: ../ffi/struct.OsString.html
1321 /// use std::path::PathBuf;
1323 /// let p = PathBuf::from("/the/head");
1324 /// let os_str = p.into_os_string();
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 pub fn into_os_string(self) -> OsString {
1331 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1333 /// [`Box`]: ../../std/boxed/struct.Box.html
1334 /// [`Path`]: struct.Path.html
1335 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1336 pub fn into_boxed_path(self) -> Box<Path> {
1337 unsafe { mem::transmute(self.inner.into_boxed_os_str()) }
1341 #[stable(feature = "box_from_path", since = "1.17.0")]
1342 impl<'a> From<&'a Path> for Box<Path> {
1343 fn from(path: &'a Path) -> Box<Path> {
1344 let boxed: Box<OsStr> = path.inner.into();
1345 unsafe { mem::transmute(boxed) }
1349 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1350 impl From<Box<Path>> for PathBuf {
1351 fn from(boxed: Box<Path>) -> PathBuf {
1352 boxed.into_path_buf()
1356 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1357 impl From<PathBuf> for Box<Path> {
1358 fn from(p: PathBuf) -> Box<Path> {
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1365 fn from(s: &'a T) -> PathBuf {
1366 PathBuf::from(s.as_ref().to_os_string())
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl From<OsString> for PathBuf {
1372 fn from(s: OsString) -> PathBuf {
1373 PathBuf { inner: s }
1377 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1378 impl From<PathBuf> for OsString {
1379 fn from(path_buf : PathBuf) -> OsString {
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl From<String> for PathBuf {
1386 fn from(s: String) -> PathBuf {
1387 PathBuf::from(OsString::from(s))
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1393 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1394 let mut buf = PathBuf::new();
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1402 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1404 self.push(p.as_ref())
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 impl fmt::Debug for PathBuf {
1411 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1412 fmt::Debug::fmt(&**self, formatter)
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl ops::Deref for PathBuf {
1420 fn deref(&self) -> &Path {
1421 Path::new(&self.inner)
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl Borrow<Path> for PathBuf {
1427 fn borrow(&self) -> &Path {
1432 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1433 impl Default for PathBuf {
1434 fn default() -> Self {
1439 #[stable(feature = "cow_from_path", since = "1.6.0")]
1440 impl<'a> From<&'a Path> for Cow<'a, Path> {
1442 fn from(s: &'a Path) -> Cow<'a, Path> {
1447 #[stable(feature = "cow_from_path", since = "1.6.0")]
1448 impl<'a> From<PathBuf> for Cow<'a, Path> {
1450 fn from(s: PathBuf) -> Cow<'a, Path> {
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl ToOwned for Path {
1457 type Owned = PathBuf;
1458 fn to_owned(&self) -> PathBuf {
1461 fn clone_into(&self, target: &mut PathBuf) {
1462 self.inner.clone_into(&mut target.inner);
1466 #[stable(feature = "rust1", since = "1.0.0")]
1467 impl cmp::PartialEq for PathBuf {
1468 fn eq(&self, other: &PathBuf) -> bool {
1469 self.components() == other.components()
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl Hash for PathBuf {
1475 fn hash<H: Hasher>(&self, h: &mut H) {
1476 self.as_path().hash(h)
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl cmp::Eq for PathBuf {}
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl cmp::PartialOrd for PathBuf {
1485 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1486 self.components().partial_cmp(other.components())
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl cmp::Ord for PathBuf {
1492 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1493 self.components().cmp(other.components())
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 impl AsRef<OsStr> for PathBuf {
1499 fn as_ref(&self) -> &OsStr {
1504 /// A slice of a path (akin to [`str`]).
1506 /// This type supports a number of operations for inspecting a path, including
1507 /// breaking the path into its components (separated by `/` on Unix and by either
1508 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1509 /// is absolute, and so on.
1511 /// This is an *unsized* type, meaning that it must always be used behind a
1512 /// pointer like `&` or [`Box`]. For an owned version of this type,
1513 /// see [`PathBuf`].
1515 /// [`str`]: ../primitive.str.html
1516 /// [`Box`]: ../boxed/struct.Box.html
1517 /// [`PathBuf`]: struct.PathBuf.html
1519 /// More details about the overall approach can be found in
1520 /// the [module documentation](index.html).
1525 /// use std::path::Path;
1526 /// use std::ffi::OsStr;
1528 /// // Note: this example does work on Windows
1529 /// let path = Path::new("./foo/bar.txt");
1531 /// let parent = path.parent();
1532 /// assert_eq!(parent, Some(Path::new("./foo")));
1534 /// let file_stem = path.file_stem();
1535 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1537 /// let extension = path.extension();
1538 /// assert_eq!(extension, Some(OsStr::new("txt")));
1540 #[stable(feature = "rust1", since = "1.0.0")]
1545 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1548 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1549 /// See its documentation for more.
1551 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1552 /// [`Path`]: struct.Path.html
1553 #[derive(Debug, Clone, PartialEq, Eq)]
1554 #[stable(since = "1.7.0", feature = "strip_prefix")]
1555 pub struct StripPrefixError(());
1558 // The following (private!) function allows construction of a path from a u8
1559 // slice, which is only safe when it is known to follow the OsStr encoding.
1560 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1561 Path::new(u8_slice_as_os_str(s))
1563 // The following (private!) function reveals the byte encoding used for OsStr.
1564 fn as_u8_slice(&self) -> &[u8] {
1565 os_str_as_u8_slice(&self.inner)
1568 /// Directly wraps a string slice as a `Path` slice.
1570 /// This is a cost-free conversion.
1575 /// use std::path::Path;
1577 /// Path::new("foo.txt");
1580 /// You can create `Path`s from `String`s, or even other `Path`s:
1583 /// use std::path::Path;
1585 /// let string = String::from("foo.txt");
1586 /// let from_string = Path::new(&string);
1587 /// let from_path = Path::new(&from_string);
1588 /// assert_eq!(from_string, from_path);
1590 #[stable(feature = "rust1", since = "1.0.0")]
1591 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1592 unsafe { mem::transmute(s.as_ref()) }
1595 /// Yields the underlying [`OsStr`] slice.
1597 /// [`OsStr`]: ../ffi/struct.OsStr.html
1602 /// use std::path::Path;
1604 /// let os_str = Path::new("foo.txt").as_os_str();
1605 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 pub fn as_os_str(&self) -> &OsStr {
1612 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1614 /// This conversion may entail doing a check for UTF-8 validity.
1616 /// [`&str`]: ../primitive.str.html
1621 /// use std::path::Path;
1623 /// let path = Path::new("foo.txt");
1624 /// assert_eq!(path.to_str(), Some("foo.txt"));
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 pub fn to_str(&self) -> Option<&str> {
1631 /// Converts a `Path` to a [`Cow<str>`].
1633 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1635 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1639 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1642 /// use std::path::Path;
1644 /// let path = Path::new("foo.txt");
1645 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1648 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1649 /// have returned `"fo�.txt"`.
1650 #[stable(feature = "rust1", since = "1.0.0")]
1651 pub fn to_string_lossy(&self) -> Cow<str> {
1652 self.inner.to_string_lossy()
1655 /// Converts a `Path` to an owned [`PathBuf`].
1657 /// [`PathBuf`]: struct.PathBuf.html
1662 /// use std::path::Path;
1664 /// let path_buf = Path::new("foo.txt").to_path_buf();
1665 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1667 #[stable(feature = "rust1", since = "1.0.0")]
1668 pub fn to_path_buf(&self) -> PathBuf {
1669 PathBuf::from(self.inner.to_os_string())
1672 /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
1673 /// the current directory.
1675 /// * On Unix, a path is absolute if it starts with the root, so
1676 /// `is_absolute` and [`has_root`] are equivalent.
1678 /// * On Windows, a path is absolute if it has a prefix and starts with the
1679 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1684 /// use std::path::Path;
1686 /// assert!(!Path::new("foo.txt").is_absolute());
1689 /// [`has_root`]: #method.has_root
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 #[allow(deprecated)]
1692 pub fn is_absolute(&self) -> bool {
1693 if !cfg!(target_os = "redox") {
1694 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1696 // FIXME: Allow Redox prefixes
1697 has_redox_scheme(self.as_u8_slice())
1701 /// Returns `true` if the `Path` is relative, i.e. not absolute.
1703 /// See [`is_absolute`]'s documentation for more details.
1708 /// use std::path::Path;
1710 /// assert!(Path::new("foo.txt").is_relative());
1713 /// [`is_absolute`]: #method.is_absolute
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 pub fn is_relative(&self) -> bool {
1719 fn prefix(&self) -> Option<Prefix> {
1720 self.components().prefix
1723 /// Returns `true` if the `Path` has a root.
1725 /// * On Unix, a path has a root if it begins with `/`.
1727 /// * On Windows, a path has a root if it:
1728 /// * has no prefix and begins with a separator, e.g. `\\windows`
1729 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1730 /// * has any non-disk prefix, e.g. `\\server\share`
1735 /// use std::path::Path;
1737 /// assert!(Path::new("/etc/passwd").has_root());
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 pub fn has_root(&self) -> bool {
1741 self.components().has_root()
1744 /// Returns the `Path` without its final component, if there is one.
1746 /// Returns [`None`] if the path terminates in a root or prefix.
1748 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1753 /// use std::path::Path;
1755 /// let path = Path::new("/foo/bar");
1756 /// let parent = path.parent().unwrap();
1757 /// assert_eq!(parent, Path::new("/foo"));
1759 /// let grand_parent = parent.parent().unwrap();
1760 /// assert_eq!(grand_parent, Path::new("/"));
1761 /// assert_eq!(grand_parent.parent(), None);
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 pub fn parent(&self) -> Option<&Path> {
1765 let mut comps = self.components();
1766 let comp = comps.next_back();
1769 Component::Normal(_) |
1771 Component::ParentDir => Some(comps.as_path()),
1777 /// Returns the final component of the `Path`, if there is one.
1779 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1780 /// is the directory name.
1782 /// Returns [`None`] If the path terminates in `..`.
1784 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1789 /// use std::path::Path;
1790 /// use std::ffi::OsStr;
1792 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1793 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1794 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1795 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1796 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1797 /// assert_eq!(None, Path::new("/").file_name());
1799 #[stable(feature = "rust1", since = "1.0.0")]
1800 pub fn file_name(&self) -> Option<&OsStr> {
1801 self.components().next_back().and_then(|p| {
1803 Component::Normal(p) => Some(p.as_ref()),
1809 /// Returns a path that, when joined onto `base`, yields `self`.
1813 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1814 /// returns `false`), returns [`Err`].
1816 /// [`starts_with`]: #method.starts_with
1817 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1822 /// use std::path::Path;
1824 /// let path = Path::new("/test/haha/foo.txt");
1826 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1827 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1828 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1830 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1831 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1832 -> Result<&'a Path, StripPrefixError>
1833 where P: AsRef<Path>
1835 self._strip_prefix(base.as_ref())
1838 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1839 -> Result<&'a Path, StripPrefixError> {
1840 iter_after(self.components(), base.components())
1841 .map(|c| c.as_path())
1842 .ok_or(StripPrefixError(()))
1845 /// Determines whether `base` is a prefix of `self`.
1847 /// Only considers whole path components to match.
1852 /// use std::path::Path;
1854 /// let path = Path::new("/etc/passwd");
1856 /// assert!(path.starts_with("/etc"));
1858 /// assert!(!path.starts_with("/e"));
1860 #[stable(feature = "rust1", since = "1.0.0")]
1861 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1862 self._starts_with(base.as_ref())
1865 fn _starts_with(&self, base: &Path) -> bool {
1866 iter_after(self.components(), base.components()).is_some()
1869 /// Determines whether `child` is a suffix of `self`.
1871 /// Only considers whole path components to match.
1876 /// use std::path::Path;
1878 /// let path = Path::new("/etc/passwd");
1880 /// assert!(path.ends_with("passwd"));
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1884 self._ends_with(child.as_ref())
1887 fn _ends_with(&self, child: &Path) -> bool {
1888 iter_after(self.components().rev(), child.components().rev()).is_some()
1891 /// Extracts the stem (non-extension) portion of [`self.file_name`].
1893 /// [`self.file_name`]: struct.Path.html#method.file_name
1897 /// * [`None`], if there is no file name;
1898 /// * The entire file name if there is no embedded `.`;
1899 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1900 /// * Otherwise, the portion of the file name before the final `.`
1902 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1907 /// use std::path::Path;
1909 /// let path = Path::new("foo.rs");
1911 /// assert_eq!("foo", path.file_stem().unwrap());
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 pub fn file_stem(&self) -> Option<&OsStr> {
1915 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1918 /// Extracts the extension of [`self.file_name`], if possible.
1920 /// The extension is:
1922 /// * [`None`], if there is no file name;
1923 /// * [`None`], if there is no embedded `.`;
1924 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1925 /// * Otherwise, the portion of the file name after the final `.`
1927 /// [`self.file_name`]: struct.Path.html#method.file_name
1928 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1933 /// use std::path::Path;
1935 /// let path = Path::new("foo.rs");
1937 /// assert_eq!("rs", path.extension().unwrap());
1939 #[stable(feature = "rust1", since = "1.0.0")]
1940 pub fn extension(&self) -> Option<&OsStr> {
1941 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1944 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1946 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1948 /// [`PathBuf`]: struct.PathBuf.html
1949 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
1954 /// use std::path::{Path, PathBuf};
1956 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1960 self._join(path.as_ref())
1963 fn _join(&self, path: &Path) -> PathBuf {
1964 let mut buf = self.to_path_buf();
1969 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
1971 /// See [`PathBuf::set_file_name`] for more details.
1973 /// [`PathBuf`]: struct.PathBuf.html
1974 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
1979 /// use std::path::{Path, PathBuf};
1981 /// let path = Path::new("/tmp/foo.txt");
1982 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1984 /// let path = Path::new("/tmp");
1985 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1989 self._with_file_name(file_name.as_ref())
1992 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1993 let mut buf = self.to_path_buf();
1994 buf.set_file_name(file_name);
1998 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2000 /// See [`PathBuf::set_extension`] for more details.
2002 /// [`PathBuf`]: struct.PathBuf.html
2003 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2008 /// use std::path::{Path, PathBuf};
2010 /// let path = Path::new("foo.rs");
2011 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2015 self._with_extension(extension.as_ref())
2018 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2019 let mut buf = self.to_path_buf();
2020 buf.set_extension(extension);
2024 /// Produces an iterator over the [`Component`]s of the path.
2026 /// When parsing the path, there is a small amount of normalization:
2028 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2029 /// `a` and `b` as components.
2031 /// * Occurrences of `.` are normalized away, except if they are at the
2032 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2033 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2034 /// an additional [`CurDir`] component.
2036 /// Note that no other normalization takes place; in particular, `a/c`
2037 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2038 /// is a symbolic link (so its parent isn't `a`).
2043 /// use std::path::{Path, Component};
2044 /// use std::ffi::OsStr;
2046 /// let mut components = Path::new("/tmp/foo.txt").components();
2048 /// assert_eq!(components.next(), Some(Component::RootDir));
2049 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2050 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2051 /// assert_eq!(components.next(), None)
2054 /// [`Component`]: enum.Component.html
2055 /// [`CurDir`]: enum.Component.html#variant.CurDir
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 pub fn components(&self) -> Components {
2058 let prefix = parse_prefix(self.as_os_str());
2060 path: self.as_u8_slice(),
2062 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2063 has_redox_scheme(self.as_u8_slice()),
2064 front: State::Prefix,
2069 /// Produces an iterator over the path's components viewed as [`OsStr`]
2072 /// For more information about the particulars of how the path is separated
2073 /// into components, see [`components`].
2075 /// [`components`]: #method.components
2076 /// [`OsStr`]: ../ffi/struct.OsStr.html
2081 /// use std::path::{self, Path};
2082 /// use std::ffi::OsStr;
2084 /// let mut it = Path::new("/tmp/foo.txt").iter();
2085 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2086 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2087 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2088 /// assert_eq!(it.next(), None)
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub fn iter(&self) -> Iter {
2092 Iter { inner: self.components() }
2095 /// Returns an object that implements [`Display`] for safely printing paths
2096 /// that may contain non-Unicode data.
2098 /// [`Display`]: ../fmt/trait.Display.html
2103 /// use std::path::Path;
2105 /// let path = Path::new("/tmp/foo.rs");
2107 /// println!("{}", path.display());
2109 #[stable(feature = "rust1", since = "1.0.0")]
2110 pub fn display(&self) -> Display {
2111 Display { path: self }
2114 /// Queries the file system to get information about a file, directory, etc.
2116 /// This function will traverse symbolic links to query information about the
2117 /// destination file.
2119 /// This is an alias to [`fs::metadata`].
2121 /// [`fs::metadata`]: ../fs/fn.metadata.html
2126 /// use std::path::Path;
2128 /// let path = Path::new("/Minas/tirith");
2129 /// let metadata = path.metadata().expect("metadata call failed");
2130 /// println!("{:?}", metadata.file_type());
2132 #[stable(feature = "path_ext", since = "1.5.0")]
2133 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2137 /// Queries the metadata about a file without following symlinks.
2139 /// This is an alias to [`fs::symlink_metadata`].
2141 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2146 /// use std::path::Path;
2148 /// let path = Path::new("/Minas/tirith");
2149 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2150 /// println!("{:?}", metadata.file_type());
2152 #[stable(feature = "path_ext", since = "1.5.0")]
2153 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2154 fs::symlink_metadata(self)
2157 /// Returns the canonical form of the path with all intermediate components
2158 /// normalized and symbolic links resolved.
2160 /// This is an alias to [`fs::canonicalize`].
2162 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2167 /// use std::path::{Path, PathBuf};
2169 /// let path = Path::new("/foo/test/../test/bar.rs");
2170 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2172 #[stable(feature = "path_ext", since = "1.5.0")]
2173 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2174 fs::canonicalize(self)
2177 /// Reads a symbolic link, returning the file that the link points to.
2179 /// This is an alias to [`fs::read_link`].
2181 /// [`fs::read_link`]: ../fs/fn.read_link.html
2186 /// use std::path::Path;
2188 /// let path = Path::new("/laputa/sky_castle.rs");
2189 /// let path_link = path.read_link().expect("read_link call failed");
2191 #[stable(feature = "path_ext", since = "1.5.0")]
2192 pub fn read_link(&self) -> io::Result<PathBuf> {
2196 /// Returns an iterator over the entries within a directory.
2198 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2199 /// errors may be encountered after an iterator is initially constructed.
2201 /// This is an alias to [`fs::read_dir`].
2203 /// [`io::Result`]: ../io/type.Result.html
2204 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2205 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2210 /// use std::path::Path;
2212 /// let path = Path::new("/laputa");
2213 /// for entry in path.read_dir().expect("read_dir call failed") {
2214 /// if let Ok(entry) = entry {
2215 /// println!("{:?}", entry.path());
2219 #[stable(feature = "path_ext", since = "1.5.0")]
2220 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2224 /// Returns whether the path points at an existing entity.
2226 /// This function will traverse symbolic links to query information about the
2227 /// destination file. In case of broken symbolic links this will return `false`.
2229 /// If you cannot access the directory containing the file, e.g. because of a
2230 /// permission error, this will return `false`.
2235 /// use std::path::Path;
2236 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2241 /// This is a convenience function that coerces errors to false. If you want to
2242 /// check errors, call [fs::metadata].
2244 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2245 #[stable(feature = "path_ext", since = "1.5.0")]
2246 pub fn exists(&self) -> bool {
2247 fs::metadata(self).is_ok()
2250 /// Returns whether the path exists on disk and is pointing at a regular file.
2252 /// This function will traverse symbolic links to query information about the
2253 /// destination file. In case of broken symbolic links this will return `false`.
2255 /// If you cannot access the directory containing the file, e.g. because of a
2256 /// permission error, this will return `false`.
2261 /// use std::path::Path;
2262 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2263 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2268 /// This is a convenience function that coerces errors to false. If you want to
2269 /// check errors, call [fs::metadata] and handle its Result. Then call
2270 /// [fs::Metadata::is_file] if it was Ok.
2272 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2273 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2274 #[stable(feature = "path_ext", since = "1.5.0")]
2275 pub fn is_file(&self) -> bool {
2276 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2279 /// Returns whether the path exists on disk and is pointing at a directory.
2281 /// This function will traverse symbolic links to query information about the
2282 /// destination file. In case of broken symbolic links this will return `false`.
2284 /// If you cannot access the directory containing the file, e.g. because of a
2285 /// permission error, this will return `false`.
2290 /// use std::path::Path;
2291 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2292 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2297 /// This is a convenience function that coerces errors to false. If you want to
2298 /// check errors, call [fs::metadata] and handle its Result. Then call
2299 /// [fs::Metadata::is_dir] if it was Ok.
2301 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2302 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2303 #[stable(feature = "path_ext", since = "1.5.0")]
2304 pub fn is_dir(&self) -> bool {
2305 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2308 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2311 /// [`Box`]: ../../std/boxed/struct.Box.html
2312 /// [`PathBuf`]: struct.PathBuf.html
2313 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2314 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2315 let inner: Box<OsStr> = unsafe { mem::transmute(self) };
2316 PathBuf { inner: OsString::from(inner) }
2320 #[stable(feature = "rust1", since = "1.0.0")]
2321 impl AsRef<OsStr> for Path {
2322 fn as_ref(&self) -> &OsStr {
2327 #[stable(feature = "rust1", since = "1.0.0")]
2328 impl fmt::Debug for Path {
2329 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2330 fmt::Debug::fmt(&self.inner, formatter)
2334 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2336 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2337 /// [`Display`] trait in a way that mitigates that. It is created by the
2338 /// [`display`][`Path::display`] method on [`Path`].
2343 /// use std::path::Path;
2345 /// let path = Path::new("/tmp/foo.rs");
2347 /// println!("{}", path.display());
2350 /// [`Display`]: ../../std/fmt/trait.Display.html
2351 /// [`format!`]: ../../std/macro.format.html
2352 /// [`Path`]: struct.Path.html
2353 /// [`Path::display`]: struct.Path.html#method.display
2354 #[stable(feature = "rust1", since = "1.0.0")]
2355 pub struct Display<'a> {
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 impl<'a> fmt::Debug for Display<'a> {
2361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2362 fmt::Debug::fmt(&self.path, f)
2366 #[stable(feature = "rust1", since = "1.0.0")]
2367 impl<'a> fmt::Display for Display<'a> {
2368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2369 self.path.inner.display(f)
2373 #[stable(feature = "rust1", since = "1.0.0")]
2374 impl cmp::PartialEq for Path {
2375 fn eq(&self, other: &Path) -> bool {
2376 self.components().eq(other.components())
2380 #[stable(feature = "rust1", since = "1.0.0")]
2381 impl Hash for Path {
2382 fn hash<H: Hasher>(&self, h: &mut H) {
2383 for component in self.components() {
2389 #[stable(feature = "rust1", since = "1.0.0")]
2390 impl cmp::Eq for Path {}
2392 #[stable(feature = "rust1", since = "1.0.0")]
2393 impl cmp::PartialOrd for Path {
2394 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2395 self.components().partial_cmp(other.components())
2399 #[stable(feature = "rust1", since = "1.0.0")]
2400 impl cmp::Ord for Path {
2401 fn cmp(&self, other: &Path) -> cmp::Ordering {
2402 self.components().cmp(other.components())
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 impl AsRef<Path> for Path {
2408 fn as_ref(&self) -> &Path {
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl AsRef<Path> for OsStr {
2415 fn as_ref(&self) -> &Path {
2420 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2421 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2422 fn as_ref(&self) -> &Path {
2427 #[stable(feature = "rust1", since = "1.0.0")]
2428 impl AsRef<Path> for OsString {
2429 fn as_ref(&self) -> &Path {
2434 #[stable(feature = "rust1", since = "1.0.0")]
2435 impl AsRef<Path> for str {
2436 fn as_ref(&self) -> &Path {
2441 #[stable(feature = "rust1", since = "1.0.0")]
2442 impl AsRef<Path> for String {
2443 fn as_ref(&self) -> &Path {
2448 #[stable(feature = "rust1", since = "1.0.0")]
2449 impl AsRef<Path> for PathBuf {
2450 fn as_ref(&self) -> &Path {
2455 #[stable(feature = "path_into_iter", since = "1.6.0")]
2456 impl<'a> IntoIterator for &'a PathBuf {
2457 type Item = &'a OsStr;
2458 type IntoIter = Iter<'a>;
2459 fn into_iter(self) -> Iter<'a> { self.iter() }
2462 #[stable(feature = "path_into_iter", since = "1.6.0")]
2463 impl<'a> IntoIterator for &'a Path {
2464 type Item = &'a OsStr;
2465 type IntoIter = Iter<'a>;
2466 fn into_iter(self) -> Iter<'a> { self.iter() }
2469 macro_rules! impl_cmp {
2470 ($lhs:ty, $rhs: ty) => {
2471 #[stable(feature = "partialeq_path", since = "1.6.0")]
2472 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2474 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2477 #[stable(feature = "partialeq_path", since = "1.6.0")]
2478 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2480 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2483 #[stable(feature = "cmp_path", since = "1.8.0")]
2484 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2486 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2487 <Path as PartialOrd>::partial_cmp(self, other)
2491 #[stable(feature = "cmp_path", since = "1.8.0")]
2492 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2494 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2495 <Path as PartialOrd>::partial_cmp(self, other)
2501 impl_cmp!(PathBuf, Path);
2502 impl_cmp!(PathBuf, &'a Path);
2503 impl_cmp!(Cow<'a, Path>, Path);
2504 impl_cmp!(Cow<'a, Path>, &'b Path);
2505 impl_cmp!(Cow<'a, Path>, PathBuf);
2507 macro_rules! impl_cmp_os_str {
2508 ($lhs:ty, $rhs: ty) => {
2509 #[stable(feature = "cmp_path", since = "1.8.0")]
2510 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2512 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2515 #[stable(feature = "cmp_path", since = "1.8.0")]
2516 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2518 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2521 #[stable(feature = "cmp_path", since = "1.8.0")]
2522 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2524 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2525 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2529 #[stable(feature = "cmp_path", since = "1.8.0")]
2530 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2532 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2533 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2539 impl_cmp_os_str!(PathBuf, OsStr);
2540 impl_cmp_os_str!(PathBuf, &'a OsStr);
2541 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2542 impl_cmp_os_str!(PathBuf, OsString);
2543 impl_cmp_os_str!(Path, OsStr);
2544 impl_cmp_os_str!(Path, &'a OsStr);
2545 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2546 impl_cmp_os_str!(Path, OsString);
2547 impl_cmp_os_str!(&'a Path, OsStr);
2548 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2549 impl_cmp_os_str!(&'a Path, OsString);
2550 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2551 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2552 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2554 #[stable(since = "1.7.0", feature = "strip_prefix")]
2555 impl fmt::Display for StripPrefixError {
2556 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2557 self.description().fmt(f)
2561 #[stable(since = "1.7.0", feature = "strip_prefix")]
2562 impl Error for StripPrefixError {
2563 fn description(&self) -> &str { "prefix not found" }
2571 ($path:expr, iter: $iter:expr) => (
2573 let path = Path::new($path);
2575 // Forward iteration
2576 let comps = path.iter()
2577 .map(|p| p.to_string_lossy().into_owned())
2578 .collect::<Vec<String>>();
2579 let exp: &[&str] = &$iter;
2580 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2581 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2584 // Reverse iteration
2585 let comps = Path::new($path).iter().rev()
2586 .map(|p| p.to_string_lossy().into_owned())
2587 .collect::<Vec<String>>();
2588 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2589 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2594 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2596 let path = Path::new($path);
2598 let act_root = path.has_root();
2599 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2600 $has_root, act_root);
2602 let act_abs = path.is_absolute();
2603 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2604 $is_absolute, act_abs);
2608 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2610 let path = Path::new($path);
2612 let parent = path.parent().map(|p| p.to_str().unwrap());
2613 let exp_parent: Option<&str> = $parent;
2614 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2615 exp_parent, parent);
2617 let file = path.file_name().map(|p| p.to_str().unwrap());
2618 let exp_file: Option<&str> = $file;
2619 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2624 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2626 let path = Path::new($path);
2628 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2629 let exp_stem: Option<&str> = $file_stem;
2630 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2633 let ext = path.extension().map(|p| p.to_str().unwrap());
2634 let exp_ext: Option<&str> = $extension;
2635 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2640 ($path:expr, iter: $iter:expr,
2641 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2642 parent: $parent:expr, file_name: $file:expr,
2643 file_stem: $file_stem:expr, extension: $extension:expr) => (
2645 t!($path, iter: $iter);
2646 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2647 t!($path, parent: $parent, file_name: $file);
2648 t!($path, file_stem: $file_stem, extension: $extension);
2657 let static_path = Path::new("/home/foo");
2658 let static_cow_path: Cow<'static, Path> = static_path.into();
2659 let pathbuf = PathBuf::from("/home/foo");
2662 let path: &Path = &pathbuf;
2663 let borrowed_cow_path: Cow<Path> = path.into();
2665 assert_eq!(static_cow_path, borrowed_cow_path);
2668 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2670 assert_eq!(static_cow_path, owned_cow_path);
2675 pub fn test_decompositions_unix() {
2691 file_name: Some("foo"),
2692 file_stem: Some("foo"),
2711 file_name: Some("foo"),
2712 file_stem: Some("foo"),
2721 file_name: Some("foo"),
2722 file_stem: Some("foo"),
2731 file_name: Some("foo"),
2732 file_stem: Some("foo"),
2737 iter: ["foo", "bar"],
2740 parent: Some("foo"),
2741 file_name: Some("bar"),
2742 file_stem: Some("bar"),
2747 iter: ["/", "foo", "bar"],
2750 parent: Some("/foo"),
2751 file_name: Some("bar"),
2752 file_stem: Some("bar"),
2761 file_name: Some("foo"),
2762 file_stem: Some("foo"),
2767 iter: ["/", "foo", "bar"],
2770 parent: Some("///foo"),
2771 file_name: Some("bar"),
2772 file_stem: Some("bar"),
2811 file_name: Some("foo"),
2812 file_stem: Some("foo"),
2817 iter: ["foo", ".."],
2820 parent: Some("foo"),
2831 file_name: Some("foo"),
2832 file_stem: Some("foo"),
2837 iter: ["foo", "bar"],
2840 parent: Some("foo"),
2841 file_name: Some("bar"),
2842 file_stem: Some("bar"),
2847 iter: ["foo", ".."],
2850 parent: Some("foo"),
2857 iter: ["foo", "..", "bar"],
2860 parent: Some("foo/.."),
2861 file_name: Some("bar"),
2862 file_stem: Some("bar"),
2871 file_name: Some("a"),
2872 file_stem: Some("a"),
2901 file_name: Some("b"),
2902 file_stem: Some("b"),
2911 file_name: Some("b"),
2912 file_stem: Some("b"),
2921 file_name: Some("b"),
2922 file_stem: Some("b"),
2927 iter: ["a", "b", "c"],
2930 parent: Some("a/b"),
2931 file_name: Some("c"),
2932 file_stem: Some("c"),
2941 file_name: Some(".foo"),
2942 file_stem: Some(".foo"),
2949 pub fn test_decompositions_windows() {
2965 file_name: Some("foo"),
2966 file_stem: Some("foo"),
3021 iter: ["\\", "foo"],
3025 file_name: Some("foo"),
3026 file_stem: Some("foo"),
3035 file_name: Some("foo"),
3036 file_stem: Some("foo"),
3041 iter: ["\\", "foo"],
3045 file_name: Some("foo"),
3046 file_stem: Some("foo"),
3051 iter: ["foo", "bar"],
3054 parent: Some("foo"),
3055 file_name: Some("bar"),
3056 file_stem: Some("bar"),
3061 iter: ["\\", "foo", "bar"],
3064 parent: Some("/foo"),
3065 file_name: Some("bar"),
3066 file_stem: Some("bar"),
3071 iter: ["\\", "foo"],
3075 file_name: Some("foo"),
3076 file_stem: Some("foo"),
3081 iter: ["\\", "foo", "bar"],
3084 parent: Some("///foo"),
3085 file_name: Some("bar"),
3086 file_stem: Some("bar"),
3125 file_name: Some("foo"),
3126 file_stem: Some("foo"),
3131 iter: ["foo", ".."],
3134 parent: Some("foo"),
3145 file_name: Some("foo"),
3146 file_stem: Some("foo"),
3151 iter: ["foo", "bar"],
3154 parent: Some("foo"),
3155 file_name: Some("bar"),
3156 file_stem: Some("bar"),
3161 iter: ["foo", ".."],
3164 parent: Some("foo"),
3171 iter: ["foo", "..", "bar"],
3174 parent: Some("foo/.."),
3175 file_name: Some("bar"),
3176 file_stem: Some("bar"),
3185 file_name: Some("a"),
3186 file_stem: Some("a"),
3215 file_name: Some("b"),
3216 file_stem: Some("b"),
3225 file_name: Some("b"),
3226 file_stem: Some("b"),
3235 file_name: Some("b"),
3236 file_stem: Some("b"),
3241 iter: ["a", "b", "c"],
3244 parent: Some("a/b"),
3245 file_name: Some("c"),
3246 file_stem: Some("c"),
3250 iter: ["a", "b", "c"],
3253 parent: Some("a\\b"),
3254 file_name: Some("c"),
3255 file_stem: Some("c"),
3264 file_name: Some("a"),
3265 file_stem: Some("a"),
3270 iter: ["c:", "\\", "foo.txt"],
3273 parent: Some("c:\\"),
3274 file_name: Some("foo.txt"),
3275 file_stem: Some("foo"),
3276 extension: Some("txt")
3279 t!("\\\\server\\share\\foo.txt",
3280 iter: ["\\\\server\\share", "\\", "foo.txt"],
3283 parent: Some("\\\\server\\share\\"),
3284 file_name: Some("foo.txt"),
3285 file_stem: Some("foo"),
3286 extension: Some("txt")
3289 t!("\\\\server\\share",
3290 iter: ["\\\\server\\share", "\\"],
3300 iter: ["\\", "server"],
3304 file_name: Some("server"),
3305 file_stem: Some("server"),
3309 t!("\\\\?\\bar\\foo.txt",
3310 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3313 parent: Some("\\\\?\\bar\\"),
3314 file_name: Some("foo.txt"),
3315 file_stem: Some("foo"),
3316 extension: Some("txt")
3320 iter: ["\\\\?\\bar"],
3339 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3340 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3343 parent: Some("\\\\?\\UNC\\server\\share\\"),
3344 file_name: Some("foo.txt"),
3345 file_stem: Some("foo"),
3346 extension: Some("txt")
3349 t!("\\\\?\\UNC\\server",
3350 iter: ["\\\\?\\UNC\\server"],
3360 iter: ["\\\\?\\UNC\\"],
3369 t!("\\\\?\\C:\\foo.txt",
3370 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3373 parent: Some("\\\\?\\C:\\"),
3374 file_name: Some("foo.txt"),
3375 file_stem: Some("foo"),
3376 extension: Some("txt")
3381 iter: ["\\\\?\\C:", "\\"],
3392 iter: ["\\\\?\\C:"],
3402 t!("\\\\?\\foo/bar",
3403 iter: ["\\\\?\\foo/bar"],
3414 iter: ["\\\\?\\C:/foo"],
3424 t!("\\\\.\\foo\\bar",
3425 iter: ["\\\\.\\foo", "\\", "bar"],
3428 parent: Some("\\\\.\\foo\\"),
3429 file_name: Some("bar"),
3430 file_stem: Some("bar"),
3436 iter: ["\\\\.\\foo", "\\"],
3446 t!("\\\\.\\foo/bar",
3447 iter: ["\\\\.\\foo/bar", "\\"],
3457 t!("\\\\.\\foo\\bar/baz",
3458 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3461 parent: Some("\\\\.\\foo\\bar"),
3462 file_name: Some("baz"),
3463 file_stem: Some("baz"),
3469 iter: ["\\\\.\\", "\\"],
3479 iter: ["\\\\?\\a", "\\", "b"],
3482 parent: Some("\\\\?\\a\\"),
3483 file_name: Some("b"),
3484 file_stem: Some("b"),
3490 pub fn test_stem_ext() {
3492 file_stem: Some("foo"),
3497 file_stem: Some("foo"),
3502 file_stem: Some(".foo"),
3507 file_stem: Some("foo"),
3508 extension: Some("txt")
3512 file_stem: Some("foo.bar"),
3513 extension: Some("txt")
3517 file_stem: Some("foo.bar"),
3538 pub fn test_push() {
3540 ($path:expr, $push:expr, $expected:expr) => ( {
3541 let mut actual = PathBuf::from($path);
3543 assert!(actual.to_str() == Some($expected),
3544 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3545 $push, $path, $expected, actual.to_str().unwrap());
3550 tp!("", "foo", "foo");
3551 tp!("foo", "bar", "foo/bar");
3552 tp!("foo/", "bar", "foo/bar");
3553 tp!("foo//", "bar", "foo//bar");
3554 tp!("foo/.", "bar", "foo/./bar");
3555 tp!("foo./.", "bar", "foo././bar");
3556 tp!("foo", "", "foo/");
3557 tp!("foo", ".", "foo/.");
3558 tp!("foo", "..", "foo/..");
3559 tp!("foo", "/", "/");
3560 tp!("/foo/bar", "/", "/");
3561 tp!("/foo/bar", "/baz", "/baz");
3562 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3564 tp!("", "foo", "foo");
3565 tp!("foo", "bar", r"foo\bar");
3566 tp!("foo/", "bar", r"foo/bar");
3567 tp!(r"foo\", "bar", r"foo\bar");
3568 tp!("foo//", "bar", r"foo//bar");
3569 tp!(r"foo\\", "bar", r"foo\\bar");
3570 tp!("foo/.", "bar", r"foo/.\bar");
3571 tp!("foo./.", "bar", r"foo./.\bar");
3572 tp!(r"foo\.", "bar", r"foo\.\bar");
3573 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3574 tp!("foo", "", "foo\\");
3575 tp!("foo", ".", r"foo\.");
3576 tp!("foo", "..", r"foo\..");
3577 tp!("foo", "/", "/");
3578 tp!("foo", r"\", r"\");
3579 tp!("/foo/bar", "/", "/");
3580 tp!(r"\foo\bar", r"\", r"\");
3581 tp!("/foo/bar", "/baz", "/baz");
3582 tp!("/foo/bar", r"\baz", r"\baz");
3583 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3584 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3586 tp!("c:\\", "windows", "c:\\windows");
3587 tp!("c:", "windows", "c:windows");
3589 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3590 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3591 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3592 tp!("a\\b", "\\c\\d", "\\c\\d");
3593 tp!("a\\b", ".", "a\\b\\.");
3594 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3595 tp!("a\\b", "C:a.txt", "C:a.txt");
3596 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3597 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3598 tp!("C:\\a\\b\\c", "C:d", "C:d");
3599 tp!("C:a\\b\\c", "C:d", "C:d");
3600 tp!("C:", r"a\b\c", r"C:a\b\c");
3601 tp!("C:", r"..\a", r"C:..\a");
3602 tp!("\\\\server\\share\\foo",
3604 "\\\\server\\share\\foo\\bar");
3605 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3606 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3607 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3608 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3609 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3610 tp!("\\\\?\\UNC\\server\\share\\foo",
3612 "\\\\?\\UNC\\server\\share\\foo\\bar");
3613 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3614 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3616 // Note: modified from old path API
3617 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3620 "\\\\?\\UNC\\server\\share",
3621 "\\\\?\\UNC\\server\\share");
3622 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3623 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3624 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3625 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3627 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3634 ($path:expr, $expected:expr, $output:expr) => ( {
3635 let mut actual = PathBuf::from($path);
3636 let output = actual.pop();
3637 assert!(actual.to_str() == Some($expected) && output == $output,
3638 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3639 $path, $expected, $output,
3640 actual.to_str().unwrap(), output);
3645 tp!("/", "/", false);
3646 tp!("foo", "", true);
3648 tp!("/foo", "/", true);
3649 tp!("/foo/bar", "/foo", true);
3650 tp!("foo/bar", "foo", true);
3651 tp!("foo/.", "", true);
3652 tp!("foo//bar", "foo", true);
3655 tp!("a\\b\\c", "a\\b", true);
3656 tp!("\\a", "\\", true);
3657 tp!("\\", "\\", false);
3659 tp!("C:\\a\\b", "C:\\a", true);
3660 tp!("C:\\a", "C:\\", true);
3661 tp!("C:\\", "C:\\", false);
3662 tp!("C:a\\b", "C:a", true);
3663 tp!("C:a", "C:", true);
3664 tp!("C:", "C:", false);
3665 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3666 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3667 tp!("\\\\server\\share", "\\\\server\\share", false);
3668 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3669 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3670 tp!("\\\\?\\a", "\\\\?\\a", false);
3671 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3672 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3673 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3674 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3675 "\\\\?\\UNC\\server\\share\\a",
3677 tp!("\\\\?\\UNC\\server\\share\\a",
3678 "\\\\?\\UNC\\server\\share\\",
3680 tp!("\\\\?\\UNC\\server\\share",
3681 "\\\\?\\UNC\\server\\share",
3683 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3684 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3685 tp!("\\\\.\\a", "\\\\.\\a", false);
3687 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3692 pub fn test_set_file_name() {
3694 ($path:expr, $file:expr, $expected:expr) => ( {
3695 let mut p = PathBuf::from($path);
3696 p.set_file_name($file);
3697 assert!(p.to_str() == Some($expected),
3698 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3699 $path, $file, $expected,
3700 p.to_str().unwrap());
3704 tfn!("foo", "foo", "foo");
3705 tfn!("foo", "bar", "bar");
3706 tfn!("foo", "", "");
3707 tfn!("", "foo", "foo");
3709 tfn!(".", "foo", "./foo");
3710 tfn!("foo/", "bar", "bar");
3711 tfn!("foo/.", "bar", "bar");
3712 tfn!("..", "foo", "../foo");
3713 tfn!("foo/..", "bar", "foo/../bar");
3714 tfn!("/", "foo", "/foo");
3716 tfn!(".", "foo", r".\foo");
3717 tfn!(r"foo\", "bar", r"bar");
3718 tfn!(r"foo\.", "bar", r"bar");
3719 tfn!("..", "foo", r"..\foo");
3720 tfn!(r"foo\..", "bar", r"foo\..\bar");
3721 tfn!(r"\", "foo", r"\foo");
3726 pub fn test_set_extension() {
3728 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3729 let mut p = PathBuf::from($path);
3730 let output = p.set_extension($ext);
3731 assert!(p.to_str() == Some($expected) && output == $output,
3732 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3733 $path, $ext, $expected, $output,
3734 p.to_str().unwrap(), output);
3738 tfe!("foo", "txt", "foo.txt", true);
3739 tfe!("foo.bar", "txt", "foo.txt", true);
3740 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3741 tfe!(".test", "txt", ".test.txt", true);
3742 tfe!("foo.txt", "", "foo", true);
3743 tfe!("foo", "", "foo", true);
3744 tfe!("", "foo", "", false);
3745 tfe!(".", "foo", ".", false);
3746 tfe!("foo/", "bar", "foo.bar", true);
3747 tfe!("foo/.", "bar", "foo.bar", true);
3748 tfe!("..", "foo", "..", false);
3749 tfe!("foo/..", "bar", "foo/..", false);
3750 tfe!("/", "foo", "/", false);
3754 fn test_eq_recievers() {
3757 let borrowed: &Path = Path::new("foo/bar");
3758 let mut owned: PathBuf = PathBuf::new();
3761 let borrowed_cow: Cow<Path> = borrowed.into();
3762 let owned_cow: Cow<Path> = owned.clone().into();
3765 ($($current:expr),+) => {
3767 assert_eq!($current, borrowed);
3768 assert_eq!($current, owned);
3769 assert_eq!($current, borrowed_cow);
3770 assert_eq!($current, owned_cow);
3775 t!(borrowed, owned, borrowed_cow, owned_cow);
3779 pub fn test_compare() {
3780 use hash::{Hash, Hasher};
3781 use collections::hash_map::DefaultHasher;
3783 fn hash<T: Hash>(t: T) -> u64 {
3784 let mut s = DefaultHasher::new();
3790 ($path1:expr, $path2:expr, eq: $eq:expr,
3791 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3792 relative_from: $relative_from:expr) => ({
3793 let path1 = Path::new($path1);
3794 let path2 = Path::new($path2);
3796 let eq = path1 == path2;
3797 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3798 $path1, $path2, $eq, eq);
3799 assert!($eq == (hash(path1) == hash(path2)),
3800 "{:?} == {:?}, expected {:?}, got {} and {}",
3801 $path1, $path2, $eq, hash(path1), hash(path2));
3803 let starts_with = path1.starts_with(path2);
3804 assert!(starts_with == $starts_with,
3805 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3806 $starts_with, starts_with);
3808 let ends_with = path1.ends_with(path2);
3809 assert!(ends_with == $ends_with,
3810 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3811 $ends_with, ends_with);
3813 let relative_from = path1.strip_prefix(path2)
3814 .map(|p| p.to_str().unwrap())
3816 let exp: Option<&str> = $relative_from;
3817 assert!(relative_from == exp,
3818 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3819 $path1, $path2, exp, relative_from);
3827 relative_from: Some("")
3834 relative_from: Some("foo")
3848 relative_from: Some("")
3855 relative_from: Some("")
3858 tc!("foo/bar", "foo",
3862 relative_from: Some("bar")
3865 tc!("foo/bar/baz", "foo/bar",
3869 relative_from: Some("baz")
3872 tc!("foo/bar", "foo/bar/baz",
3879 tc!("./foo/bar/", ".",
3883 relative_from: Some("foo/bar")
3887 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3888 r"c:\src\rust\cargo-test\test",
3892 relative_from: Some("Cargo.toml")
3895 tc!(r"c:\foo", r"C:\foo",
3899 relative_from: Some("")
3905 fn test_components_debug() {
3906 let path = Path::new("/tmp");
3908 let mut components = path.components();
3910 let expected = "Components([RootDir, Normal(\"tmp\")])";
3911 let actual = format!("{:?}", components);
3912 assert_eq!(expected, actual);
3914 let _ = components.next().unwrap();
3915 let expected = "Components([Normal(\"tmp\")])";
3916 let actual = format!("{:?}", components);
3917 assert_eq!(expected, actual);
3919 let _ = components.next().unwrap();
3920 let expected = "Components([])";
3921 let actual = format!("{:?}", components);
3922 assert_eq!(expected, actual);
3927 fn test_iter_debug() {
3928 let path = Path::new("/tmp");
3930 let mut iter = path.iter();
3932 let expected = "Iter([\"/\", \"tmp\"])";
3933 let actual = format!("{:?}", iter);
3934 assert_eq!(expected, actual);
3936 let _ = iter.next().unwrap();
3937 let expected = "Iter([\"tmp\"])";
3938 let actual = format!("{:?}", iter);
3939 assert_eq!(expected, actual);
3941 let _ = iter.next().unwrap();
3942 let expected = "Iter([])";
3943 let actual = format!("{:?}", iter);
3944 assert_eq!(expected, actual);
3949 let orig: &str = "some/sort/of/path";
3950 let path = Path::new(orig);
3951 let boxed: Box<Path> = Box::from(path);
3952 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
3953 assert_eq!(path, &*boxed);
3954 assert_eq!(&*boxed, &*path_buf);
3955 assert_eq!(&*path_buf, path);
3959 fn test_clone_into() {
3960 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
3961 let path = Path::new("short");
3962 path.clone_into(&mut path_buf);
3963 assert_eq!(path, path_buf);
3964 assert!(path_buf.into_os_string().capacity() >= 15);