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` (akin to `String` and
14 //! `str`), for working with paths abstractly. These types are thin wrappers
15 //! around `OsString` and `OsStr` respectively, meaning that they work directly
16 //! on strings according to the local platform's path syntax.
20 //! Path manipulation includes both parsing components from slices and building
23 //! To parse a path, you can create a `Path` slice from a `str`
24 //! slice and start asking questions:
27 //! use std::path::Path;
29 //! let path = Path::new("/tmp/foo/bar.txt");
30 //! let file = path.file_name();
31 //! let extension = path.extension();
32 //! let parent_dir = path.parent();
35 //! To build or modify paths, use `PathBuf`:
38 //! use std::path::PathBuf;
40 //! let mut path = PathBuf::from("c:\\");
41 //! path.push("windows");
42 //! path.push("system32");
43 //! path.set_extension("dll");
46 //! ## Path components and normalization
48 //! The path APIs are built around the notion of "components", which roughly
49 //! correspond to the substrings between path separators (`/` and, on Windows,
50 //! `\`). The APIs for path parsing are largely specified in terms of the path's
51 //! components, so it's important to clearly understand how those are
54 //! A path can always be reconstructed into an *equivalent* path by
55 //! putting together its components via `push`. Syntactically, the
56 //! paths may differ by the normalization described below.
58 //! ### Component types
60 //! Components come in several types:
62 //! * Normal components are the default: standard references to files or
63 //! directories. The path `a/b` has two normal components, `a` and `b`.
65 //! * Current directory components represent the `.` character. For example,
66 //! `./a` has a current directory component and a normal component `a`.
68 //! * The root directory component represents a separator that designates
69 //! starting from root. For example, `/a/b` has a root directory component
70 //! followed by normal components `a` and `b`.
72 //! On Windows, an additional component type comes into play:
74 //! * Prefix components, of which there is a large variety. For example, `C:`
75 //! and `\\server\share` are prefixes. The path `C:windows` has a prefix
76 //! component `C:` and a normal component `windows`; the path `C:\windows` has a
77 //! prefix component `C:`, a root directory component, and a normal component
82 //! Aside from splitting on the separator(s), there is a small amount of
85 //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
88 //! * Occurrences of `.` are normalized away, *except* if they are at
89 //! the beginning of the path (in which case they are often meaningful
90 //! in terms of path searching). So, for example, `a/./b`, `a/b/`,
91 //! `/a/b/.` and `a/b` all have components `a` and `b`, but `./a/b`
92 //! has a leading current directory component.
94 //! No other normalization takes place by default. In particular,
95 //! `a/c` and `a/b/../c` are distinct, to account for the possibility
96 //! that `b` is a symbolic link (so its parent isn't `a`). Further
97 //! normalization is possible to build on top of the components APIs,
98 //! and will be included in this library in the near future.
100 #![stable(feature = "rust1", since = "1.0.0")]
103 use borrow::{Borrow, ToOwned, Cow};
108 use hash::{Hash, Hasher};
112 use ops::{self, Deref};
116 use ffi::{OsStr, OsString};
118 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
120 ////////////////////////////////////////////////////////////////////////////////
122 ////////////////////////////////////////////////////////////////////////////////
124 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
125 // taking advantage of the fact that OsStr always encodes ASCII characters
126 // as-is. Eventually, this transmutation should be replaced by direct uses of
127 // OsStr APIs for parsing, but it will take a while for those to become
130 ////////////////////////////////////////////////////////////////////////////////
131 // Platform-specific definitions
132 ////////////////////////////////////////////////////////////////////////////////
134 // The following modules give the most basic tools for parsing paths on various
135 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
143 pub fn is_sep_byte(b: u8) -> bool {
148 pub fn is_verbatim_sep(b: u8) -> bool {
152 pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
156 pub const MAIN_SEP_STR: &'static str = "/";
157 pub const MAIN_SEP: char = '/';
164 use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
168 pub fn is_sep_byte(b: u8) -> bool {
169 b == b'/' || b == b'\\'
173 pub fn is_verbatim_sep(b: u8) -> bool {
177 pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
178 use super::Prefix::*;
180 // The unsafety here stems from converting between &OsStr and &[u8]
181 // and back. This is safe to do because (1) we only look at ASCII
182 // contents of the encoding and (2) new &OsStr values are produced
183 // only from ASCII-bounded slices of existing &OsStr values.
184 let mut path = os_str_as_u8_slice(path);
186 if path.starts_with(br"\\") {
189 if path.starts_with(br"?\") {
192 if path.starts_with(br"UNC\") {
193 // \\?\UNC\server\share
195 let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
196 Some((server, share)) =>
197 (u8_slice_as_os_str(server), u8_slice_as_os_str(share)),
198 None => (u8_slice_as_os_str(path), u8_slice_as_os_str(&[])),
200 return Some(VerbatimUNC(server, share));
203 let idx = path.iter().position(|&b| b == b'\\');
204 if idx == Some(2) && path[1] == b':' {
206 if c.is_ascii() && (c as char).is_alphabetic() {
208 return Some(VerbatimDisk(c.to_ascii_uppercase()));
211 let slice = &path[..idx.unwrap_or(path.len())];
212 return Some(Verbatim(u8_slice_as_os_str(slice)));
214 } else if path.starts_with(b".\\") {
217 let pos = path.iter().position(|&b| b == b'\\');
218 let slice = &path[..pos.unwrap_or(path.len())];
219 return Some(DeviceNS(u8_slice_as_os_str(slice)));
221 match parse_two_comps(path, is_sep_byte) {
222 Some((server, share)) if !server.is_empty() && !share.is_empty() => {
224 return Some(UNC(u8_slice_as_os_str(server), u8_slice_as_os_str(share)));
228 } else if path.get(1) == Some(& b':') {
231 if c.is_ascii() && (c as char).is_alphabetic() {
232 return Some(Disk(c.to_ascii_uppercase()));
238 fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
239 let first = match path.iter().position(|x| f(*x)) {
241 Some(x) => &path[..x],
243 path = &path[(first.len() + 1)..];
244 let idx = path.iter().position(|x| f(*x));
245 let second = &path[..idx.unwrap_or(path.len())];
246 Some((first, second))
250 pub const MAIN_SEP_STR: &'static str = "\\";
251 pub const MAIN_SEP: char = '\\';
254 ////////////////////////////////////////////////////////////////////////////////
256 ////////////////////////////////////////////////////////////////////////////////
258 /// Path prefixes (Windows only).
260 /// Windows uses a variety of path styles, including references to drive
261 /// volumes (like `C:`), network shared folders (like `\\server\share`) and
262 /// others. In addition, some path prefixes are "verbatim", in which case
263 /// `/` is *not* treated as a separator and essentially no normalization is
265 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub enum Prefix<'a> {
268 /// Prefix `\\?\`, together with the given component immediately following it.
269 #[stable(feature = "rust1", since = "1.0.0")]
270 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
272 /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
273 #[stable(feature = "rust1", since = "1.0.0")]
275 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
276 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
279 /// Prefix like `\\?\C:\`, for the given drive letter
280 #[stable(feature = "rust1", since = "1.0.0")]
281 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
283 /// Prefix `\\.\`, together with the given component immediately following it.
284 #[stable(feature = "rust1", since = "1.0.0")]
285 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
287 /// Prefix `\\server\share`, with the given "server" and "share" components.
288 #[stable(feature = "rust1", since = "1.0.0")]
290 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
291 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
294 /// Prefix `C:` for the given disk drive.
295 #[stable(feature = "rust1", since = "1.0.0")]
296 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
299 impl<'a> Prefix<'a> {
301 fn len(&self) -> usize {
303 fn os_str_len(s: &OsStr) -> usize {
304 os_str_as_u8_slice(s).len()
307 Verbatim(x) => 4 + os_str_len(x),
308 VerbatimUNC(x, y) => {
310 if os_str_len(y) > 0 {
316 VerbatimDisk(_) => 6,
319 if os_str_len(y) > 0 {
325 DeviceNS(x) => 4 + os_str_len(x),
331 /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub fn is_verbatim(&self) -> bool {
337 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
343 fn is_drive(&self) -> bool {
345 Prefix::Disk(_) => true,
351 fn has_implicit_root(&self) -> bool {
356 ////////////////////////////////////////////////////////////////////////////////
357 // Exposed parsing helpers
358 ////////////////////////////////////////////////////////////////////////////////
360 /// Determines whether the character is one of the permitted path
361 /// separators for the current platform.
368 /// assert!(path::is_separator('/'));
369 /// assert!(!path::is_separator('❤'));
371 #[stable(feature = "rust1", since = "1.0.0")]
372 pub fn is_separator(c: char) -> bool {
373 c.is_ascii() && is_sep_byte(c as u8)
376 /// The primary separator for the current platform
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
380 ////////////////////////////////////////////////////////////////////////////////
382 ////////////////////////////////////////////////////////////////////////////////
384 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
385 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
386 // `iter` after having exhausted `prefix`.
387 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
388 where I: Iterator<Item = A> + Clone,
389 J: Iterator<Item = A>,
393 let mut iter_next = iter.clone();
394 match (iter_next.next(), prefix.next()) {
395 (Some(ref x), Some(ref y)) if x == y => (),
396 (Some(_), Some(_)) => return None,
397 (Some(_), None) => return Some(iter),
398 (None, None) => return Some(iter),
399 (None, Some(_)) => return None,
405 // See note at the top of this module to understand why these are used:
406 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
407 unsafe { mem::transmute(s) }
409 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
413 ////////////////////////////////////////////////////////////////////////////////
414 // Cross-platform, iterator-independent parsing
415 ////////////////////////////////////////////////////////////////////////////////
417 /// Says whether the first byte after the prefix is a separator.
418 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
419 let path = if let Some(p) = prefix {
424 !path.is_empty() && is_sep_byte(path[0])
427 // basic workhorse for splitting stem and extension
428 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
430 if os_str_as_u8_slice(file) == b".." {
431 return (Some(file), None);
434 // The unsafety here stems from converting between &OsStr and &[u8]
435 // and back. This is safe to do because (1) we only look at ASCII
436 // contents of the encoding and (2) new &OsStr values are produced
437 // only from ASCII-bounded slices of existing &OsStr values.
439 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
440 let after = iter.next();
441 let before = iter.next();
442 if before == Some(b"") {
445 (before.map(|s| u8_slice_as_os_str(s)),
446 after.map(|s| u8_slice_as_os_str(s)))
451 ////////////////////////////////////////////////////////////////////////////////
452 // The core iterators
453 ////////////////////////////////////////////////////////////////////////////////
455 /// Component parsing works by a double-ended state machine; the cursors at the
456 /// front and back of the path each keep track of what parts of the path have
457 /// been consumed so far.
459 /// Going front to back, a path is made up of a prefix, a starting
460 /// directory component, and a body (of normal components)
461 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
464 StartDir = 1, // / or . or nothing
465 Body = 2, // foo/bar/baz
469 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
471 /// Does not occur on Unix.
472 #[stable(feature = "rust1", since = "1.0.0")]
473 #[derive(Copy, Clone, Eq, Debug)]
474 pub struct PrefixComponent<'a> {
475 /// The prefix as an unparsed `OsStr` slice.
478 /// The parsed prefix data.
482 impl<'a> PrefixComponent<'a> {
483 /// The parsed prefix data.
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn kind(&self) -> Prefix<'a> {
489 /// The raw `OsStr` slice for this prefix.
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn as_os_str(&self) -> &'a OsStr {
496 #[stable(feature = "rust1", since = "1.0.0")]
497 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
498 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
499 cmp::PartialEq::eq(&self.parsed, &other.parsed)
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
505 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
506 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
510 #[stable(feature = "rust1", since = "1.0.0")]
511 impl<'a> cmp::Ord for PrefixComponent<'a> {
512 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
513 cmp::Ord::cmp(&self.parsed, &other.parsed)
517 #[stable(feature = "rust1", since = "1.0.0")]
518 impl<'a> Hash for PrefixComponent<'a> {
519 fn hash<H: Hasher>(&self, h: &mut H) {
524 /// A single component of a path.
526 /// See the module documentation for an in-depth explanation of components and
527 /// their role in the API.
529 /// This `enum` is created from iterating over the [`path::Components`]
535 /// use std::path::{Component, Path};
537 /// let path = Path::new("/tmp/foo/bar.txt");
538 /// let components = path.components().collect::<Vec<_>>();
539 /// assert_eq!(&components, &[
540 /// Component::RootDir,
541 /// Component::Normal("tmp".as_ref()),
542 /// Component::Normal("foo".as_ref()),
543 /// Component::Normal("bar.txt".as_ref()),
547 /// [`path::Components`]: struct.Components.html
548 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub enum Component<'a> {
551 /// A Windows path prefix, e.g. `C:` or `\\server\share`.
553 /// Does not occur on Unix.
554 #[stable(feature = "rust1", since = "1.0.0")]
556 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
559 /// The root directory component, appears after any prefix and before anything else
560 #[stable(feature = "rust1", since = "1.0.0")]
563 /// A reference to the current directory, i.e. `.`
564 #[stable(feature = "rust1", since = "1.0.0")]
567 /// A reference to the parent directory, i.e. `..`
568 #[stable(feature = "rust1", since = "1.0.0")]
571 /// A normal component, i.e. `a` and `b` in `a/b`
572 #[stable(feature = "rust1", since = "1.0.0")]
573 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
576 impl<'a> Component<'a> {
577 /// Extracts the underlying `OsStr` slice
578 #[stable(feature = "rust1", since = "1.0.0")]
579 pub fn as_os_str(self) -> &'a OsStr {
581 Component::Prefix(p) => p.as_os_str(),
582 Component::RootDir => OsStr::new(MAIN_SEP_STR),
583 Component::CurDir => OsStr::new("."),
584 Component::ParentDir => OsStr::new(".."),
585 Component::Normal(path) => path,
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<'a> AsRef<OsStr> for Component<'a> {
592 fn as_ref(&self) -> &OsStr {
597 /// The core iterator giving the components of a path.
599 /// See the module documentation for an in-depth explanation of components and
600 /// their role in the API.
602 /// This `struct` is created by the [`path::Path::components`] method.
607 /// use std::path::Path;
609 /// let path = Path::new("/tmp/foo/bar.txt");
611 /// for component in path.components() {
612 /// println!("{:?}", component);
616 /// [`path::Path::components`]: struct.Path.html#method.components
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub struct Components<'a> {
620 // The path left to parse components from
623 // The prefix as it was originally parsed, if any
624 prefix: Option<Prefix<'a>>,
626 // true if path *physically* has a root separator; for most Windows
627 // prefixes, it may have a "logical" rootseparator for the purposes of
628 // normalization, e.g. \\server\share == \\server\share\.
629 has_physical_root: bool,
631 // The iterator is double-ended, and these two states keep track of what has
632 // been produced from either end
637 /// An iterator over the components of a path, as `OsStr` slices.
639 #[stable(feature = "rust1", since = "1.0.0")]
640 pub struct Iter<'a> {
641 inner: Components<'a>,
644 impl<'a> Components<'a> {
645 // how long is the prefix, if any?
647 fn prefix_len(&self) -> usize {
648 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
652 fn prefix_verbatim(&self) -> bool {
653 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
656 /// how much of the prefix is left from the point of view of iteration?
658 fn prefix_remaining(&self) -> usize {
659 if self.front == State::Prefix {
666 // Given the iteration so far, how much of the pre-State::Body path is left?
668 fn len_before_body(&self) -> usize {
669 let root = if self.front <= State::StartDir && self.has_physical_root {
674 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
679 self.prefix_remaining() + root + cur_dir
682 // is the iteration complete?
684 fn finished(&self) -> bool {
685 self.front == State::Done || self.back == State::Done || self.front > self.back
689 fn is_sep_byte(&self, b: u8) -> bool {
690 if self.prefix_verbatim() {
697 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
702 /// use std::path::Path;
704 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
705 /// components.next();
706 /// components.next();
708 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
710 #[stable(feature = "rust1", since = "1.0.0")]
711 pub fn as_path(&self) -> &'a Path {
712 let mut comps = self.clone();
713 if comps.front == State::Body {
716 if comps.back == State::Body {
719 unsafe { Path::from_u8_slice(comps.path) }
722 /// Is the *original* path rooted?
723 fn has_root(&self) -> bool {
724 if self.has_physical_root {
727 if let Some(p) = self.prefix {
728 if p.has_implicit_root() {
735 /// Should the normalized path include a leading . ?
736 fn include_cur_dir(&self) -> bool {
740 let mut iter = self.path[self.prefix_len()..].iter();
741 match (iter.next(), iter.next()) {
742 (Some(&b'.'), None) => true,
743 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
748 // parse a given byte sequence into the corresponding path component
749 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
751 b"." if self.prefix_verbatim() => Some(Component::CurDir),
752 b"." => None, // . components are normalized away, except at
753 // the beginning of a path, which is treated
754 // separately via `include_cur_dir`
755 b".." => Some(Component::ParentDir),
757 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
761 // parse a component from the left, saying how many bytes to consume to
762 // remove the component
763 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
764 debug_assert!(self.front == State::Body);
765 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
766 None => (0, self.path),
767 Some(i) => (1, &self.path[..i]),
769 (comp.len() + extra, self.parse_single_component(comp))
772 // parse a component from the right, saying how many bytes to consume to
773 // remove the component
774 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
775 debug_assert!(self.back == State::Body);
776 let start = self.len_before_body();
777 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
778 None => (0, &self.path[start..]),
779 Some(i) => (1, &self.path[start + i + 1..]),
781 (comp.len() + extra, self.parse_single_component(comp))
784 // trim away repeated separators (i.e. empty components) on the left
785 fn trim_left(&mut self) {
786 while !self.path.is_empty() {
787 let (size, comp) = self.parse_next_component();
791 self.path = &self.path[size..];
796 // trim away repeated separators (i.e. empty components) on the right
797 fn trim_right(&mut self) {
798 while self.path.len() > self.len_before_body() {
799 let (size, comp) = self.parse_next_component_back();
803 self.path = &self.path[..self.path.len() - size];
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a> AsRef<Path> for Components<'a> {
811 fn as_ref(&self) -> &Path {
816 #[stable(feature = "rust1", since = "1.0.0")]
817 impl<'a> AsRef<OsStr> for Components<'a> {
818 fn as_ref(&self) -> &OsStr {
819 self.as_path().as_os_str()
824 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn as_path(&self) -> &'a Path {
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<'a> AsRef<Path> for Iter<'a> {
833 fn as_ref(&self) -> &Path {
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<'a> AsRef<OsStr> for Iter<'a> {
840 fn as_ref(&self) -> &OsStr {
841 self.as_path().as_os_str()
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<'a> Iterator for Iter<'a> {
847 type Item = &'a OsStr;
849 fn next(&mut self) -> Option<&'a OsStr> {
850 self.inner.next().map(Component::as_os_str)
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<'a> DoubleEndedIterator for Iter<'a> {
856 fn next_back(&mut self) -> Option<&'a OsStr> {
857 self.inner.next_back().map(Component::as_os_str)
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<'a> Iterator for Components<'a> {
863 type Item = Component<'a>;
865 fn next(&mut self) -> Option<Component<'a>> {
866 while !self.finished() {
868 State::Prefix if self.prefix_len() > 0 => {
869 self.front = State::StartDir;
870 debug_assert!(self.prefix_len() <= self.path.len());
871 let raw = &self.path[..self.prefix_len()];
872 self.path = &self.path[self.prefix_len()..];
873 return Some(Component::Prefix(PrefixComponent {
874 raw: unsafe { u8_slice_as_os_str(raw) },
875 parsed: self.prefix.unwrap(),
879 self.front = State::StartDir;
882 self.front = State::Body;
883 if self.has_physical_root {
884 debug_assert!(!self.path.is_empty());
885 self.path = &self.path[1..];
886 return Some(Component::RootDir);
887 } else if let Some(p) = self.prefix {
888 if p.has_implicit_root() && !p.is_verbatim() {
889 return Some(Component::RootDir);
891 } else if self.include_cur_dir() {
892 debug_assert!(!self.path.is_empty());
893 self.path = &self.path[1..];
894 return Some(Component::CurDir);
897 State::Body if !self.path.is_empty() => {
898 let (size, comp) = self.parse_next_component();
899 self.path = &self.path[size..];
905 self.front = State::Done;
907 State::Done => unreachable!(),
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<'a> DoubleEndedIterator for Components<'a> {
916 fn next_back(&mut self) -> Option<Component<'a>> {
917 while !self.finished() {
919 State::Body if self.path.len() > self.len_before_body() => {
920 let (size, comp) = self.parse_next_component_back();
921 self.path = &self.path[..self.path.len() - size];
927 self.back = State::StartDir;
930 self.back = State::Prefix;
931 if self.has_physical_root {
932 self.path = &self.path[..self.path.len() - 1];
933 return Some(Component::RootDir);
934 } else if let Some(p) = self.prefix {
935 if p.has_implicit_root() && !p.is_verbatim() {
936 return Some(Component::RootDir);
938 } else if self.include_cur_dir() {
939 self.path = &self.path[..self.path.len() - 1];
940 return Some(Component::CurDir);
943 State::Prefix if self.prefix_len() > 0 => {
944 self.back = State::Done;
945 return Some(Component::Prefix(PrefixComponent {
946 raw: unsafe { u8_slice_as_os_str(self.path) },
947 parsed: self.prefix.unwrap(),
951 self.back = State::Done;
954 State::Done => unreachable!(),
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<'a> cmp::PartialEq for Components<'a> {
963 fn eq(&self, other: &Components<'a>) -> bool {
964 Iterator::eq(self.clone(), other.clone())
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<'a> cmp::Eq for Components<'a> {}
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<'a> cmp::PartialOrd for Components<'a> {
973 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
974 Iterator::partial_cmp(self.clone(), other.clone())
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl<'a> cmp::Ord for Components<'a> {
980 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
981 Iterator::cmp(self.clone(), other.clone())
985 ////////////////////////////////////////////////////////////////////////////////
986 // Basic types and traits
987 ////////////////////////////////////////////////////////////////////////////////
989 /// An owned, mutable path (akin to `String`).
991 /// This type provides methods like `push` and `set_extension` that mutate the
992 /// path in place. It also implements `Deref` to `Path`, meaning that all
993 /// methods on `Path` slices are available on `PathBuf` values as well.
995 /// More details about the overall approach can be found in
996 /// the module documentation.
1001 /// use std::path::PathBuf;
1003 /// let mut path = PathBuf::from("c:\\");
1004 /// path.push("windows");
1005 /// path.push("system32");
1006 /// path.set_extension("dll");
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 pub struct PathBuf {
1015 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1016 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1019 /// Allocates an empty `PathBuf`.
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn new() -> PathBuf {
1022 PathBuf { inner: OsString::new() }
1025 /// Coerces to a `Path` slice.
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 pub fn as_path(&self) -> &Path {
1031 /// Extends `self` with `path`.
1033 /// If `path` is absolute, it replaces the current path.
1037 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1038 /// replaces everything except for the prefix (if any) of `self`.
1039 /// * if `path` has a prefix but no root, it replaces `self`.
1044 /// use std::path::PathBuf;
1046 /// let mut path = PathBuf::new();
1047 /// path.push("/tmp");
1048 /// path.push("file.bk");
1049 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1051 /// // Pushing an absolute path replaces the current path
1052 /// path.push("/etc/passwd");
1053 /// assert_eq!(path, PathBuf::from("/etc/passwd"));
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1057 self._push(path.as_ref())
1060 #[allow(deprecated)]
1061 fn _push(&mut self, path: &Path) {
1062 // in general, a separator is needed if the rightmost byte is not a separator
1063 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1065 // in the special case of `C:` on Windows, do *not* add a separator
1067 let comps = self.components();
1068 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1069 comps.prefix.unwrap().is_drive() {
1074 // absolute `path` replaces `self`
1075 if path.is_absolute() || path.prefix().is_some() {
1076 self.as_mut_vec().truncate(0);
1078 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1079 } else if path.has_root() {
1080 let prefix_len = self.components().prefix_remaining();
1081 self.as_mut_vec().truncate(prefix_len);
1083 // `path` is a pure relative path
1084 } else if need_sep {
1085 self.inner.push(MAIN_SEP_STR);
1088 self.inner.push(path);
1091 /// Truncate `self` to `self.parent()`.
1093 /// Returns false and does nothing if `self.file_name()` is `None`.
1094 /// Otherwise, returns `true`.
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn pop(&mut self) -> bool {
1097 match self.parent().map(|p| p.as_u8_slice().len()) {
1099 self.as_mut_vec().truncate(len);
1106 /// Updates `self.file_name()` to `file_name`.
1108 /// If `self.file_name()` was `None`, this is equivalent to pushing
1114 /// use std::path::PathBuf;
1116 /// let mut buf = PathBuf::from("/");
1117 /// assert!(buf.file_name() == None);
1118 /// buf.set_file_name("bar");
1119 /// assert!(buf == PathBuf::from("/bar"));
1120 /// assert!(buf.file_name().is_some());
1121 /// buf.set_file_name("baz.txt");
1122 /// assert!(buf == PathBuf::from("/baz.txt"));
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1126 self._set_file_name(file_name.as_ref())
1129 fn _set_file_name(&mut self, file_name: &OsStr) {
1130 if self.file_name().is_some() {
1131 let popped = self.pop();
1132 debug_assert!(popped);
1134 self.push(file_name);
1137 /// Updates `self.extension()` to `extension`.
1139 /// If `self.file_name()` is `None`, does nothing and returns `false`.
1141 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
1142 /// is added; otherwise it is replaced.
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1145 self._set_extension(extension.as_ref())
1148 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1149 if self.file_name().is_none() {
1153 let mut stem = match self.file_stem() {
1154 Some(stem) => stem.to_os_string(),
1155 None => OsString::new(),
1158 if !os_str_as_u8_slice(extension).is_empty() {
1160 stem.push(extension);
1162 self.set_file_name(&stem);
1167 /// Consumes the `PathBuf`, yielding its internal `OsString` storage.
1168 #[stable(feature = "rust1", since = "1.0.0")]
1169 pub fn into_os_string(self) -> OsString {
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1176 fn from(s: &'a T) -> PathBuf {
1177 PathBuf::from(s.as_ref().to_os_string())
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl From<OsString> for PathBuf {
1183 fn from(s: OsString) -> PathBuf {
1184 PathBuf { inner: s }
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 impl From<String> for PathBuf {
1190 fn from(s: String) -> PathBuf {
1191 PathBuf::from(OsString::from(s))
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1197 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1198 let mut buf = PathBuf::new();
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1206 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1208 self.push(p.as_ref())
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl fmt::Debug for PathBuf {
1215 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1216 fmt::Debug::fmt(&**self, formatter)
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl ops::Deref for PathBuf {
1224 fn deref(&self) -> &Path {
1225 Path::new(&self.inner)
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 impl Borrow<Path> for PathBuf {
1231 fn borrow(&self) -> &Path {
1236 #[stable(feature = "cow_from_path", since = "1.6.0")]
1237 impl<'a> From<&'a Path> for Cow<'a, Path> {
1239 fn from(s: &'a Path) -> Cow<'a, Path> {
1244 #[stable(feature = "cow_from_path", since = "1.6.0")]
1245 impl<'a> From<PathBuf> for Cow<'a, Path> {
1247 fn from(s: PathBuf) -> Cow<'a, Path> {
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl ToOwned for Path {
1254 type Owned = PathBuf;
1255 fn to_owned(&self) -> PathBuf {
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl cmp::PartialEq for PathBuf {
1262 fn eq(&self, other: &PathBuf) -> bool {
1263 self.components() == other.components()
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 impl Hash for PathBuf {
1269 fn hash<H: Hasher>(&self, h: &mut H) {
1270 self.as_path().hash(h)
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl cmp::Eq for PathBuf {}
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl cmp::PartialOrd for PathBuf {
1279 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1280 self.components().partial_cmp(other.components())
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 impl cmp::Ord for PathBuf {
1286 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1287 self.components().cmp(other.components())
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 impl AsRef<OsStr> for PathBuf {
1293 fn as_ref(&self) -> &OsStr {
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 impl Into<OsString> for PathBuf {
1300 fn into(self) -> OsString {
1305 /// A slice of a path (akin to `str`).
1307 /// This type supports a number of operations for inspecting a path, including
1308 /// breaking the path into its components (separated by `/` or `\`, depending on
1309 /// the platform), extracting the file name, determining whether the path is
1310 /// absolute, and so on. More details about the overall approach can be found in
1311 /// the module documentation.
1313 /// This is an *unsized* type, meaning that it must always be used behind a
1314 /// pointer like `&` or `Box`.
1319 /// use std::path::Path;
1321 /// let path = Path::new("/tmp/foo/bar.txt");
1322 /// let file = path.file_name();
1323 /// let extension = path.extension();
1324 /// let parent_dir = path.parent();
1327 #[stable(feature = "rust1", since = "1.0.0")]
1332 /// An error returned from the `Path::strip_prefix` method indicating that the
1333 /// prefix was not found in `self`.
1334 #[derive(Debug, Clone, PartialEq, Eq)]
1335 #[stable(since = "1.7.0", feature = "strip_prefix")]
1336 pub struct StripPrefixError(());
1339 // The following (private!) function allows construction of a path from a u8
1340 // slice, which is only safe when it is known to follow the OsStr encoding.
1341 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1342 Path::new(u8_slice_as_os_str(s))
1344 // The following (private!) function reveals the byte encoding used for OsStr.
1345 fn as_u8_slice(&self) -> &[u8] {
1346 os_str_as_u8_slice(&self.inner)
1349 /// Directly wrap a string slice as a `Path` slice.
1351 /// This is a cost-free conversion.
1356 /// use std::path::Path;
1358 /// Path::new("foo.txt");
1361 /// You can create `Path`s from `String`s, or even other `Path`s:
1364 /// use std::path::Path;
1366 /// let string = String::from("foo.txt");
1367 /// let from_string = Path::new(&string);
1368 /// let from_path = Path::new(&from_string);
1369 /// assert_eq!(from_string, from_path);
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1373 unsafe { mem::transmute(s.as_ref()) }
1376 /// Yields the underlying `OsStr` slice.
1381 /// use std::path::Path;
1383 /// let os_str = Path::new("foo.txt").as_os_str();
1384 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 pub fn as_os_str(&self) -> &OsStr {
1391 /// Yields a `&str` slice if the `Path` is valid unicode.
1393 /// This conversion may entail doing a check for UTF-8 validity.
1398 /// use std::path::Path;
1400 /// let path_str = Path::new("foo.txt").to_str();
1401 /// assert_eq!(path_str, Some("foo.txt"));
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 pub fn to_str(&self) -> Option<&str> {
1408 /// Converts a `Path` to a `Cow<str>`.
1410 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1415 /// use std::path::Path;
1417 /// let path_str = Path::new("foo.txt").to_string_lossy();
1418 /// assert_eq!(path_str, "foo.txt");
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 pub fn to_string_lossy(&self) -> Cow<str> {
1422 self.inner.to_string_lossy()
1425 /// Converts a `Path` to an owned `PathBuf`.
1430 /// use std::path::Path;
1432 /// let path_buf = Path::new("foo.txt").to_path_buf();
1433 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub fn to_path_buf(&self) -> PathBuf {
1437 PathBuf::from(self.inner.to_os_string())
1440 /// A path is *absolute* if it is independent of the current directory.
1442 /// * On Unix, a path is absolute if it starts with the root, so
1443 /// `is_absolute` and `has_root` are equivalent.
1445 /// * On Windows, a path is absolute if it has a prefix and starts with the
1446 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1447 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1452 /// use std::path::Path;
1454 /// assert!(!Path::new("foo.txt").is_absolute());
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 #[allow(deprecated)]
1458 pub fn is_absolute(&self) -> bool {
1459 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1462 /// A path is *relative* if it is not absolute.
1467 /// use std::path::Path;
1469 /// assert!(Path::new("foo.txt").is_relative());
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 pub fn is_relative(&self) -> bool {
1476 fn prefix(&self) -> Option<Prefix> {
1477 self.components().prefix
1480 /// A path has a root if the body of the path begins with the directory separator.
1482 /// * On Unix, a path has a root if it begins with `/`.
1484 /// * On Windows, a path has a root if it:
1485 /// * has no prefix and begins with a separator, e.g. `\\windows`
1486 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1487 /// * has any non-disk prefix, e.g. `\\server\share`
1492 /// use std::path::Path;
1494 /// assert!(Path::new("/etc/passwd").has_root());
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn has_root(&self) -> bool {
1498 self.components().has_root()
1501 /// The path without its final component, if any.
1503 /// Returns `None` if the path terminates in a root or prefix.
1508 /// use std::path::Path;
1510 /// let path = Path::new("/foo/bar");
1511 /// let parent = path.parent().unwrap();
1512 /// assert_eq!(parent, Path::new("/foo"));
1514 /// let grand_parent = parent.parent().unwrap();
1515 /// assert_eq!(grand_parent, Path::new("/"));
1516 /// assert_eq!(grand_parent.parent(), None);
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 pub fn parent(&self) -> Option<&Path> {
1520 let mut comps = self.components();
1521 let comp = comps.next_back();
1524 Component::Normal(_) |
1526 Component::ParentDir => Some(comps.as_path()),
1532 /// The final component of the path, if it is a normal file.
1534 /// If the path terminates in `.`, `..`, or consists solely of a root of
1535 /// prefix, `file_name` will return `None`.
1540 /// use std::path::Path;
1541 /// use std::ffi::OsStr;
1543 /// let path = Path::new("foo.txt");
1544 /// let os_str = OsStr::new("foo.txt");
1546 /// assert_eq!(Some(os_str), path.file_name());
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 pub fn file_name(&self) -> Option<&OsStr> {
1550 self.components().next_back().and_then(|p| {
1552 Component::Normal(p) => Some(p.as_ref()),
1558 /// Returns a path that, when joined onto `base`, yields `self`.
1562 /// If `base` is not a prefix of `self` (i.e. `starts_with`
1563 /// returns `false`), returns `Err`.
1564 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1565 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1566 -> Result<&'a Path, StripPrefixError>
1567 where P: AsRef<Path>
1569 self._strip_prefix(base.as_ref())
1572 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1573 -> Result<&'a Path, StripPrefixError> {
1574 iter_after(self.components(), base.components())
1575 .map(|c| c.as_path())
1576 .ok_or(StripPrefixError(()))
1579 /// Determines whether `base` is a prefix of `self`.
1581 /// Only considers whole path components to match.
1586 /// use std::path::Path;
1588 /// let path = Path::new("/etc/passwd");
1590 /// assert!(path.starts_with("/etc"));
1592 /// assert!(!path.starts_with("/e"));
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1596 self._starts_with(base.as_ref())
1599 fn _starts_with(&self, base: &Path) -> bool {
1600 iter_after(self.components(), base.components()).is_some()
1603 /// Determines whether `child` is a suffix of `self`.
1605 /// Only considers whole path components to match.
1610 /// use std::path::Path;
1612 /// let path = Path::new("/etc/passwd");
1614 /// assert!(path.ends_with("passwd"));
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1618 self._ends_with(child.as_ref())
1621 fn _ends_with(&self, child: &Path) -> bool {
1622 iter_after(self.components().rev(), child.components().rev()).is_some()
1625 /// Extracts the stem (non-extension) portion of `self.file_name()`.
1629 /// * None, if there is no file name;
1630 /// * The entire file name if there is no embedded `.`;
1631 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1632 /// * Otherwise, the portion of the file name before the final `.`
1637 /// use std::path::Path;
1639 /// let path = Path::new("foo.rs");
1641 /// assert_eq!("foo", path.file_stem().unwrap());
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 pub fn file_stem(&self) -> Option<&OsStr> {
1645 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1648 /// Extracts the extension of `self.file_name()`, if possible.
1650 /// The extension is:
1652 /// * None, if there is no file name;
1653 /// * None, if there is no embedded `.`;
1654 /// * None, if the file name begins with `.` and has no other `.`s within;
1655 /// * Otherwise, the portion of the file name after the final `.`
1660 /// use std::path::Path;
1662 /// let path = Path::new("foo.rs");
1664 /// assert_eq!("rs", path.extension().unwrap());
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 pub fn extension(&self) -> Option<&OsStr> {
1668 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1671 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1673 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1678 /// use std::path::{Path, PathBuf};
1680 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1684 self._join(path.as_ref())
1687 fn _join(&self, path: &Path) -> PathBuf {
1688 let mut buf = self.to_path_buf();
1693 /// Creates an owned `PathBuf` like `self` but with the given file name.
1695 /// See `PathBuf::set_file_name` for more details.
1700 /// use std::path::{Path, PathBuf};
1702 /// let path = Path::new("/tmp/foo.txt");
1703 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1707 self._with_file_name(file_name.as_ref())
1710 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1711 let mut buf = self.to_path_buf();
1712 buf.set_file_name(file_name);
1716 /// Creates an owned `PathBuf` like `self` but with the given extension.
1718 /// See `PathBuf::set_extension` for more details.
1723 /// use std::path::{Path, PathBuf};
1725 /// let path = Path::new("foo.rs");
1726 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1730 self._with_extension(extension.as_ref())
1733 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1734 let mut buf = self.to_path_buf();
1735 buf.set_extension(extension);
1739 /// Produce an iterator over the components of the path.
1744 /// use std::path::{Path, Component};
1745 /// use std::ffi::OsStr;
1747 /// let mut components = Path::new("/tmp/foo.txt").components();
1749 /// assert_eq!(components.next(), Some(Component::RootDir));
1750 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1751 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1752 /// assert_eq!(components.next(), None)
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 pub fn components(&self) -> Components {
1756 let prefix = parse_prefix(self.as_os_str());
1758 path: self.as_u8_slice(),
1760 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1761 front: State::Prefix,
1766 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1771 /// use std::path::{self, Path};
1772 /// use std::ffi::OsStr;
1774 /// let mut it = Path::new("/tmp/foo.txt").iter();
1775 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1776 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1777 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1778 /// assert_eq!(it.next(), None)
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 pub fn iter(&self) -> Iter {
1782 Iter { inner: self.components() }
1785 /// Returns an object that implements `Display` for safely printing paths
1786 /// that may contain non-Unicode data.
1791 /// use std::path::Path;
1793 /// let path = Path::new("/tmp/foo.rs");
1795 /// println!("{}", path.display());
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 pub fn display(&self) -> Display {
1799 Display { path: self }
1803 /// Query the file system to get information about a file, directory, etc.
1805 /// This function will traverse symbolic links to query information about the
1806 /// destination file.
1808 /// This is an alias to [`fs::metadata`].
1810 /// [`fs::metadata`]: ../fs/fn.metadata.html
1811 #[stable(feature = "path_ext", since = "1.5.0")]
1812 pub fn metadata(&self) -> io::Result<fs::Metadata> {
1816 /// Query the metadata about a file without following symlinks.
1818 /// This is an alias to [`fs::symlink_metadata`].
1820 /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
1821 #[stable(feature = "path_ext", since = "1.5.0")]
1822 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1823 fs::symlink_metadata(self)
1826 /// Returns the canonical form of the path with all intermediate components
1827 /// normalized and symbolic links resolved.
1829 /// This is an alias to [`fs::canonicalize`].
1831 /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
1832 #[stable(feature = "path_ext", since = "1.5.0")]
1833 pub fn canonicalize(&self) -> io::Result<PathBuf> {
1834 fs::canonicalize(self)
1837 /// Reads a symbolic link, returning the file that the link points to.
1839 /// This is an alias to [`fs::read_link`].
1841 /// [`fs::read_link`]: ../fs/fn.read_link.html
1842 #[stable(feature = "path_ext", since = "1.5.0")]
1843 pub fn read_link(&self) -> io::Result<PathBuf> {
1847 /// Returns an iterator over the entries within a directory.
1849 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1850 /// be encountered after an iterator is initially constructed.
1852 /// This is an alias to [`fs::read_dir`].
1854 /// [`fs::read_dir`]: ../fs/fn.read_dir.html
1855 #[stable(feature = "path_ext", since = "1.5.0")]
1856 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
1860 /// Returns whether the path points at an existing entity.
1862 /// This function will traverse symbolic links to query information about the
1863 /// destination file. In case of broken symbolic links this will return `false`.
1868 /// use std::path::Path;
1869 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
1871 #[stable(feature = "path_ext", since = "1.5.0")]
1872 pub fn exists(&self) -> bool {
1873 fs::metadata(self).is_ok()
1876 /// Returns whether the path is pointing at a regular file.
1878 /// This function will traverse symbolic links to query information about the
1879 /// destination file. In case of broken symbolic links this will return `false`.
1884 /// use std::path::Path;
1885 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
1886 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
1888 #[stable(feature = "path_ext", since = "1.5.0")]
1889 pub fn is_file(&self) -> bool {
1890 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
1893 /// Returns whether the path is pointing at a directory.
1895 /// This function will traverse symbolic links to query information about the
1896 /// destination file. In case of broken symbolic links this will return `false`.
1901 /// use std::path::Path;
1902 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
1903 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
1905 #[stable(feature = "path_ext", since = "1.5.0")]
1906 pub fn is_dir(&self) -> bool {
1907 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 impl AsRef<OsStr> for Path {
1913 fn as_ref(&self) -> &OsStr {
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl fmt::Debug for Path {
1920 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1921 self.inner.fmt(formatter)
1925 /// Helper struct for safely printing paths with `format!()` and `{}`
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 pub struct Display<'a> {
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl<'a> fmt::Debug for Display<'a> {
1933 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1934 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 impl<'a> fmt::Display for Display<'a> {
1940 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1941 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl cmp::PartialEq for Path {
1947 fn eq(&self, other: &Path) -> bool {
1948 self.components().eq(other.components())
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 impl Hash for Path {
1954 fn hash<H: Hasher>(&self, h: &mut H) {
1955 for component in self.components() {
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 impl cmp::Eq for Path {}
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl cmp::PartialOrd for Path {
1966 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1967 self.components().partial_cmp(other.components())
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 impl cmp::Ord for Path {
1973 fn cmp(&self, other: &Path) -> cmp::Ordering {
1974 self.components().cmp(other.components())
1978 #[stable(feature = "rust1", since = "1.0.0")]
1979 impl AsRef<Path> for Path {
1980 fn as_ref(&self) -> &Path {
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 impl AsRef<Path> for OsStr {
1987 fn as_ref(&self) -> &Path {
1992 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
1993 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
1994 fn as_ref(&self) -> &Path {
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl AsRef<Path> for OsString {
2001 fn as_ref(&self) -> &Path {
2006 #[stable(feature = "rust1", since = "1.0.0")]
2007 impl AsRef<Path> for str {
2008 fn as_ref(&self) -> &Path {
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl AsRef<Path> for String {
2015 fn as_ref(&self) -> &Path {
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 impl AsRef<Path> for PathBuf {
2022 fn as_ref(&self) -> &Path {
2027 #[stable(feature = "path_into_iter", since = "1.6.0")]
2028 impl<'a> IntoIterator for &'a PathBuf {
2029 type Item = &'a OsStr;
2030 type IntoIter = Iter<'a>;
2031 fn into_iter(self) -> Iter<'a> { self.iter() }
2034 #[stable(feature = "path_into_iter", since = "1.6.0")]
2035 impl<'a> IntoIterator for &'a Path {
2036 type Item = &'a OsStr;
2037 type IntoIter = Iter<'a>;
2038 fn into_iter(self) -> Iter<'a> { self.iter() }
2041 macro_rules! impl_cmp {
2042 ($lhs:ty, $rhs: ty) => {
2043 #[stable(feature = "partialeq_path", since = "1.6.0")]
2044 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2046 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2049 #[stable(feature = "partialeq_path", since = "1.6.0")]
2050 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2052 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2055 #[stable(feature = "cmp_path", since = "1.8.0")]
2056 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2058 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2059 <Path as PartialOrd>::partial_cmp(self, other)
2063 #[stable(feature = "cmp_path", since = "1.8.0")]
2064 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2066 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2067 <Path as PartialOrd>::partial_cmp(self, other)
2073 impl_cmp!(PathBuf, Path);
2074 impl_cmp!(PathBuf, &'a Path);
2075 impl_cmp!(Cow<'a, Path>, Path);
2076 impl_cmp!(Cow<'a, Path>, &'b Path);
2077 impl_cmp!(Cow<'a, Path>, PathBuf);
2079 macro_rules! impl_cmp_os_str {
2080 ($lhs:ty, $rhs: ty) => {
2081 #[stable(feature = "cmp_path", since = "1.8.0")]
2082 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2084 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2087 #[stable(feature = "cmp_path", since = "1.8.0")]
2088 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2090 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2093 #[stable(feature = "cmp_path", since = "1.8.0")]
2094 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2096 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2097 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2101 #[stable(feature = "cmp_path", since = "1.8.0")]
2102 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2104 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2105 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2111 impl_cmp_os_str!(PathBuf, OsStr);
2112 impl_cmp_os_str!(PathBuf, &'a OsStr);
2113 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2114 impl_cmp_os_str!(PathBuf, OsString);
2115 impl_cmp_os_str!(Path, OsStr);
2116 impl_cmp_os_str!(Path, &'a OsStr);
2117 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2118 impl_cmp_os_str!(Path, OsString);
2119 impl_cmp_os_str!(&'a Path, OsStr);
2120 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2121 impl_cmp_os_str!(&'a Path, OsString);
2122 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2123 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2124 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2126 #[stable(since = "1.7.0", feature = "strip_prefix")]
2127 impl fmt::Display for StripPrefixError {
2128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2129 self.description().fmt(f)
2133 #[stable(since = "1.7.0", feature = "strip_prefix")]
2134 impl Error for StripPrefixError {
2135 fn description(&self) -> &str { "prefix not found" }
2141 use string::{ToString, String};
2145 ($path:expr, iter: $iter:expr) => (
2147 let path = Path::new($path);
2149 // Forward iteration
2150 let comps = path.iter()
2151 .map(|p| p.to_string_lossy().into_owned())
2152 .collect::<Vec<String>>();
2153 let exp: &[&str] = &$iter;
2154 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2155 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2158 // Reverse iteration
2159 let comps = Path::new($path).iter().rev()
2160 .map(|p| p.to_string_lossy().into_owned())
2161 .collect::<Vec<String>>();
2162 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2163 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2168 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2170 let path = Path::new($path);
2172 let act_root = path.has_root();
2173 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2174 $has_root, act_root);
2176 let act_abs = path.is_absolute();
2177 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2178 $is_absolute, act_abs);
2182 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2184 let path = Path::new($path);
2186 let parent = path.parent().map(|p| p.to_str().unwrap());
2187 let exp_parent: Option<&str> = $parent;
2188 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2189 exp_parent, parent);
2191 let file = path.file_name().map(|p| p.to_str().unwrap());
2192 let exp_file: Option<&str> = $file;
2193 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2198 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2200 let path = Path::new($path);
2202 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2203 let exp_stem: Option<&str> = $file_stem;
2204 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2207 let ext = path.extension().map(|p| p.to_str().unwrap());
2208 let exp_ext: Option<&str> = $extension;
2209 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2214 ($path:expr, iter: $iter:expr,
2215 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2216 parent: $parent:expr, file_name: $file:expr,
2217 file_stem: $file_stem:expr, extension: $extension:expr) => (
2219 t!($path, iter: $iter);
2220 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2221 t!($path, parent: $parent, file_name: $file);
2222 t!($path, file_stem: $file_stem, extension: $extension);
2231 let static_path = Path::new("/home/foo");
2232 let static_cow_path: Cow<'static, Path> = static_path.into();
2233 let pathbuf = PathBuf::from("/home/foo");
2236 let path: &Path = &pathbuf;
2237 let borrowed_cow_path: Cow<Path> = path.into();
2239 assert_eq!(static_cow_path, borrowed_cow_path);
2242 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2244 assert_eq!(static_cow_path, owned_cow_path);
2249 pub fn test_decompositions_unix() {
2265 file_name: Some("foo"),
2266 file_stem: Some("foo"),
2285 file_name: Some("foo"),
2286 file_stem: Some("foo"),
2295 file_name: Some("foo"),
2296 file_stem: Some("foo"),
2305 file_name: Some("foo"),
2306 file_stem: Some("foo"),
2311 iter: ["foo", "bar"],
2314 parent: Some("foo"),
2315 file_name: Some("bar"),
2316 file_stem: Some("bar"),
2321 iter: ["/", "foo", "bar"],
2324 parent: Some("/foo"),
2325 file_name: Some("bar"),
2326 file_stem: Some("bar"),
2335 file_name: Some("foo"),
2336 file_stem: Some("foo"),
2341 iter: ["/", "foo", "bar"],
2344 parent: Some("///foo"),
2345 file_name: Some("bar"),
2346 file_stem: Some("bar"),
2385 file_name: Some("foo"),
2386 file_stem: Some("foo"),
2391 iter: ["foo", ".."],
2394 parent: Some("foo"),
2405 file_name: Some("foo"),
2406 file_stem: Some("foo"),
2411 iter: ["foo", "bar"],
2414 parent: Some("foo"),
2415 file_name: Some("bar"),
2416 file_stem: Some("bar"),
2421 iter: ["foo", ".."],
2424 parent: Some("foo"),
2431 iter: ["foo", "..", "bar"],
2434 parent: Some("foo/.."),
2435 file_name: Some("bar"),
2436 file_stem: Some("bar"),
2445 file_name: Some("a"),
2446 file_stem: Some("a"),
2475 file_name: Some("b"),
2476 file_stem: Some("b"),
2485 file_name: Some("b"),
2486 file_stem: Some("b"),
2495 file_name: Some("b"),
2496 file_stem: Some("b"),
2501 iter: ["a", "b", "c"],
2504 parent: Some("a/b"),
2505 file_name: Some("c"),
2506 file_stem: Some("c"),
2515 file_name: Some(".foo"),
2516 file_stem: Some(".foo"),
2523 pub fn test_decompositions_windows() {
2539 file_name: Some("foo"),
2540 file_stem: Some("foo"),
2595 iter: ["\\", "foo"],
2599 file_name: Some("foo"),
2600 file_stem: Some("foo"),
2609 file_name: Some("foo"),
2610 file_stem: Some("foo"),
2615 iter: ["\\", "foo"],
2619 file_name: Some("foo"),
2620 file_stem: Some("foo"),
2625 iter: ["foo", "bar"],
2628 parent: Some("foo"),
2629 file_name: Some("bar"),
2630 file_stem: Some("bar"),
2635 iter: ["\\", "foo", "bar"],
2638 parent: Some("/foo"),
2639 file_name: Some("bar"),
2640 file_stem: Some("bar"),
2645 iter: ["\\", "foo"],
2649 file_name: Some("foo"),
2650 file_stem: Some("foo"),
2655 iter: ["\\", "foo", "bar"],
2658 parent: Some("///foo"),
2659 file_name: Some("bar"),
2660 file_stem: Some("bar"),
2699 file_name: Some("foo"),
2700 file_stem: Some("foo"),
2705 iter: ["foo", ".."],
2708 parent: Some("foo"),
2719 file_name: Some("foo"),
2720 file_stem: Some("foo"),
2725 iter: ["foo", "bar"],
2728 parent: Some("foo"),
2729 file_name: Some("bar"),
2730 file_stem: Some("bar"),
2735 iter: ["foo", ".."],
2738 parent: Some("foo"),
2745 iter: ["foo", "..", "bar"],
2748 parent: Some("foo/.."),
2749 file_name: Some("bar"),
2750 file_stem: Some("bar"),
2759 file_name: Some("a"),
2760 file_stem: Some("a"),
2789 file_name: Some("b"),
2790 file_stem: Some("b"),
2799 file_name: Some("b"),
2800 file_stem: Some("b"),
2809 file_name: Some("b"),
2810 file_stem: Some("b"),
2815 iter: ["a", "b", "c"],
2818 parent: Some("a/b"),
2819 file_name: Some("c"),
2820 file_stem: Some("c"),
2824 iter: ["a", "b", "c"],
2827 parent: Some("a\\b"),
2828 file_name: Some("c"),
2829 file_stem: Some("c"),
2838 file_name: Some("a"),
2839 file_stem: Some("a"),
2844 iter: ["c:", "\\", "foo.txt"],
2847 parent: Some("c:\\"),
2848 file_name: Some("foo.txt"),
2849 file_stem: Some("foo"),
2850 extension: Some("txt")
2853 t!("\\\\server\\share\\foo.txt",
2854 iter: ["\\\\server\\share", "\\", "foo.txt"],
2857 parent: Some("\\\\server\\share\\"),
2858 file_name: Some("foo.txt"),
2859 file_stem: Some("foo"),
2860 extension: Some("txt")
2863 t!("\\\\server\\share",
2864 iter: ["\\\\server\\share", "\\"],
2874 iter: ["\\", "server"],
2878 file_name: Some("server"),
2879 file_stem: Some("server"),
2883 t!("\\\\?\\bar\\foo.txt",
2884 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2887 parent: Some("\\\\?\\bar\\"),
2888 file_name: Some("foo.txt"),
2889 file_stem: Some("foo"),
2890 extension: Some("txt")
2894 iter: ["\\\\?\\bar"],
2913 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2914 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2917 parent: Some("\\\\?\\UNC\\server\\share\\"),
2918 file_name: Some("foo.txt"),
2919 file_stem: Some("foo"),
2920 extension: Some("txt")
2923 t!("\\\\?\\UNC\\server",
2924 iter: ["\\\\?\\UNC\\server"],
2934 iter: ["\\\\?\\UNC\\"],
2943 t!("\\\\?\\C:\\foo.txt",
2944 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2947 parent: Some("\\\\?\\C:\\"),
2948 file_name: Some("foo.txt"),
2949 file_stem: Some("foo"),
2950 extension: Some("txt")
2955 iter: ["\\\\?\\C:", "\\"],
2966 iter: ["\\\\?\\C:"],
2976 t!("\\\\?\\foo/bar",
2977 iter: ["\\\\?\\foo/bar"],
2988 iter: ["\\\\?\\C:/foo"],
2998 t!("\\\\.\\foo\\bar",
2999 iter: ["\\\\.\\foo", "\\", "bar"],
3002 parent: Some("\\\\.\\foo\\"),
3003 file_name: Some("bar"),
3004 file_stem: Some("bar"),
3010 iter: ["\\\\.\\foo", "\\"],
3020 t!("\\\\.\\foo/bar",
3021 iter: ["\\\\.\\foo/bar", "\\"],
3031 t!("\\\\.\\foo\\bar/baz",
3032 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3035 parent: Some("\\\\.\\foo\\bar"),
3036 file_name: Some("baz"),
3037 file_stem: Some("baz"),
3043 iter: ["\\\\.\\", "\\"],
3053 iter: ["\\\\?\\a", "\\", "b"],
3056 parent: Some("\\\\?\\a\\"),
3057 file_name: Some("b"),
3058 file_stem: Some("b"),
3064 pub fn test_stem_ext() {
3066 file_stem: Some("foo"),
3071 file_stem: Some("foo"),
3076 file_stem: Some(".foo"),
3081 file_stem: Some("foo"),
3082 extension: Some("txt")
3086 file_stem: Some("foo.bar"),
3087 extension: Some("txt")
3091 file_stem: Some("foo.bar"),
3112 pub fn test_push() {
3114 ($path:expr, $push:expr, $expected:expr) => ( {
3115 let mut actual = PathBuf::from($path);
3117 assert!(actual.to_str() == Some($expected),
3118 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3119 $push, $path, $expected, actual.to_str().unwrap());
3124 tp!("", "foo", "foo");
3125 tp!("foo", "bar", "foo/bar");
3126 tp!("foo/", "bar", "foo/bar");
3127 tp!("foo//", "bar", "foo//bar");
3128 tp!("foo/.", "bar", "foo/./bar");
3129 tp!("foo./.", "bar", "foo././bar");
3130 tp!("foo", "", "foo/");
3131 tp!("foo", ".", "foo/.");
3132 tp!("foo", "..", "foo/..");
3133 tp!("foo", "/", "/");
3134 tp!("/foo/bar", "/", "/");
3135 tp!("/foo/bar", "/baz", "/baz");
3136 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3138 tp!("", "foo", "foo");
3139 tp!("foo", "bar", r"foo\bar");
3140 tp!("foo/", "bar", r"foo/bar");
3141 tp!(r"foo\", "bar", r"foo\bar");
3142 tp!("foo//", "bar", r"foo//bar");
3143 tp!(r"foo\\", "bar", r"foo\\bar");
3144 tp!("foo/.", "bar", r"foo/.\bar");
3145 tp!("foo./.", "bar", r"foo./.\bar");
3146 tp!(r"foo\.", "bar", r"foo\.\bar");
3147 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3148 tp!("foo", "", "foo\\");
3149 tp!("foo", ".", r"foo\.");
3150 tp!("foo", "..", r"foo\..");
3151 tp!("foo", "/", "/");
3152 tp!("foo", r"\", r"\");
3153 tp!("/foo/bar", "/", "/");
3154 tp!(r"\foo\bar", r"\", r"\");
3155 tp!("/foo/bar", "/baz", "/baz");
3156 tp!("/foo/bar", r"\baz", r"\baz");
3157 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3158 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3160 tp!("c:\\", "windows", "c:\\windows");
3161 tp!("c:", "windows", "c:windows");
3163 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3164 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3165 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3166 tp!("a\\b", "\\c\\d", "\\c\\d");
3167 tp!("a\\b", ".", "a\\b\\.");
3168 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3169 tp!("a\\b", "C:a.txt", "C:a.txt");
3170 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3171 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3172 tp!("C:\\a\\b\\c", "C:d", "C:d");
3173 tp!("C:a\\b\\c", "C:d", "C:d");
3174 tp!("C:", r"a\b\c", r"C:a\b\c");
3175 tp!("C:", r"..\a", r"C:..\a");
3176 tp!("\\\\server\\share\\foo",
3178 "\\\\server\\share\\foo\\bar");
3179 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3180 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3181 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3182 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3183 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3184 tp!("\\\\?\\UNC\\server\\share\\foo",
3186 "\\\\?\\UNC\\server\\share\\foo\\bar");
3187 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3188 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3190 // Note: modified from old path API
3191 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3194 "\\\\?\\UNC\\server\\share",
3195 "\\\\?\\UNC\\server\\share");
3196 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3197 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3198 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3199 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3201 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3208 ($path:expr, $expected:expr, $output:expr) => ( {
3209 let mut actual = PathBuf::from($path);
3210 let output = actual.pop();
3211 assert!(actual.to_str() == Some($expected) && output == $output,
3212 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3213 $path, $expected, $output,
3214 actual.to_str().unwrap(), output);
3219 tp!("/", "/", false);
3220 tp!("foo", "", true);
3222 tp!("/foo", "/", true);
3223 tp!("/foo/bar", "/foo", true);
3224 tp!("foo/bar", "foo", true);
3225 tp!("foo/.", "", true);
3226 tp!("foo//bar", "foo", true);
3229 tp!("a\\b\\c", "a\\b", true);
3230 tp!("\\a", "\\", true);
3231 tp!("\\", "\\", false);
3233 tp!("C:\\a\\b", "C:\\a", true);
3234 tp!("C:\\a", "C:\\", true);
3235 tp!("C:\\", "C:\\", false);
3236 tp!("C:a\\b", "C:a", true);
3237 tp!("C:a", "C:", true);
3238 tp!("C:", "C:", false);
3239 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3240 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3241 tp!("\\\\server\\share", "\\\\server\\share", false);
3242 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3243 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3244 tp!("\\\\?\\a", "\\\\?\\a", false);
3245 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3246 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3247 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3248 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3249 "\\\\?\\UNC\\server\\share\\a",
3251 tp!("\\\\?\\UNC\\server\\share\\a",
3252 "\\\\?\\UNC\\server\\share\\",
3254 tp!("\\\\?\\UNC\\server\\share",
3255 "\\\\?\\UNC\\server\\share",
3257 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3258 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3259 tp!("\\\\.\\a", "\\\\.\\a", false);
3261 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3266 pub fn test_set_file_name() {
3268 ($path:expr, $file:expr, $expected:expr) => ( {
3269 let mut p = PathBuf::from($path);
3270 p.set_file_name($file);
3271 assert!(p.to_str() == Some($expected),
3272 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3273 $path, $file, $expected,
3274 p.to_str().unwrap());
3278 tfn!("foo", "foo", "foo");
3279 tfn!("foo", "bar", "bar");
3280 tfn!("foo", "", "");
3281 tfn!("", "foo", "foo");
3283 tfn!(".", "foo", "./foo");
3284 tfn!("foo/", "bar", "bar");
3285 tfn!("foo/.", "bar", "bar");
3286 tfn!("..", "foo", "../foo");
3287 tfn!("foo/..", "bar", "foo/../bar");
3288 tfn!("/", "foo", "/foo");
3290 tfn!(".", "foo", r".\foo");
3291 tfn!(r"foo\", "bar", r"bar");
3292 tfn!(r"foo\.", "bar", r"bar");
3293 tfn!("..", "foo", r"..\foo");
3294 tfn!(r"foo\..", "bar", r"foo\..\bar");
3295 tfn!(r"\", "foo", r"\foo");
3300 pub fn test_set_extension() {
3302 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3303 let mut p = PathBuf::from($path);
3304 let output = p.set_extension($ext);
3305 assert!(p.to_str() == Some($expected) && output == $output,
3306 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3307 $path, $ext, $expected, $output,
3308 p.to_str().unwrap(), output);
3312 tfe!("foo", "txt", "foo.txt", true);
3313 tfe!("foo.bar", "txt", "foo.txt", true);
3314 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3315 tfe!(".test", "txt", ".test.txt", true);
3316 tfe!("foo.txt", "", "foo", true);
3317 tfe!("foo", "", "foo", true);
3318 tfe!("", "foo", "", false);
3319 tfe!(".", "foo", ".", false);
3320 tfe!("foo/", "bar", "foo.bar", true);
3321 tfe!("foo/.", "bar", "foo.bar", true);
3322 tfe!("..", "foo", "..", false);
3323 tfe!("foo/..", "bar", "foo/..", false);
3324 tfe!("/", "foo", "/", false);
3328 fn test_eq_recievers() {
3331 let borrowed: &Path = Path::new("foo/bar");
3332 let mut owned: PathBuf = PathBuf::new();
3335 let borrowed_cow: Cow<Path> = borrowed.into();
3336 let owned_cow: Cow<Path> = owned.clone().into();
3339 ($($current:expr),+) => {
3341 assert_eq!($current, borrowed);
3342 assert_eq!($current, owned);
3343 assert_eq!($current, borrowed_cow);
3344 assert_eq!($current, owned_cow);
3349 t!(borrowed, owned, borrowed_cow, owned_cow);
3353 pub fn test_compare() {
3354 use hash::{Hash, Hasher, SipHasher};
3356 fn hash<T: Hash>(t: T) -> u64 {
3357 let mut s = SipHasher::new_with_keys(0, 0);
3363 ($path1:expr, $path2:expr, eq: $eq:expr,
3364 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3365 relative_from: $relative_from:expr) => ({
3366 let path1 = Path::new($path1);
3367 let path2 = Path::new($path2);
3369 let eq = path1 == path2;
3370 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3371 $path1, $path2, $eq, eq);
3372 assert!($eq == (hash(path1) == hash(path2)),
3373 "{:?} == {:?}, expected {:?}, got {} and {}",
3374 $path1, $path2, $eq, hash(path1), hash(path2));
3376 let starts_with = path1.starts_with(path2);
3377 assert!(starts_with == $starts_with,
3378 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3379 $starts_with, starts_with);
3381 let ends_with = path1.ends_with(path2);
3382 assert!(ends_with == $ends_with,
3383 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3384 $ends_with, ends_with);
3386 let relative_from = path1.strip_prefix(path2)
3387 .map(|p| p.to_str().unwrap())
3389 let exp: Option<&str> = $relative_from;
3390 assert!(relative_from == exp,
3391 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3392 $path1, $path2, exp, relative_from);
3400 relative_from: Some("")
3407 relative_from: Some("foo")
3421 relative_from: Some("")
3428 relative_from: Some("")
3431 tc!("foo/bar", "foo",
3435 relative_from: Some("bar")
3438 tc!("foo/bar/baz", "foo/bar",
3442 relative_from: Some("baz")
3445 tc!("foo/bar", "foo/bar/baz",
3452 tc!("./foo/bar/", ".",
3456 relative_from: Some("foo/bar")
3460 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3461 r"c:\src\rust\cargo-test\test",
3465 relative_from: Some("Cargo.toml")
3468 tc!(r"c:\foo", r"C:\foo",
3472 relative_from: Some("")