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")]
80 use borrow::{Borrow, Cow};
85 use hash::{Hash, Hasher};
87 use iter::{self, FusedIterator};
88 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 { &*(s as *const OsStr as *const [u8]) }
322 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
323 &*(s as *const [u8] as *const 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 #[stable(feature = "path_component_asref", since = "1.24.0")]
580 impl<'a> AsRef<Path> for Component<'a> {
581 fn as_ref(&self) -> &Path {
582 self.as_os_str().as_ref()
586 /// An iterator over the [`Component`]s of a [`Path`].
588 /// This `struct` is created by the [`components`] method on [`Path`].
589 /// See its documentation for more.
594 /// use std::path::Path;
596 /// let path = Path::new("/tmp/foo/bar.txt");
598 /// for component in path.components() {
599 /// println!("{:?}", component);
603 /// [`Component`]: enum.Component.html
604 /// [`components`]: struct.Path.html#method.components
605 /// [`Path`]: struct.Path.html
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub struct Components<'a> {
609 // The path left to parse components from
612 // The prefix as it was originally parsed, if any
613 prefix: Option<Prefix<'a>>,
615 // true if path *physically* has a root separator; for most Windows
616 // prefixes, it may have a "logical" rootseparator for the purposes of
617 // normalization, e.g. \\server\share == \\server\share\.
618 has_physical_root: bool,
620 // The iterator is double-ended, and these two states keep track of what has
621 // been produced from either end
626 /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
628 /// This `struct` is created by the [`iter`] method on [`Path`].
629 /// See its documentation for more.
631 /// [`Component`]: enum.Component.html
632 /// [`iter`]: struct.Path.html#method.iter
633 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
634 /// [`Path`]: struct.Path.html
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub struct Iter<'a> {
638 inner: Components<'a>,
641 #[stable(feature = "path_components_debug", since = "1.13.0")]
642 impl<'a> fmt::Debug for Components<'a> {
643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
644 struct DebugHelper<'a>(&'a Path);
646 impl<'a> fmt::Debug for DebugHelper<'a> {
647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
649 .entries(self.0.components())
654 f.debug_tuple("Components")
655 .field(&DebugHelper(self.as_path()))
660 impl<'a> Components<'a> {
661 // how long is the prefix, if any?
663 fn prefix_len(&self) -> usize {
664 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
668 fn prefix_verbatim(&self) -> bool {
669 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
672 /// how much of the prefix is left from the point of view of iteration?
674 fn prefix_remaining(&self) -> usize {
675 if self.front == State::Prefix {
682 // Given the iteration so far, how much of the pre-State::Body path is left?
684 fn len_before_body(&self) -> usize {
685 let root = if self.front <= State::StartDir && self.has_physical_root {
690 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
695 self.prefix_remaining() + root + cur_dir
698 // is the iteration complete?
700 fn finished(&self) -> bool {
701 self.front == State::Done || self.back == State::Done || self.front > self.back
705 fn is_sep_byte(&self, b: u8) -> bool {
706 if self.prefix_verbatim() {
713 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
718 /// use std::path::Path;
720 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
721 /// components.next();
722 /// components.next();
724 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn as_path(&self) -> &'a Path {
728 let mut comps = self.clone();
729 if comps.front == State::Body {
732 if comps.back == State::Body {
735 unsafe { Path::from_u8_slice(comps.path) }
738 /// Is the *original* path rooted?
739 fn has_root(&self) -> bool {
740 if self.has_physical_root {
743 if let Some(p) = self.prefix {
744 if p.has_implicit_root() {
751 /// Should the normalized path include a leading . ?
752 fn include_cur_dir(&self) -> bool {
756 let mut iter = self.path[self.prefix_len()..].iter();
757 match (iter.next(), iter.next()) {
758 (Some(&b'.'), None) => true,
759 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
764 // parse a given byte sequence into the corresponding path component
765 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
767 b"." if self.prefix_verbatim() => Some(Component::CurDir),
768 b"." => None, // . components are normalized away, except at
769 // the beginning of a path, which is treated
770 // separately via `include_cur_dir`
771 b".." => Some(Component::ParentDir),
773 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
777 // parse a component from the left, saying how many bytes to consume to
778 // remove the component
779 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
780 debug_assert!(self.front == State::Body);
781 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
782 None => (0, self.path),
783 Some(i) => (1, &self.path[..i]),
785 (comp.len() + extra, self.parse_single_component(comp))
788 // parse a component from the right, saying how many bytes to consume to
789 // remove the component
790 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
791 debug_assert!(self.back == State::Body);
792 let start = self.len_before_body();
793 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
794 None => (0, &self.path[start..]),
795 Some(i) => (1, &self.path[start + i + 1..]),
797 (comp.len() + extra, self.parse_single_component(comp))
800 // trim away repeated separators (i.e. empty components) on the left
801 fn trim_left(&mut self) {
802 while !self.path.is_empty() {
803 let (size, comp) = self.parse_next_component();
807 self.path = &self.path[size..];
812 // trim away repeated separators (i.e. empty components) on the right
813 fn trim_right(&mut self) {
814 while self.path.len() > self.len_before_body() {
815 let (size, comp) = self.parse_next_component_back();
819 self.path = &self.path[..self.path.len() - size];
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<'a> AsRef<Path> for Components<'a> {
827 fn as_ref(&self) -> &Path {
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<'a> AsRef<OsStr> for Components<'a> {
834 fn as_ref(&self) -> &OsStr {
835 self.as_path().as_os_str()
839 #[stable(feature = "path_iter_debug", since = "1.13.0")]
840 impl<'a> fmt::Debug for Iter<'a> {
841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842 struct DebugHelper<'a>(&'a Path);
844 impl<'a> fmt::Debug for DebugHelper<'a> {
845 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847 .entries(self.0.iter())
852 f.debug_tuple("Iter")
853 .field(&DebugHelper(self.as_path()))
859 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
864 /// use std::path::Path;
866 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
870 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn as_path(&self) -> &'a Path {
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<'a> AsRef<Path> for Iter<'a> {
880 fn as_ref(&self) -> &Path {
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a> AsRef<OsStr> for Iter<'a> {
887 fn as_ref(&self) -> &OsStr {
888 self.as_path().as_os_str()
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<'a> Iterator for Iter<'a> {
894 type Item = &'a OsStr;
896 fn next(&mut self) -> Option<&'a OsStr> {
897 self.inner.next().map(Component::as_os_str)
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> DoubleEndedIterator for Iter<'a> {
903 fn next_back(&mut self) -> Option<&'a OsStr> {
904 self.inner.next_back().map(Component::as_os_str)
908 #[unstable(feature = "fused", issue = "35602")]
909 impl<'a> FusedIterator for Iter<'a> {}
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<'a> Iterator for Components<'a> {
913 type Item = Component<'a>;
915 fn next(&mut self) -> Option<Component<'a>> {
916 while !self.finished() {
918 State::Prefix if self.prefix_len() > 0 => {
919 self.front = State::StartDir;
920 debug_assert!(self.prefix_len() <= self.path.len());
921 let raw = &self.path[..self.prefix_len()];
922 self.path = &self.path[self.prefix_len()..];
923 return Some(Component::Prefix(PrefixComponent {
924 raw: unsafe { u8_slice_as_os_str(raw) },
925 parsed: self.prefix.unwrap(),
929 self.front = State::StartDir;
932 self.front = State::Body;
933 if self.has_physical_root {
934 debug_assert!(!self.path.is_empty());
935 self.path = &self.path[1..];
936 return Some(Component::RootDir);
937 } else if let Some(p) = self.prefix {
938 if p.has_implicit_root() && !p.is_verbatim() {
939 return Some(Component::RootDir);
941 } else if self.include_cur_dir() {
942 debug_assert!(!self.path.is_empty());
943 self.path = &self.path[1..];
944 return Some(Component::CurDir);
947 State::Body if !self.path.is_empty() => {
948 let (size, comp) = self.parse_next_component();
949 self.path = &self.path[size..];
955 self.front = State::Done;
957 State::Done => unreachable!(),
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl<'a> DoubleEndedIterator for Components<'a> {
966 fn next_back(&mut self) -> Option<Component<'a>> {
967 while !self.finished() {
969 State::Body if self.path.len() > self.len_before_body() => {
970 let (size, comp) = self.parse_next_component_back();
971 self.path = &self.path[..self.path.len() - size];
977 self.back = State::StartDir;
980 self.back = State::Prefix;
981 if self.has_physical_root {
982 self.path = &self.path[..self.path.len() - 1];
983 return Some(Component::RootDir);
984 } else if let Some(p) = self.prefix {
985 if p.has_implicit_root() && !p.is_verbatim() {
986 return Some(Component::RootDir);
988 } else if self.include_cur_dir() {
989 self.path = &self.path[..self.path.len() - 1];
990 return Some(Component::CurDir);
993 State::Prefix if self.prefix_len() > 0 => {
994 self.back = State::Done;
995 return Some(Component::Prefix(PrefixComponent {
996 raw: unsafe { u8_slice_as_os_str(self.path) },
997 parsed: self.prefix.unwrap(),
1001 self.back = State::Done;
1004 State::Done => unreachable!(),
1011 #[unstable(feature = "fused", issue = "35602")]
1012 impl<'a> FusedIterator for Components<'a> {}
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<'a> cmp::PartialEq for Components<'a> {
1016 fn eq(&self, other: &Components<'a>) -> bool {
1017 Iterator::eq(self.clone(), other.clone())
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl<'a> cmp::Eq for Components<'a> {}
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<'a> cmp::PartialOrd for Components<'a> {
1026 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1027 Iterator::partial_cmp(self.clone(), other.clone())
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl<'a> cmp::Ord for Components<'a> {
1033 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
1034 Iterator::cmp(self.clone(), other.clone())
1038 ////////////////////////////////////////////////////////////////////////////////
1039 // Basic types and traits
1040 ////////////////////////////////////////////////////////////////////////////////
1042 /// An owned, mutable path (akin to [`String`]).
1044 /// This type provides methods like [`push`] and [`set_extension`] that mutate
1045 /// the path in place. It also implements [`Deref`] to [`Path`], meaning that
1046 /// all methods on [`Path`] slices are available on `PathBuf` values as well.
1048 /// [`String`]: ../string/struct.String.html
1049 /// [`Path`]: struct.Path.html
1050 /// [`push`]: struct.PathBuf.html#method.push
1051 /// [`set_extension`]: struct.PathBuf.html#method.set_extension
1052 /// [`Deref`]: ../ops/trait.Deref.html
1054 /// More details about the overall approach can be found in
1055 /// the [module documentation](index.html).
1059 /// You can use [`push`] to build up a `PathBuf` from
1063 /// use std::path::PathBuf;
1065 /// let mut path = PathBuf::new();
1067 /// path.push(r"C:\");
1068 /// path.push("windows");
1069 /// path.push("system32");
1071 /// path.set_extension("dll");
1074 /// However, [`push`] is best used for dynamic situations. This is a better way
1075 /// to do this when you know all of the components ahead of time:
1078 /// use std::path::PathBuf;
1080 /// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1083 /// We can still do better than this! Since these are all strings, we can use
1087 /// use std::path::PathBuf;
1089 /// let path = PathBuf::from(r"C:\windows\system32.dll");
1092 /// Which method works best depends on what kind of situation you're in.
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 pub struct PathBuf {
1100 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1101 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1104 /// Allocates an empty `PathBuf`.
1109 /// use std::path::PathBuf;
1111 /// let path = PathBuf::new();
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub fn new() -> PathBuf {
1115 PathBuf { inner: OsString::new() }
1118 /// Coerces to a [`Path`] slice.
1120 /// [`Path`]: struct.Path.html
1125 /// use std::path::{Path, PathBuf};
1127 /// let p = PathBuf::from("/test");
1128 /// assert_eq!(Path::new("/test"), p.as_path());
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 pub fn as_path(&self) -> &Path {
1135 /// Extends `self` with `path`.
1137 /// If `path` is absolute, it replaces the current path.
1141 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1142 /// replaces everything except for the prefix (if any) of `self`.
1143 /// * if `path` has a prefix but no root, it replaces `self`.
1147 /// Pushing a relative path extends the existing path:
1150 /// use std::path::PathBuf;
1152 /// let mut path = PathBuf::from("/tmp");
1153 /// path.push("file.bk");
1154 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1157 /// Pushing an absolute path replaces the existing path:
1160 /// use std::path::PathBuf;
1162 /// let mut path = PathBuf::from("/tmp");
1163 /// path.push("/etc");
1164 /// assert_eq!(path, PathBuf::from("/etc"));
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1168 self._push(path.as_ref())
1171 fn _push(&mut self, path: &Path) {
1172 // in general, a separator is needed if the rightmost byte is not a separator
1173 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1175 // in the special case of `C:` on Windows, do *not* add a separator
1177 let comps = self.components();
1178 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1179 comps.prefix.unwrap().is_drive() {
1184 // absolute `path` replaces `self`
1185 if path.is_absolute() || path.prefix().is_some() {
1186 self.as_mut_vec().truncate(0);
1188 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1189 } else if path.has_root() {
1190 let prefix_len = self.components().prefix_remaining();
1191 self.as_mut_vec().truncate(prefix_len);
1193 // `path` is a pure relative path
1194 } else if need_sep {
1195 self.inner.push(MAIN_SEP_STR);
1198 self.inner.push(path);
1201 /// Truncates `self` to [`self.parent`].
1203 /// Returns `false` and does nothing if [`self.file_name`] is [`None`].
1204 /// Otherwise, returns `true`.
1206 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1207 /// [`self.parent`]: struct.PathBuf.html#method.parent
1208 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1213 /// use std::path::{Path, PathBuf};
1215 /// let mut p = PathBuf::from("/test/test.rs");
1218 /// assert_eq!(Path::new("/test"), p);
1220 /// assert_eq!(Path::new("/"), p);
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn pop(&mut self) -> bool {
1224 match self.parent().map(|p| p.as_u8_slice().len()) {
1226 self.as_mut_vec().truncate(len);
1233 /// Updates [`self.file_name`] to `file_name`.
1235 /// If [`self.file_name`] was [`None`], this is equivalent to pushing
1238 /// Otherwise it is equivalent to calling [`pop`] and then pushing
1239 /// `file_name`. The new path will be a sibling of the original path.
1240 /// (That is, it will have the same parent.)
1242 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1243 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1244 /// [`pop`]: struct.PathBuf.html#method.pop
1249 /// use std::path::PathBuf;
1251 /// let mut buf = PathBuf::from("/");
1252 /// assert!(buf.file_name() == None);
1253 /// buf.set_file_name("bar");
1254 /// assert!(buf == PathBuf::from("/bar"));
1255 /// assert!(buf.file_name().is_some());
1256 /// buf.set_file_name("baz.txt");
1257 /// assert!(buf == PathBuf::from("/baz.txt"));
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1261 self._set_file_name(file_name.as_ref())
1264 fn _set_file_name(&mut self, file_name: &OsStr) {
1265 if self.file_name().is_some() {
1266 let popped = self.pop();
1267 debug_assert!(popped);
1269 self.push(file_name);
1272 /// Updates [`self.extension`] to `extension`.
1274 /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
1275 /// returns `true` and updates the extension otherwise.
1277 /// If [`self.extension`] is [`None`], the extension is added; otherwise
1280 /// [`self.file_name`]: struct.PathBuf.html#method.file_name
1281 /// [`self.extension`]: struct.PathBuf.html#method.extension
1282 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1287 /// use std::path::{Path, PathBuf};
1289 /// let mut p = PathBuf::from("/feel/the");
1291 /// p.set_extension("force");
1292 /// assert_eq!(Path::new("/feel/the.force"), p.as_path());
1294 /// p.set_extension("dark_side");
1295 /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path());
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1299 self._set_extension(extension.as_ref())
1302 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1303 if self.file_name().is_none() {
1307 let mut stem = match self.file_stem() {
1308 Some(stem) => stem.to_os_string(),
1309 None => OsString::new(),
1312 if !os_str_as_u8_slice(extension).is_empty() {
1314 stem.push(extension);
1316 self.set_file_name(&stem);
1321 /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage.
1323 /// [`OsString`]: ../ffi/struct.OsString.html
1328 /// use std::path::PathBuf;
1330 /// let p = PathBuf::from("/the/head");
1331 /// let os_str = p.into_os_string();
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 pub fn into_os_string(self) -> OsString {
1338 /// Converts this `PathBuf` into a [boxed][`Box`] [`Path`].
1340 /// [`Box`]: ../../std/boxed/struct.Box.html
1341 /// [`Path`]: struct.Path.html
1342 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1343 pub fn into_boxed_path(self) -> Box<Path> {
1344 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1345 unsafe { Box::from_raw(rw) }
1349 #[stable(feature = "box_from_path", since = "1.17.0")]
1350 impl<'a> From<&'a Path> for Box<Path> {
1351 fn from(path: &'a Path) -> Box<Path> {
1352 let boxed: Box<OsStr> = path.inner.into();
1353 let rw = Box::into_raw(boxed) as *mut Path;
1354 unsafe { Box::from_raw(rw) }
1358 #[stable(feature = "path_buf_from_box", since = "1.18.0")]
1359 impl From<Box<Path>> for PathBuf {
1360 fn from(boxed: Box<Path>) -> PathBuf {
1361 boxed.into_path_buf()
1365 #[stable(feature = "box_from_path_buf", since = "1.20.0")]
1366 impl From<PathBuf> for Box<Path> {
1367 fn from(p: PathBuf) -> Box<Path> {
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1374 fn from(s: &'a T) -> PathBuf {
1375 PathBuf::from(s.as_ref().to_os_string())
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl From<OsString> for PathBuf {
1381 fn from(s: OsString) -> PathBuf {
1382 PathBuf { inner: s }
1386 #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
1387 impl From<PathBuf> for OsString {
1388 fn from(path_buf : PathBuf) -> OsString {
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl From<String> for PathBuf {
1395 fn from(s: String) -> PathBuf {
1396 PathBuf::from(OsString::from(s))
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1402 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1403 let mut buf = PathBuf::new();
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1411 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1413 self.push(p.as_ref())
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 impl fmt::Debug for PathBuf {
1420 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1421 fmt::Debug::fmt(&**self, formatter)
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl ops::Deref for PathBuf {
1429 fn deref(&self) -> &Path {
1430 Path::new(&self.inner)
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl Borrow<Path> for PathBuf {
1436 fn borrow(&self) -> &Path {
1441 #[stable(feature = "default_for_pathbuf", since = "1.17.0")]
1442 impl Default for PathBuf {
1443 fn default() -> Self {
1448 #[stable(feature = "cow_from_path", since = "1.6.0")]
1449 impl<'a> From<&'a Path> for Cow<'a, Path> {
1451 fn from(s: &'a Path) -> Cow<'a, Path> {
1456 #[stable(feature = "cow_from_path", since = "1.6.0")]
1457 impl<'a> From<PathBuf> for Cow<'a, Path> {
1459 fn from(s: PathBuf) -> Cow<'a, Path> {
1464 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1465 impl From<PathBuf> for Arc<Path> {
1467 fn from(s: PathBuf) -> Arc<Path> {
1468 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
1469 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1473 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1474 impl<'a> From<&'a Path> for Arc<Path> {
1476 fn from(s: &Path) -> Arc<Path> {
1477 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
1478 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
1482 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1483 impl From<PathBuf> for Rc<Path> {
1485 fn from(s: PathBuf) -> Rc<Path> {
1486 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
1487 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1491 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1492 impl<'a> From<&'a Path> for Rc<Path> {
1494 fn from(s: &Path) -> Rc<Path> {
1495 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
1496 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 impl ToOwned for Path {
1502 type Owned = PathBuf;
1503 fn to_owned(&self) -> PathBuf {
1506 fn clone_into(&self, target: &mut PathBuf) {
1507 self.inner.clone_into(&mut target.inner);
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 impl cmp::PartialEq for PathBuf {
1513 fn eq(&self, other: &PathBuf) -> bool {
1514 self.components() == other.components()
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 impl Hash for PathBuf {
1520 fn hash<H: Hasher>(&self, h: &mut H) {
1521 self.as_path().hash(h)
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 impl cmp::Eq for PathBuf {}
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 impl cmp::PartialOrd for PathBuf {
1530 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1531 self.components().partial_cmp(other.components())
1535 #[stable(feature = "rust1", since = "1.0.0")]
1536 impl cmp::Ord for PathBuf {
1537 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1538 self.components().cmp(other.components())
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl AsRef<OsStr> for PathBuf {
1544 fn as_ref(&self) -> &OsStr {
1549 /// A slice of a path (akin to [`str`]).
1551 /// This type supports a number of operations for inspecting a path, including
1552 /// breaking the path into its components (separated by `/` on Unix and by either
1553 /// `/` or `\` on Windows), extracting the file name, determining whether the path
1554 /// is absolute, and so on.
1556 /// This is an *unsized* type, meaning that it must always be used behind a
1557 /// pointer like `&` or [`Box`]. For an owned version of this type,
1558 /// see [`PathBuf`].
1560 /// [`str`]: ../primitive.str.html
1561 /// [`Box`]: ../boxed/struct.Box.html
1562 /// [`PathBuf`]: struct.PathBuf.html
1564 /// More details about the overall approach can be found in
1565 /// the [module documentation](index.html).
1570 /// use std::path::Path;
1571 /// use std::ffi::OsStr;
1573 /// // Note: this example does work on Windows
1574 /// let path = Path::new("./foo/bar.txt");
1576 /// let parent = path.parent();
1577 /// assert_eq!(parent, Some(Path::new("./foo")));
1579 /// let file_stem = path.file_stem();
1580 /// assert_eq!(file_stem, Some(OsStr::new("bar")));
1582 /// let extension = path.extension();
1583 /// assert_eq!(extension, Some(OsStr::new("txt")));
1585 #[stable(feature = "rust1", since = "1.0.0")]
1590 /// An error returned from [`Path::strip_prefix`][`strip_prefix`] if the prefix
1593 /// This `struct` is created by the [`strip_prefix`] method on [`Path`].
1594 /// See its documentation for more.
1596 /// [`strip_prefix`]: struct.Path.html#method.strip_prefix
1597 /// [`Path`]: struct.Path.html
1598 #[derive(Debug, Clone, PartialEq, Eq)]
1599 #[stable(since = "1.7.0", feature = "strip_prefix")]
1600 pub struct StripPrefixError(());
1603 // The following (private!) function allows construction of a path from a u8
1604 // slice, which is only safe when it is known to follow the OsStr encoding.
1605 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1606 Path::new(u8_slice_as_os_str(s))
1608 // The following (private!) function reveals the byte encoding used for OsStr.
1609 fn as_u8_slice(&self) -> &[u8] {
1610 os_str_as_u8_slice(&self.inner)
1613 /// Directly wraps a string slice as a `Path` slice.
1615 /// This is a cost-free conversion.
1620 /// use std::path::Path;
1622 /// Path::new("foo.txt");
1625 /// You can create `Path`s from `String`s, or even other `Path`s:
1628 /// use std::path::Path;
1630 /// let string = String::from("foo.txt");
1631 /// let from_string = Path::new(&string);
1632 /// let from_path = Path::new(&from_string);
1633 /// assert_eq!(from_string, from_path);
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1637 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
1640 /// Yields the underlying [`OsStr`] slice.
1642 /// [`OsStr`]: ../ffi/struct.OsStr.html
1647 /// use std::path::Path;
1649 /// let os_str = Path::new("foo.txt").as_os_str();
1650 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 pub fn as_os_str(&self) -> &OsStr {
1657 /// Yields a [`&str`] slice if the `Path` is valid unicode.
1659 /// This conversion may entail doing a check for UTF-8 validity.
1661 /// [`&str`]: ../primitive.str.html
1666 /// use std::path::Path;
1668 /// let path = Path::new("foo.txt");
1669 /// assert_eq!(path.to_str(), Some("foo.txt"));
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 pub fn to_str(&self) -> Option<&str> {
1676 /// Converts a `Path` to a [`Cow<str>`].
1678 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1680 /// [`Cow<str>`]: ../borrow/enum.Cow.html
1684 /// Calling `to_string_lossy` on a `Path` with valid unicode:
1687 /// use std::path::Path;
1689 /// let path = Path::new("foo.txt");
1690 /// assert_eq!(path.to_string_lossy(), "foo.txt");
1693 /// Had `path` contained invalid unicode, the `to_string_lossy` call might
1694 /// have returned `"fo�.txt"`.
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 pub fn to_string_lossy(&self) -> Cow<str> {
1697 self.inner.to_string_lossy()
1700 /// Converts a `Path` to an owned [`PathBuf`].
1702 /// [`PathBuf`]: struct.PathBuf.html
1707 /// use std::path::Path;
1709 /// let path_buf = Path::new("foo.txt").to_path_buf();
1710 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1712 #[rustc_conversion_suggestion]
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub fn to_path_buf(&self) -> PathBuf {
1715 PathBuf::from(self.inner.to_os_string())
1718 /// Returns `true` if the `Path` is absolute, i.e. if it is independent of
1719 /// the current directory.
1721 /// * On Unix, a path is absolute if it starts with the root, so
1722 /// `is_absolute` and [`has_root`] are equivalent.
1724 /// * On Windows, a path is absolute if it has a prefix and starts with the
1725 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not.
1730 /// use std::path::Path;
1732 /// assert!(!Path::new("foo.txt").is_absolute());
1735 /// [`has_root`]: #method.has_root
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 #[allow(deprecated)]
1738 pub fn is_absolute(&self) -> bool {
1739 if cfg!(target_os = "redox") {
1740 // FIXME: Allow Redox prefixes
1741 self.has_root() || has_redox_scheme(self.as_u8_slice())
1743 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1747 /// Returns `true` if the `Path` is relative, i.e. not absolute.
1749 /// See [`is_absolute`]'s documentation for more details.
1754 /// use std::path::Path;
1756 /// assert!(Path::new("foo.txt").is_relative());
1759 /// [`is_absolute`]: #method.is_absolute
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 pub fn is_relative(&self) -> bool {
1765 fn prefix(&self) -> Option<Prefix> {
1766 self.components().prefix
1769 /// Returns `true` if the `Path` has a root.
1771 /// * On Unix, a path has a root if it begins with `/`.
1773 /// * On Windows, a path has a root if it:
1774 /// * has no prefix and begins with a separator, e.g. `\\windows`
1775 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1776 /// * has any non-disk prefix, e.g. `\\server\share`
1781 /// use std::path::Path;
1783 /// assert!(Path::new("/etc/passwd").has_root());
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 pub fn has_root(&self) -> bool {
1787 self.components().has_root()
1790 /// Returns the `Path` without its final component, if there is one.
1792 /// Returns [`None`] if the path terminates in a root or prefix.
1794 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1799 /// use std::path::Path;
1801 /// let path = Path::new("/foo/bar");
1802 /// let parent = path.parent().unwrap();
1803 /// assert_eq!(parent, Path::new("/foo"));
1805 /// let grand_parent = parent.parent().unwrap();
1806 /// assert_eq!(grand_parent, Path::new("/"));
1807 /// assert_eq!(grand_parent.parent(), None);
1809 #[stable(feature = "rust1", since = "1.0.0")]
1810 pub fn parent(&self) -> Option<&Path> {
1811 let mut comps = self.components();
1812 let comp = comps.next_back();
1815 Component::Normal(_) |
1817 Component::ParentDir => Some(comps.as_path()),
1823 /// Returns the final component of the `Path`, if there is one.
1825 /// If the path is a normal file, this is the file name. If it's the path of a directory, this
1826 /// is the directory name.
1828 /// Returns [`None`] If the path terminates in `..`.
1830 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1835 /// use std::path::Path;
1836 /// use std::ffi::OsStr;
1838 /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
1839 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
1840 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
1841 /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
1842 /// assert_eq!(None, Path::new("foo.txt/..").file_name());
1843 /// assert_eq!(None, Path::new("/").file_name());
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 pub fn file_name(&self) -> Option<&OsStr> {
1847 self.components().next_back().and_then(|p| {
1849 Component::Normal(p) => Some(p.as_ref()),
1855 /// Returns a path that, when joined onto `base`, yields `self`.
1859 /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
1860 /// returns `false`), returns [`Err`].
1862 /// [`starts_with`]: #method.starts_with
1863 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1868 /// use std::path::Path;
1870 /// let path = Path::new("/test/haha/foo.txt");
1872 /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
1873 /// assert_eq!(path.strip_prefix("test").is_ok(), false);
1874 /// assert_eq!(path.strip_prefix("/haha").is_ok(), false);
1876 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1877 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1878 -> Result<&'a Path, StripPrefixError>
1879 where P: AsRef<Path>
1881 self._strip_prefix(base.as_ref())
1884 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1885 -> Result<&'a Path, StripPrefixError> {
1886 iter_after(self.components(), base.components())
1887 .map(|c| c.as_path())
1888 .ok_or(StripPrefixError(()))
1891 /// Determines whether `base` is a prefix of `self`.
1893 /// Only considers whole path components to match.
1898 /// use std::path::Path;
1900 /// let path = Path::new("/etc/passwd");
1902 /// assert!(path.starts_with("/etc"));
1904 /// assert!(!path.starts_with("/e"));
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1908 self._starts_with(base.as_ref())
1911 fn _starts_with(&self, base: &Path) -> bool {
1912 iter_after(self.components(), base.components()).is_some()
1915 /// Determines whether `child` is a suffix of `self`.
1917 /// Only considers whole path components to match.
1922 /// use std::path::Path;
1924 /// let path = Path::new("/etc/passwd");
1926 /// assert!(path.ends_with("passwd"));
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1930 self._ends_with(child.as_ref())
1933 fn _ends_with(&self, child: &Path) -> bool {
1934 iter_after(self.components().rev(), child.components().rev()).is_some()
1937 /// Extracts the stem (non-extension) portion of [`self.file_name`].
1939 /// [`self.file_name`]: struct.Path.html#method.file_name
1943 /// * [`None`], if there is no file name;
1944 /// * The entire file name if there is no embedded `.`;
1945 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1946 /// * Otherwise, the portion of the file name before the final `.`
1948 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1953 /// use std::path::Path;
1955 /// let path = Path::new("foo.rs");
1957 /// assert_eq!("foo", path.file_stem().unwrap());
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 pub fn file_stem(&self) -> Option<&OsStr> {
1961 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1964 /// Extracts the extension of [`self.file_name`], if possible.
1966 /// The extension is:
1968 /// * [`None`], if there is no file name;
1969 /// * [`None`], if there is no embedded `.`;
1970 /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1971 /// * Otherwise, the portion of the file name after the final `.`
1973 /// [`self.file_name`]: struct.Path.html#method.file_name
1974 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1979 /// use std::path::Path;
1981 /// let path = Path::new("foo.rs");
1983 /// assert_eq!("rs", path.extension().unwrap());
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 pub fn extension(&self) -> Option<&OsStr> {
1987 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1990 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1992 /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1994 /// [`PathBuf`]: struct.PathBuf.html
1995 /// [`PathBuf::push`]: struct.PathBuf.html#method.push
2000 /// use std::path::{Path, PathBuf};
2002 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
2006 self._join(path.as_ref())
2009 fn _join(&self, path: &Path) -> PathBuf {
2010 let mut buf = self.to_path_buf();
2015 /// Creates an owned [`PathBuf`] like `self` but with the given file name.
2017 /// See [`PathBuf::set_file_name`] for more details.
2019 /// [`PathBuf`]: struct.PathBuf.html
2020 /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name
2025 /// use std::path::{Path, PathBuf};
2027 /// let path = Path::new("/tmp/foo.txt");
2028 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
2030 /// let path = Path::new("/tmp");
2031 /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
2033 #[stable(feature = "rust1", since = "1.0.0")]
2034 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
2035 self._with_file_name(file_name.as_ref())
2038 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
2039 let mut buf = self.to_path_buf();
2040 buf.set_file_name(file_name);
2044 /// Creates an owned [`PathBuf`] like `self` but with the given extension.
2046 /// See [`PathBuf::set_extension`] for more details.
2048 /// [`PathBuf`]: struct.PathBuf.html
2049 /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension
2054 /// use std::path::{Path, PathBuf};
2056 /// let path = Path::new("foo.rs");
2057 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
2061 self._with_extension(extension.as_ref())
2064 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
2065 let mut buf = self.to_path_buf();
2066 buf.set_extension(extension);
2070 /// Produces an iterator over the [`Component`]s of the path.
2072 /// When parsing the path, there is a small amount of normalization:
2074 /// * Repeated separators are ignored, so `a/b` and `a//b` both have
2075 /// `a` and `b` as components.
2077 /// * Occurrences of `.` are normalized away, except if they are at the
2078 /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
2079 /// `a/b` all have `a` and `b` as components, but `./a/b` starts with
2080 /// an additional [`CurDir`] component.
2082 /// Note that no other normalization takes place; in particular, `a/c`
2083 /// and `a/b/../c` are distinct, to account for the possibility that `b`
2084 /// is a symbolic link (so its parent isn't `a`).
2089 /// use std::path::{Path, Component};
2090 /// use std::ffi::OsStr;
2092 /// let mut components = Path::new("/tmp/foo.txt").components();
2094 /// assert_eq!(components.next(), Some(Component::RootDir));
2095 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
2096 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
2097 /// assert_eq!(components.next(), None)
2100 /// [`Component`]: enum.Component.html
2101 /// [`CurDir`]: enum.Component.html#variant.CurDir
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 pub fn components(&self) -> Components {
2104 let prefix = parse_prefix(self.as_os_str());
2106 path: self.as_u8_slice(),
2108 has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
2109 has_redox_scheme(self.as_u8_slice()),
2110 front: State::Prefix,
2115 /// Produces an iterator over the path's components viewed as [`OsStr`]
2118 /// For more information about the particulars of how the path is separated
2119 /// into components, see [`components`].
2121 /// [`components`]: #method.components
2122 /// [`OsStr`]: ../ffi/struct.OsStr.html
2127 /// use std::path::{self, Path};
2128 /// use std::ffi::OsStr;
2130 /// let mut it = Path::new("/tmp/foo.txt").iter();
2131 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
2132 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
2133 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
2134 /// assert_eq!(it.next(), None)
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 pub fn iter(&self) -> Iter {
2138 Iter { inner: self.components() }
2141 /// Returns an object that implements [`Display`] for safely printing paths
2142 /// that may contain non-Unicode data.
2144 /// [`Display`]: ../fmt/trait.Display.html
2149 /// use std::path::Path;
2151 /// let path = Path::new("/tmp/foo.rs");
2153 /// println!("{}", path.display());
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 pub fn display(&self) -> Display {
2157 Display { path: self }
2160 /// Queries the file system to get information about a file, directory, etc.
2162 /// This function will traverse symbolic links to query information about the
2163 /// destination file.
2165 /// This is an alias to [`fs::metadata`].
2167 /// [`fs::metadata`]: ../fs/fn.metadata.html
2172 /// use std::path::Path;
2174 /// let path = Path::new("/Minas/tirith");
2175 /// let metadata = path.metadata().expect("metadata call failed");
2176 /// println!("{:?}", metadata.file_type());
2178 #[stable(feature = "path_ext", since = "1.5.0")]
2179 pub fn metadata(&self) -> io::Result<fs::Metadata> {
2183 /// Queries the metadata about a file without following symlinks.
2185 /// This is an alias to [`fs::symlink_metadata`].
2187 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
2192 /// use std::path::Path;
2194 /// let path = Path::new("/Minas/tirith");
2195 /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
2196 /// println!("{:?}", metadata.file_type());
2198 #[stable(feature = "path_ext", since = "1.5.0")]
2199 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
2200 fs::symlink_metadata(self)
2203 /// Returns the canonical form of the path with all intermediate components
2204 /// normalized and symbolic links resolved.
2206 /// This is an alias to [`fs::canonicalize`].
2208 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
2213 /// use std::path::{Path, PathBuf};
2215 /// let path = Path::new("/foo/test/../test/bar.rs");
2216 /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
2218 #[stable(feature = "path_ext", since = "1.5.0")]
2219 pub fn canonicalize(&self) -> io::Result<PathBuf> {
2220 fs::canonicalize(self)
2223 /// Reads a symbolic link, returning the file that the link points to.
2225 /// This is an alias to [`fs::read_link`].
2227 /// [`fs::read_link`]: ../fs/fn.read_link.html
2232 /// use std::path::Path;
2234 /// let path = Path::new("/laputa/sky_castle.rs");
2235 /// let path_link = path.read_link().expect("read_link call failed");
2237 #[stable(feature = "path_ext", since = "1.5.0")]
2238 pub fn read_link(&self) -> io::Result<PathBuf> {
2242 /// Returns an iterator over the entries within a directory.
2244 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New
2245 /// errors may be encountered after an iterator is initially constructed.
2247 /// This is an alias to [`fs::read_dir`].
2249 /// [`io::Result`]: ../io/type.Result.html
2250 /// [`DirEntry`]: ../fs/struct.DirEntry.html
2251 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
2256 /// use std::path::Path;
2258 /// let path = Path::new("/laputa");
2259 /// for entry in path.read_dir().expect("read_dir call failed") {
2260 /// if let Ok(entry) = entry {
2261 /// println!("{:?}", entry.path());
2265 #[stable(feature = "path_ext", since = "1.5.0")]
2266 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
2270 /// Returns whether the path points at an existing entity.
2272 /// This function will traverse symbolic links to query information about the
2273 /// destination file. In case of broken symbolic links this will return `false`.
2275 /// If you cannot access the directory containing the file, e.g. because of a
2276 /// permission error, this will return `false`.
2281 /// use std::path::Path;
2282 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
2287 /// This is a convenience function that coerces errors to false. If you want to
2288 /// check errors, call [fs::metadata].
2290 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2291 #[stable(feature = "path_ext", since = "1.5.0")]
2292 pub fn exists(&self) -> bool {
2293 fs::metadata(self).is_ok()
2296 /// Returns whether the path exists on disk and is pointing at a regular file.
2298 /// This function will traverse symbolic links to query information about the
2299 /// destination file. In case of broken symbolic links this will return `false`.
2301 /// If you cannot access the directory containing the file, e.g. because of a
2302 /// permission error, this will return `false`.
2307 /// use std::path::Path;
2308 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
2309 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
2314 /// This is a convenience function that coerces errors to false. If you want to
2315 /// check errors, call [fs::metadata] and handle its Result. Then call
2316 /// [fs::Metadata::is_file] if it was Ok.
2318 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2319 /// [fs::Metadata::is_file]: ../../std/fs/struct.Metadata.html#method.is_file
2320 #[stable(feature = "path_ext", since = "1.5.0")]
2321 pub fn is_file(&self) -> bool {
2322 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
2325 /// Returns whether the path exists on disk and is pointing at a directory.
2327 /// This function will traverse symbolic links to query information about the
2328 /// destination file. In case of broken symbolic links this will return `false`.
2330 /// If you cannot access the directory containing the file, e.g. because of a
2331 /// permission error, this will return `false`.
2336 /// use std::path::Path;
2337 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
2338 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
2343 /// This is a convenience function that coerces errors to false. If you want to
2344 /// check errors, call [fs::metadata] and handle its Result. Then call
2345 /// [fs::Metadata::is_dir] if it was Ok.
2347 /// [fs::metadata]: ../../std/fs/fn.metadata.html
2348 /// [fs::Metadata::is_dir]: ../../std/fs/struct.Metadata.html#method.is_dir
2349 #[stable(feature = "path_ext", since = "1.5.0")]
2350 pub fn is_dir(&self) -> bool {
2351 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
2354 /// Converts a [`Box<Path>`][`Box`] into a [`PathBuf`] without copying or
2357 /// [`Box`]: ../../std/boxed/struct.Box.html
2358 /// [`PathBuf`]: struct.PathBuf.html
2359 #[stable(feature = "into_boxed_path", since = "1.20.0")]
2360 pub fn into_path_buf(self: Box<Path>) -> PathBuf {
2361 let rw = Box::into_raw(self) as *mut OsStr;
2362 let inner = unsafe { Box::from_raw(rw) };
2363 PathBuf { inner: OsString::from(inner) }
2367 #[stable(feature = "rust1", since = "1.0.0")]
2368 impl AsRef<OsStr> for Path {
2369 fn as_ref(&self) -> &OsStr {
2374 #[stable(feature = "rust1", since = "1.0.0")]
2375 impl fmt::Debug for Path {
2376 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2377 fmt::Debug::fmt(&self.inner, formatter)
2381 /// Helper struct for safely printing paths with [`format!`] and `{}`.
2383 /// A [`Path`] might contain non-Unicode data. This `struct` implements the
2384 /// [`Display`] trait in a way that mitigates that. It is created by the
2385 /// [`display`][`Path::display`] method on [`Path`].
2390 /// use std::path::Path;
2392 /// let path = Path::new("/tmp/foo.rs");
2394 /// println!("{}", path.display());
2397 /// [`Display`]: ../../std/fmt/trait.Display.html
2398 /// [`format!`]: ../../std/macro.format.html
2399 /// [`Path`]: struct.Path.html
2400 /// [`Path::display`]: struct.Path.html#method.display
2401 #[stable(feature = "rust1", since = "1.0.0")]
2402 pub struct Display<'a> {
2406 #[stable(feature = "rust1", since = "1.0.0")]
2407 impl<'a> fmt::Debug for Display<'a> {
2408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2409 fmt::Debug::fmt(&self.path, f)
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl<'a> fmt::Display for Display<'a> {
2415 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2416 self.path.inner.display(f)
2420 #[stable(feature = "rust1", since = "1.0.0")]
2421 impl cmp::PartialEq for Path {
2422 fn eq(&self, other: &Path) -> bool {
2423 self.components().eq(other.components())
2427 #[stable(feature = "rust1", since = "1.0.0")]
2428 impl Hash for Path {
2429 fn hash<H: Hasher>(&self, h: &mut H) {
2430 for component in self.components() {
2436 #[stable(feature = "rust1", since = "1.0.0")]
2437 impl cmp::Eq for Path {}
2439 #[stable(feature = "rust1", since = "1.0.0")]
2440 impl cmp::PartialOrd for Path {
2441 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
2442 self.components().partial_cmp(other.components())
2446 #[stable(feature = "rust1", since = "1.0.0")]
2447 impl cmp::Ord for Path {
2448 fn cmp(&self, other: &Path) -> cmp::Ordering {
2449 self.components().cmp(other.components())
2453 #[stable(feature = "rust1", since = "1.0.0")]
2454 impl AsRef<Path> for Path {
2455 fn as_ref(&self) -> &Path {
2460 #[stable(feature = "rust1", since = "1.0.0")]
2461 impl AsRef<Path> for OsStr {
2462 fn as_ref(&self) -> &Path {
2467 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2468 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2469 fn as_ref(&self) -> &Path {
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl AsRef<Path> for OsString {
2476 fn as_ref(&self) -> &Path {
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 impl AsRef<Path> for str {
2483 fn as_ref(&self) -> &Path {
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 impl AsRef<Path> for String {
2490 fn as_ref(&self) -> &Path {
2495 #[stable(feature = "rust1", since = "1.0.0")]
2496 impl AsRef<Path> for PathBuf {
2497 fn as_ref(&self) -> &Path {
2502 #[stable(feature = "path_into_iter", since = "1.6.0")]
2503 impl<'a> IntoIterator for &'a PathBuf {
2504 type Item = &'a OsStr;
2505 type IntoIter = Iter<'a>;
2506 fn into_iter(self) -> Iter<'a> { self.iter() }
2509 #[stable(feature = "path_into_iter", since = "1.6.0")]
2510 impl<'a> IntoIterator for &'a Path {
2511 type Item = &'a OsStr;
2512 type IntoIter = Iter<'a>;
2513 fn into_iter(self) -> Iter<'a> { self.iter() }
2516 macro_rules! impl_cmp {
2517 ($lhs:ty, $rhs: ty) => {
2518 #[stable(feature = "partialeq_path", since = "1.6.0")]
2519 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2521 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2524 #[stable(feature = "partialeq_path", since = "1.6.0")]
2525 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2527 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2530 #[stable(feature = "cmp_path", since = "1.8.0")]
2531 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2533 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2534 <Path as PartialOrd>::partial_cmp(self, other)
2538 #[stable(feature = "cmp_path", since = "1.8.0")]
2539 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2541 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2542 <Path as PartialOrd>::partial_cmp(self, other)
2548 impl_cmp!(PathBuf, Path);
2549 impl_cmp!(PathBuf, &'a Path);
2550 impl_cmp!(Cow<'a, Path>, Path);
2551 impl_cmp!(Cow<'a, Path>, &'b Path);
2552 impl_cmp!(Cow<'a, Path>, PathBuf);
2554 macro_rules! impl_cmp_os_str {
2555 ($lhs:ty, $rhs: ty) => {
2556 #[stable(feature = "cmp_path", since = "1.8.0")]
2557 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2559 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2562 #[stable(feature = "cmp_path", since = "1.8.0")]
2563 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2565 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2568 #[stable(feature = "cmp_path", since = "1.8.0")]
2569 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2571 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2572 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2576 #[stable(feature = "cmp_path", since = "1.8.0")]
2577 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2579 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2580 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2586 impl_cmp_os_str!(PathBuf, OsStr);
2587 impl_cmp_os_str!(PathBuf, &'a OsStr);
2588 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2589 impl_cmp_os_str!(PathBuf, OsString);
2590 impl_cmp_os_str!(Path, OsStr);
2591 impl_cmp_os_str!(Path, &'a OsStr);
2592 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2593 impl_cmp_os_str!(Path, OsString);
2594 impl_cmp_os_str!(&'a Path, OsStr);
2595 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2596 impl_cmp_os_str!(&'a Path, OsString);
2597 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2598 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2599 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2601 #[stable(since = "1.7.0", feature = "strip_prefix")]
2602 impl fmt::Display for StripPrefixError {
2603 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2604 self.description().fmt(f)
2608 #[stable(since = "1.7.0", feature = "strip_prefix")]
2609 impl Error for StripPrefixError {
2610 fn description(&self) -> &str { "prefix not found" }
2621 ($path:expr, iter: $iter:expr) => (
2623 let path = Path::new($path);
2625 // Forward iteration
2626 let comps = path.iter()
2627 .map(|p| p.to_string_lossy().into_owned())
2628 .collect::<Vec<String>>();
2629 let exp: &[&str] = &$iter;
2630 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2631 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2634 // Reverse iteration
2635 let comps = Path::new($path).iter().rev()
2636 .map(|p| p.to_string_lossy().into_owned())
2637 .collect::<Vec<String>>();
2638 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2639 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2644 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2646 let path = Path::new($path);
2648 let act_root = path.has_root();
2649 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2650 $has_root, act_root);
2652 let act_abs = path.is_absolute();
2653 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2654 $is_absolute, act_abs);
2658 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2660 let path = Path::new($path);
2662 let parent = path.parent().map(|p| p.to_str().unwrap());
2663 let exp_parent: Option<&str> = $parent;
2664 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2665 exp_parent, parent);
2667 let file = path.file_name().map(|p| p.to_str().unwrap());
2668 let exp_file: Option<&str> = $file;
2669 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2674 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2676 let path = Path::new($path);
2678 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2679 let exp_stem: Option<&str> = $file_stem;
2680 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2683 let ext = path.extension().map(|p| p.to_str().unwrap());
2684 let exp_ext: Option<&str> = $extension;
2685 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2690 ($path:expr, iter: $iter:expr,
2691 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2692 parent: $parent:expr, file_name: $file:expr,
2693 file_stem: $file_stem:expr, extension: $extension:expr) => (
2695 t!($path, iter: $iter);
2696 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2697 t!($path, parent: $parent, file_name: $file);
2698 t!($path, file_stem: $file_stem, extension: $extension);
2707 let static_path = Path::new("/home/foo");
2708 let static_cow_path: Cow<'static, Path> = static_path.into();
2709 let pathbuf = PathBuf::from("/home/foo");
2712 let path: &Path = &pathbuf;
2713 let borrowed_cow_path: Cow<Path> = path.into();
2715 assert_eq!(static_cow_path, borrowed_cow_path);
2718 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2720 assert_eq!(static_cow_path, owned_cow_path);
2725 pub fn test_decompositions_unix() {
2741 file_name: Some("foo"),
2742 file_stem: Some("foo"),
2761 file_name: Some("foo"),
2762 file_stem: Some("foo"),
2771 file_name: Some("foo"),
2772 file_stem: Some("foo"),
2781 file_name: Some("foo"),
2782 file_stem: Some("foo"),
2787 iter: ["foo", "bar"],
2790 parent: Some("foo"),
2791 file_name: Some("bar"),
2792 file_stem: Some("bar"),
2797 iter: ["/", "foo", "bar"],
2800 parent: Some("/foo"),
2801 file_name: Some("bar"),
2802 file_stem: Some("bar"),
2811 file_name: Some("foo"),
2812 file_stem: Some("foo"),
2817 iter: ["/", "foo", "bar"],
2820 parent: Some("///foo"),
2821 file_name: Some("bar"),
2822 file_stem: Some("bar"),
2861 file_name: Some("foo"),
2862 file_stem: Some("foo"),
2867 iter: ["foo", ".."],
2870 parent: Some("foo"),
2881 file_name: Some("foo"),
2882 file_stem: Some("foo"),
2887 iter: ["foo", "bar"],
2890 parent: Some("foo"),
2891 file_name: Some("bar"),
2892 file_stem: Some("bar"),
2897 iter: ["foo", ".."],
2900 parent: Some("foo"),
2907 iter: ["foo", "..", "bar"],
2910 parent: Some("foo/.."),
2911 file_name: Some("bar"),
2912 file_stem: Some("bar"),
2921 file_name: Some("a"),
2922 file_stem: Some("a"),
2951 file_name: Some("b"),
2952 file_stem: Some("b"),
2961 file_name: Some("b"),
2962 file_stem: Some("b"),
2971 file_name: Some("b"),
2972 file_stem: Some("b"),
2977 iter: ["a", "b", "c"],
2980 parent: Some("a/b"),
2981 file_name: Some("c"),
2982 file_stem: Some("c"),
2991 file_name: Some(".foo"),
2992 file_stem: Some(".foo"),
2999 pub fn test_decompositions_windows() {
3015 file_name: Some("foo"),
3016 file_stem: Some("foo"),
3071 iter: ["\\", "foo"],
3075 file_name: Some("foo"),
3076 file_stem: Some("foo"),
3085 file_name: Some("foo"),
3086 file_stem: Some("foo"),
3091 iter: ["\\", "foo"],
3095 file_name: Some("foo"),
3096 file_stem: Some("foo"),
3101 iter: ["foo", "bar"],
3104 parent: Some("foo"),
3105 file_name: Some("bar"),
3106 file_stem: Some("bar"),
3111 iter: ["\\", "foo", "bar"],
3114 parent: Some("/foo"),
3115 file_name: Some("bar"),
3116 file_stem: Some("bar"),
3121 iter: ["\\", "foo"],
3125 file_name: Some("foo"),
3126 file_stem: Some("foo"),
3131 iter: ["\\", "foo", "bar"],
3134 parent: Some("///foo"),
3135 file_name: Some("bar"),
3136 file_stem: Some("bar"),
3175 file_name: Some("foo"),
3176 file_stem: Some("foo"),
3181 iter: ["foo", ".."],
3184 parent: Some("foo"),
3195 file_name: Some("foo"),
3196 file_stem: Some("foo"),
3201 iter: ["foo", "bar"],
3204 parent: Some("foo"),
3205 file_name: Some("bar"),
3206 file_stem: Some("bar"),
3211 iter: ["foo", ".."],
3214 parent: Some("foo"),
3221 iter: ["foo", "..", "bar"],
3224 parent: Some("foo/.."),
3225 file_name: Some("bar"),
3226 file_stem: Some("bar"),
3235 file_name: Some("a"),
3236 file_stem: Some("a"),
3265 file_name: Some("b"),
3266 file_stem: Some("b"),
3275 file_name: Some("b"),
3276 file_stem: Some("b"),
3285 file_name: Some("b"),
3286 file_stem: Some("b"),
3291 iter: ["a", "b", "c"],
3294 parent: Some("a/b"),
3295 file_name: Some("c"),
3296 file_stem: Some("c"),
3300 iter: ["a", "b", "c"],
3303 parent: Some("a\\b"),
3304 file_name: Some("c"),
3305 file_stem: Some("c"),
3314 file_name: Some("a"),
3315 file_stem: Some("a"),
3320 iter: ["c:", "\\", "foo.txt"],
3323 parent: Some("c:\\"),
3324 file_name: Some("foo.txt"),
3325 file_stem: Some("foo"),
3326 extension: Some("txt")
3329 t!("\\\\server\\share\\foo.txt",
3330 iter: ["\\\\server\\share", "\\", "foo.txt"],
3333 parent: Some("\\\\server\\share\\"),
3334 file_name: Some("foo.txt"),
3335 file_stem: Some("foo"),
3336 extension: Some("txt")
3339 t!("\\\\server\\share",
3340 iter: ["\\\\server\\share", "\\"],
3350 iter: ["\\", "server"],
3354 file_name: Some("server"),
3355 file_stem: Some("server"),
3359 t!("\\\\?\\bar\\foo.txt",
3360 iter: ["\\\\?\\bar", "\\", "foo.txt"],
3363 parent: Some("\\\\?\\bar\\"),
3364 file_name: Some("foo.txt"),
3365 file_stem: Some("foo"),
3366 extension: Some("txt")
3370 iter: ["\\\\?\\bar"],
3389 t!("\\\\?\\UNC\\server\\share\\foo.txt",
3390 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
3393 parent: Some("\\\\?\\UNC\\server\\share\\"),
3394 file_name: Some("foo.txt"),
3395 file_stem: Some("foo"),
3396 extension: Some("txt")
3399 t!("\\\\?\\UNC\\server",
3400 iter: ["\\\\?\\UNC\\server"],
3410 iter: ["\\\\?\\UNC\\"],
3419 t!("\\\\?\\C:\\foo.txt",
3420 iter: ["\\\\?\\C:", "\\", "foo.txt"],
3423 parent: Some("\\\\?\\C:\\"),
3424 file_name: Some("foo.txt"),
3425 file_stem: Some("foo"),
3426 extension: Some("txt")
3431 iter: ["\\\\?\\C:", "\\"],
3442 iter: ["\\\\?\\C:"],
3452 t!("\\\\?\\foo/bar",
3453 iter: ["\\\\?\\foo/bar"],
3464 iter: ["\\\\?\\C:/foo"],
3474 t!("\\\\.\\foo\\bar",
3475 iter: ["\\\\.\\foo", "\\", "bar"],
3478 parent: Some("\\\\.\\foo\\"),
3479 file_name: Some("bar"),
3480 file_stem: Some("bar"),
3486 iter: ["\\\\.\\foo", "\\"],
3496 t!("\\\\.\\foo/bar",
3497 iter: ["\\\\.\\foo/bar", "\\"],
3507 t!("\\\\.\\foo\\bar/baz",
3508 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3511 parent: Some("\\\\.\\foo\\bar"),
3512 file_name: Some("baz"),
3513 file_stem: Some("baz"),
3519 iter: ["\\\\.\\", "\\"],
3529 iter: ["\\\\?\\a", "\\", "b"],
3532 parent: Some("\\\\?\\a\\"),
3533 file_name: Some("b"),
3534 file_stem: Some("b"),
3540 pub fn test_stem_ext() {
3542 file_stem: Some("foo"),
3547 file_stem: Some("foo"),
3552 file_stem: Some(".foo"),
3557 file_stem: Some("foo"),
3558 extension: Some("txt")
3562 file_stem: Some("foo.bar"),
3563 extension: Some("txt")
3567 file_stem: Some("foo.bar"),
3588 pub fn test_push() {
3590 ($path:expr, $push:expr, $expected:expr) => ( {
3591 let mut actual = PathBuf::from($path);
3593 assert!(actual.to_str() == Some($expected),
3594 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3595 $push, $path, $expected, actual.to_str().unwrap());
3600 tp!("", "foo", "foo");
3601 tp!("foo", "bar", "foo/bar");
3602 tp!("foo/", "bar", "foo/bar");
3603 tp!("foo//", "bar", "foo//bar");
3604 tp!("foo/.", "bar", "foo/./bar");
3605 tp!("foo./.", "bar", "foo././bar");
3606 tp!("foo", "", "foo/");
3607 tp!("foo", ".", "foo/.");
3608 tp!("foo", "..", "foo/..");
3609 tp!("foo", "/", "/");
3610 tp!("/foo/bar", "/", "/");
3611 tp!("/foo/bar", "/baz", "/baz");
3612 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3614 tp!("", "foo", "foo");
3615 tp!("foo", "bar", r"foo\bar");
3616 tp!("foo/", "bar", r"foo/bar");
3617 tp!(r"foo\", "bar", r"foo\bar");
3618 tp!("foo//", "bar", r"foo//bar");
3619 tp!(r"foo\\", "bar", r"foo\\bar");
3620 tp!("foo/.", "bar", r"foo/.\bar");
3621 tp!("foo./.", "bar", r"foo./.\bar");
3622 tp!(r"foo\.", "bar", r"foo\.\bar");
3623 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3624 tp!("foo", "", "foo\\");
3625 tp!("foo", ".", r"foo\.");
3626 tp!("foo", "..", r"foo\..");
3627 tp!("foo", "/", "/");
3628 tp!("foo", r"\", r"\");
3629 tp!("/foo/bar", "/", "/");
3630 tp!(r"\foo\bar", r"\", r"\");
3631 tp!("/foo/bar", "/baz", "/baz");
3632 tp!("/foo/bar", r"\baz", r"\baz");
3633 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3634 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3636 tp!("c:\\", "windows", "c:\\windows");
3637 tp!("c:", "windows", "c:windows");
3639 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3640 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3641 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3642 tp!("a\\b", "\\c\\d", "\\c\\d");
3643 tp!("a\\b", ".", "a\\b\\.");
3644 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3645 tp!("a\\b", "C:a.txt", "C:a.txt");
3646 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3647 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3648 tp!("C:\\a\\b\\c", "C:d", "C:d");
3649 tp!("C:a\\b\\c", "C:d", "C:d");
3650 tp!("C:", r"a\b\c", r"C:a\b\c");
3651 tp!("C:", r"..\a", r"C:..\a");
3652 tp!("\\\\server\\share\\foo",
3654 "\\\\server\\share\\foo\\bar");
3655 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3656 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3657 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3658 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3659 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3660 tp!("\\\\?\\UNC\\server\\share\\foo",
3662 "\\\\?\\UNC\\server\\share\\foo\\bar");
3663 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3664 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3666 // Note: modified from old path API
3667 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3670 "\\\\?\\UNC\\server\\share",
3671 "\\\\?\\UNC\\server\\share");
3672 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3673 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3674 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3675 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3677 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3684 ($path:expr, $expected:expr, $output:expr) => ( {
3685 let mut actual = PathBuf::from($path);
3686 let output = actual.pop();
3687 assert!(actual.to_str() == Some($expected) && output == $output,
3688 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3689 $path, $expected, $output,
3690 actual.to_str().unwrap(), output);
3695 tp!("/", "/", false);
3696 tp!("foo", "", true);
3698 tp!("/foo", "/", true);
3699 tp!("/foo/bar", "/foo", true);
3700 tp!("foo/bar", "foo", true);
3701 tp!("foo/.", "", true);
3702 tp!("foo//bar", "foo", true);
3705 tp!("a\\b\\c", "a\\b", true);
3706 tp!("\\a", "\\", true);
3707 tp!("\\", "\\", false);
3709 tp!("C:\\a\\b", "C:\\a", true);
3710 tp!("C:\\a", "C:\\", true);
3711 tp!("C:\\", "C:\\", false);
3712 tp!("C:a\\b", "C:a", true);
3713 tp!("C:a", "C:", true);
3714 tp!("C:", "C:", false);
3715 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3716 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3717 tp!("\\\\server\\share", "\\\\server\\share", false);
3718 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3719 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3720 tp!("\\\\?\\a", "\\\\?\\a", false);
3721 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3722 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3723 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3724 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3725 "\\\\?\\UNC\\server\\share\\a",
3727 tp!("\\\\?\\UNC\\server\\share\\a",
3728 "\\\\?\\UNC\\server\\share\\",
3730 tp!("\\\\?\\UNC\\server\\share",
3731 "\\\\?\\UNC\\server\\share",
3733 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3734 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3735 tp!("\\\\.\\a", "\\\\.\\a", false);
3737 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3742 pub fn test_set_file_name() {
3744 ($path:expr, $file:expr, $expected:expr) => ( {
3745 let mut p = PathBuf::from($path);
3746 p.set_file_name($file);
3747 assert!(p.to_str() == Some($expected),
3748 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3749 $path, $file, $expected,
3750 p.to_str().unwrap());
3754 tfn!("foo", "foo", "foo");
3755 tfn!("foo", "bar", "bar");
3756 tfn!("foo", "", "");
3757 tfn!("", "foo", "foo");
3759 tfn!(".", "foo", "./foo");
3760 tfn!("foo/", "bar", "bar");
3761 tfn!("foo/.", "bar", "bar");
3762 tfn!("..", "foo", "../foo");
3763 tfn!("foo/..", "bar", "foo/../bar");
3764 tfn!("/", "foo", "/foo");
3766 tfn!(".", "foo", r".\foo");
3767 tfn!(r"foo\", "bar", r"bar");
3768 tfn!(r"foo\.", "bar", r"bar");
3769 tfn!("..", "foo", r"..\foo");
3770 tfn!(r"foo\..", "bar", r"foo\..\bar");
3771 tfn!(r"\", "foo", r"\foo");
3776 pub fn test_set_extension() {
3778 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3779 let mut p = PathBuf::from($path);
3780 let output = p.set_extension($ext);
3781 assert!(p.to_str() == Some($expected) && output == $output,
3782 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3783 $path, $ext, $expected, $output,
3784 p.to_str().unwrap(), output);
3788 tfe!("foo", "txt", "foo.txt", true);
3789 tfe!("foo.bar", "txt", "foo.txt", true);
3790 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3791 tfe!(".test", "txt", ".test.txt", true);
3792 tfe!("foo.txt", "", "foo", true);
3793 tfe!("foo", "", "foo", true);
3794 tfe!("", "foo", "", false);
3795 tfe!(".", "foo", ".", false);
3796 tfe!("foo/", "bar", "foo.bar", true);
3797 tfe!("foo/.", "bar", "foo.bar", true);
3798 tfe!("..", "foo", "..", false);
3799 tfe!("foo/..", "bar", "foo/..", false);
3800 tfe!("/", "foo", "/", false);
3804 fn test_eq_receivers() {
3807 let borrowed: &Path = Path::new("foo/bar");
3808 let mut owned: PathBuf = PathBuf::new();
3811 let borrowed_cow: Cow<Path> = borrowed.into();
3812 let owned_cow: Cow<Path> = owned.clone().into();
3815 ($($current:expr),+) => {
3817 assert_eq!($current, borrowed);
3818 assert_eq!($current, owned);
3819 assert_eq!($current, borrowed_cow);
3820 assert_eq!($current, owned_cow);
3825 t!(borrowed, owned, borrowed_cow, owned_cow);
3829 pub fn test_compare() {
3830 use hash::{Hash, Hasher};
3831 use collections::hash_map::DefaultHasher;
3833 fn hash<T: Hash>(t: T) -> u64 {
3834 let mut s = DefaultHasher::new();
3840 ($path1:expr, $path2:expr, eq: $eq:expr,
3841 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3842 relative_from: $relative_from:expr) => ({
3843 let path1 = Path::new($path1);
3844 let path2 = Path::new($path2);
3846 let eq = path1 == path2;
3847 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3848 $path1, $path2, $eq, eq);
3849 assert!($eq == (hash(path1) == hash(path2)),
3850 "{:?} == {:?}, expected {:?}, got {} and {}",
3851 $path1, $path2, $eq, hash(path1), hash(path2));
3853 let starts_with = path1.starts_with(path2);
3854 assert!(starts_with == $starts_with,
3855 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3856 $starts_with, starts_with);
3858 let ends_with = path1.ends_with(path2);
3859 assert!(ends_with == $ends_with,
3860 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3861 $ends_with, ends_with);
3863 let relative_from = path1.strip_prefix(path2)
3864 .map(|p| p.to_str().unwrap())
3866 let exp: Option<&str> = $relative_from;
3867 assert!(relative_from == exp,
3868 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3869 $path1, $path2, exp, relative_from);
3877 relative_from: Some("")
3884 relative_from: Some("foo")
3898 relative_from: Some("")
3905 relative_from: Some("")
3908 tc!("foo/bar", "foo",
3912 relative_from: Some("bar")
3915 tc!("foo/bar/baz", "foo/bar",
3919 relative_from: Some("baz")
3922 tc!("foo/bar", "foo/bar/baz",
3929 tc!("./foo/bar/", ".",
3933 relative_from: Some("foo/bar")
3937 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3938 r"c:\src\rust\cargo-test\test",
3942 relative_from: Some("Cargo.toml")
3945 tc!(r"c:\foo", r"C:\foo",
3949 relative_from: Some("")
3955 fn test_components_debug() {
3956 let path = Path::new("/tmp");
3958 let mut components = path.components();
3960 let expected = "Components([RootDir, Normal(\"tmp\")])";
3961 let actual = format!("{:?}", components);
3962 assert_eq!(expected, actual);
3964 let _ = components.next().unwrap();
3965 let expected = "Components([Normal(\"tmp\")])";
3966 let actual = format!("{:?}", components);
3967 assert_eq!(expected, actual);
3969 let _ = components.next().unwrap();
3970 let expected = "Components([])";
3971 let actual = format!("{:?}", components);
3972 assert_eq!(expected, actual);
3977 fn test_iter_debug() {
3978 let path = Path::new("/tmp");
3980 let mut iter = path.iter();
3982 let expected = "Iter([\"/\", \"tmp\"])";
3983 let actual = format!("{:?}", iter);
3984 assert_eq!(expected, actual);
3986 let _ = iter.next().unwrap();
3987 let expected = "Iter([\"tmp\"])";
3988 let actual = format!("{:?}", iter);
3989 assert_eq!(expected, actual);
3991 let _ = iter.next().unwrap();
3992 let expected = "Iter([])";
3993 let actual = format!("{:?}", iter);
3994 assert_eq!(expected, actual);
3999 let orig: &str = "some/sort/of/path";
4000 let path = Path::new(orig);
4001 let boxed: Box<Path> = Box::from(path);
4002 let path_buf = path.to_owned().into_boxed_path().into_path_buf();
4003 assert_eq!(path, &*boxed);
4004 assert_eq!(&*boxed, &*path_buf);
4005 assert_eq!(&*path_buf, path);
4009 fn test_clone_into() {
4010 let mut path_buf = PathBuf::from("supercalifragilisticexpialidocious");
4011 let path = Path::new("short");
4012 path.clone_into(&mut path_buf);
4013 assert_eq!(path, path_buf);
4014 assert!(path_buf.into_os_string().capacity() >= 15);
4018 fn display_format_flags() {
4019 assert_eq!(format!("a{:#<5}b", Path::new("").display()), "a#####b");
4020 assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
4025 let orig = "hello/world";
4026 let path = Path::new(orig);
4027 let rc: Rc<Path> = Rc::from(path);
4028 let arc: Arc<Path> = Arc::from(path);
4030 assert_eq!(&*rc, path);
4031 assert_eq!(&*arc, path);
4033 let rc2: Rc<Path> = Rc::from(path.to_owned());
4034 let arc2: Arc<Path> = Arc::from(path.to_owned());
4036 assert_eq!(&*rc2, path);
4037 assert_eq!(&*arc2, path);