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.
528 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
529 #[stable(feature = "rust1", since = "1.0.0")]
530 pub enum Component<'a> {
531 /// A Windows path prefix, e.g. `C:` or `\server\share`.
533 /// Does not occur on Unix.
534 #[stable(feature = "rust1", since = "1.0.0")]
536 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
539 /// The root directory component, appears after any prefix and before anything else
540 #[stable(feature = "rust1", since = "1.0.0")]
543 /// A reference to the current directory, i.e. `.`
544 #[stable(feature = "rust1", since = "1.0.0")]
547 /// A reference to the parent directory, i.e. `..`
548 #[stable(feature = "rust1", since = "1.0.0")]
551 /// A normal component, i.e. `a` and `b` in `a/b`
552 #[stable(feature = "rust1", since = "1.0.0")]
553 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
556 impl<'a> Component<'a> {
557 /// Extracts the underlying `OsStr` slice
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn as_os_str(self) -> &'a OsStr {
561 Component::Prefix(p) => p.as_os_str(),
562 Component::RootDir => OsStr::new(MAIN_SEP_STR),
563 Component::CurDir => OsStr::new("."),
564 Component::ParentDir => OsStr::new(".."),
565 Component::Normal(path) => path,
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl<'a> AsRef<OsStr> for Component<'a> {
572 fn as_ref(&self) -> &OsStr {
577 /// The core iterator giving the components of a path.
579 /// See the module documentation for an in-depth explanation of components and
580 /// their role in the API.
585 /// use std::path::Path;
587 /// let path = Path::new("/tmp/foo/bar.txt");
589 /// for component in path.components() {
590 /// println!("{:?}", component);
594 #[stable(feature = "rust1", since = "1.0.0")]
595 pub struct Components<'a> {
596 // The path left to parse components from
599 // The prefix as it was originally parsed, if any
600 prefix: Option<Prefix<'a>>,
602 // true if path *physically* has a root separator; for most Windows
603 // prefixes, it may have a "logical" rootseparator for the purposes of
604 // normalization, e.g. \\server\share == \\server\share\.
605 has_physical_root: bool,
607 // The iterator is double-ended, and these two states keep track of what has
608 // been produced from either end
613 /// An iterator over the components of a path, as `OsStr` slices.
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub struct Iter<'a> {
617 inner: Components<'a>,
620 impl<'a> Components<'a> {
621 // how long is the prefix, if any?
623 fn prefix_len(&self) -> usize {
624 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
628 fn prefix_verbatim(&self) -> bool {
629 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
632 /// how much of the prefix is left from the point of view of iteration?
634 fn prefix_remaining(&self) -> usize {
635 if self.front == State::Prefix {
642 // Given the iteration so far, how much of the pre-State::Body path is left?
644 fn len_before_body(&self) -> usize {
645 let root = if self.front <= State::StartDir && self.has_physical_root {
650 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
655 self.prefix_remaining() + root + cur_dir
658 // is the iteration complete?
660 fn finished(&self) -> bool {
661 self.front == State::Done || self.back == State::Done || self.front > self.back
665 fn is_sep_byte(&self, b: u8) -> bool {
666 if self.prefix_verbatim() {
673 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
678 /// use std::path::Path;
680 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
681 /// components.next();
682 /// components.next();
684 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn as_path(&self) -> &'a Path {
688 let mut comps = self.clone();
689 if comps.front == State::Body {
692 if comps.back == State::Body {
695 unsafe { Path::from_u8_slice(comps.path) }
698 /// Is the *original* path rooted?
699 fn has_root(&self) -> bool {
700 if self.has_physical_root {
703 if let Some(p) = self.prefix {
704 if p.has_implicit_root() {
711 /// Should the normalized path include a leading . ?
712 fn include_cur_dir(&self) -> bool {
716 let mut iter = self.path[self.prefix_len()..].iter();
717 match (iter.next(), iter.next()) {
718 (Some(&b'.'), None) => true,
719 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
724 // parse a given byte sequence into the corresponding path component
725 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
727 b"." if self.prefix_verbatim() => Some(Component::CurDir),
728 b"." => None, // . components are normalized away, except at
729 // the beginning of a path, which is treated
730 // separately via `include_cur_dir`
731 b".." => Some(Component::ParentDir),
733 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
737 // parse a component from the left, saying how many bytes to consume to
738 // remove the component
739 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
740 debug_assert!(self.front == State::Body);
741 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
742 None => (0, self.path),
743 Some(i) => (1, &self.path[..i]),
745 (comp.len() + extra, self.parse_single_component(comp))
748 // parse a component from the right, saying how many bytes to consume to
749 // remove the component
750 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
751 debug_assert!(self.back == State::Body);
752 let start = self.len_before_body();
753 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
754 None => (0, &self.path[start..]),
755 Some(i) => (1, &self.path[start + i + 1..]),
757 (comp.len() + extra, self.parse_single_component(comp))
760 // trim away repeated separators (i.e. empty components) on the left
761 fn trim_left(&mut self) {
762 while !self.path.is_empty() {
763 let (size, comp) = self.parse_next_component();
767 self.path = &self.path[size..];
772 // trim away repeated separators (i.e. empty components) on the right
773 fn trim_right(&mut self) {
774 while self.path.len() > self.len_before_body() {
775 let (size, comp) = self.parse_next_component_back();
779 self.path = &self.path[..self.path.len() - size];
785 #[stable(feature = "rust1", since = "1.0.0")]
786 impl<'a> AsRef<Path> for Components<'a> {
787 fn as_ref(&self) -> &Path {
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<'a> AsRef<OsStr> for Components<'a> {
794 fn as_ref(&self) -> &OsStr {
795 self.as_path().as_os_str()
800 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn as_path(&self) -> &'a Path {
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<'a> AsRef<Path> for Iter<'a> {
809 fn as_ref(&self) -> &Path {
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a> AsRef<OsStr> for Iter<'a> {
816 fn as_ref(&self) -> &OsStr {
817 self.as_path().as_os_str()
821 #[stable(feature = "rust1", since = "1.0.0")]
822 impl<'a> Iterator for Iter<'a> {
823 type Item = &'a OsStr;
825 fn next(&mut self) -> Option<&'a OsStr> {
826 self.inner.next().map(Component::as_os_str)
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl<'a> DoubleEndedIterator for Iter<'a> {
832 fn next_back(&mut self) -> Option<&'a OsStr> {
833 self.inner.next_back().map(Component::as_os_str)
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl<'a> Iterator for Components<'a> {
839 type Item = Component<'a>;
841 fn next(&mut self) -> Option<Component<'a>> {
842 while !self.finished() {
844 State::Prefix if self.prefix_len() > 0 => {
845 self.front = State::StartDir;
846 debug_assert!(self.prefix_len() <= self.path.len());
847 let raw = &self.path[..self.prefix_len()];
848 self.path = &self.path[self.prefix_len()..];
849 return Some(Component::Prefix(PrefixComponent {
850 raw: unsafe { u8_slice_as_os_str(raw) },
851 parsed: self.prefix.unwrap(),
855 self.front = State::StartDir;
858 self.front = State::Body;
859 if self.has_physical_root {
860 debug_assert!(!self.path.is_empty());
861 self.path = &self.path[1..];
862 return Some(Component::RootDir);
863 } else if let Some(p) = self.prefix {
864 if p.has_implicit_root() && !p.is_verbatim() {
865 return Some(Component::RootDir);
867 } else if self.include_cur_dir() {
868 debug_assert!(!self.path.is_empty());
869 self.path = &self.path[1..];
870 return Some(Component::CurDir);
873 State::Body if !self.path.is_empty() => {
874 let (size, comp) = self.parse_next_component();
875 self.path = &self.path[size..];
881 self.front = State::Done;
883 State::Done => unreachable!(),
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl<'a> DoubleEndedIterator for Components<'a> {
892 fn next_back(&mut self) -> Option<Component<'a>> {
893 while !self.finished() {
895 State::Body if self.path.len() > self.len_before_body() => {
896 let (size, comp) = self.parse_next_component_back();
897 self.path = &self.path[..self.path.len() - size];
903 self.back = State::StartDir;
906 self.back = State::Prefix;
907 if self.has_physical_root {
908 self.path = &self.path[..self.path.len() - 1];
909 return Some(Component::RootDir);
910 } else if let Some(p) = self.prefix {
911 if p.has_implicit_root() && !p.is_verbatim() {
912 return Some(Component::RootDir);
914 } else if self.include_cur_dir() {
915 self.path = &self.path[..self.path.len() - 1];
916 return Some(Component::CurDir);
919 State::Prefix if self.prefix_len() > 0 => {
920 self.back = State::Done;
921 return Some(Component::Prefix(PrefixComponent {
922 raw: unsafe { u8_slice_as_os_str(self.path) },
923 parsed: self.prefix.unwrap(),
927 self.back = State::Done;
930 State::Done => unreachable!(),
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a> cmp::PartialEq for Components<'a> {
939 fn eq(&self, other: &Components<'a>) -> bool {
940 Iterator::eq(self.clone(), other.clone())
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl<'a> cmp::Eq for Components<'a> {}
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<'a> cmp::PartialOrd for Components<'a> {
949 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
950 Iterator::partial_cmp(self.clone(), other.clone())
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl<'a> cmp::Ord for Components<'a> {
956 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
957 Iterator::cmp(self.clone(), other.clone())
961 ////////////////////////////////////////////////////////////////////////////////
962 // Basic types and traits
963 ////////////////////////////////////////////////////////////////////////////////
965 /// An owned, mutable path (akin to `String`).
967 /// This type provides methods like `push` and `set_extension` that mutate the
968 /// path in place. It also implements `Deref` to `Path`, meaning that all
969 /// methods on `Path` slices are available on `PathBuf` values as well.
971 /// More details about the overall approach can be found in
972 /// the module documentation.
977 /// use std::path::PathBuf;
979 /// let mut path = PathBuf::from("c:\\");
980 /// path.push("windows");
981 /// path.push("system32");
982 /// path.set_extension("dll");
985 #[stable(feature = "rust1", since = "1.0.0")]
991 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
992 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
995 /// Allocates an empty `PathBuf`.
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn new() -> PathBuf {
998 PathBuf { inner: OsString::new() }
1001 /// Coerces to a `Path` slice.
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub fn as_path(&self) -> &Path {
1007 /// Extends `self` with `path`.
1009 /// If `path` is absolute, it replaces the current path.
1013 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1014 /// replaces everything except for the prefix (if any) of `self`.
1015 /// * if `path` has a prefix but no root, it replaces `self`.
1020 /// use std::path::PathBuf;
1022 /// let mut path = PathBuf::new();
1023 /// path.push("/tmp");
1024 /// path.push("file.bk");
1025 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1027 /// // Pushing an absolute path replaces the current path
1028 /// path.push("/etc/passwd");
1029 /// assert_eq!(path, PathBuf::from("/etc/passwd"));
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1033 self._push(path.as_ref())
1036 #[allow(deprecated)]
1037 fn _push(&mut self, path: &Path) {
1038 // in general, a separator is needed if the rightmost byte is not a separator
1039 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1041 // in the special case of `C:` on Windows, do *not* add a separator
1043 let comps = self.components();
1044 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1045 comps.prefix.unwrap().is_drive() {
1050 // absolute `path` replaces `self`
1051 if path.is_absolute() || path.prefix().is_some() {
1052 self.as_mut_vec().truncate(0);
1054 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1055 } else if path.has_root() {
1056 let prefix_len = self.components().prefix_remaining();
1057 self.as_mut_vec().truncate(prefix_len);
1059 // `path` is a pure relative path
1060 } else if need_sep {
1061 self.inner.push(MAIN_SEP_STR);
1064 self.inner.push(path);
1067 /// Truncate `self` to `self.parent()`.
1069 /// Returns false and does nothing if `self.file_name()` is `None`.
1070 /// Otherwise, returns `true`.
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 pub fn pop(&mut self) -> bool {
1073 match self.parent().map(|p| p.as_u8_slice().len()) {
1075 self.as_mut_vec().truncate(len);
1082 /// Updates `self.file_name()` to `file_name`.
1084 /// If `self.file_name()` was `None`, this is equivalent to pushing
1090 /// use std::path::PathBuf;
1092 /// let mut buf = PathBuf::from("/");
1093 /// assert!(buf.file_name() == None);
1094 /// buf.set_file_name("bar");
1095 /// assert!(buf == PathBuf::from("/bar"));
1096 /// assert!(buf.file_name().is_some());
1097 /// buf.set_file_name("baz.txt");
1098 /// assert!(buf == PathBuf::from("/baz.txt"));
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1102 self._set_file_name(file_name.as_ref())
1105 fn _set_file_name(&mut self, file_name: &OsStr) {
1106 if self.file_name().is_some() {
1107 let popped = self.pop();
1108 debug_assert!(popped);
1110 self.push(file_name);
1113 /// Updates `self.extension()` to `extension`.
1115 /// If `self.file_name()` is `None`, does nothing and returns `false`.
1117 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
1118 /// is added; otherwise it is replaced.
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1121 self._set_extension(extension.as_ref())
1124 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1125 if self.file_name().is_none() {
1129 let mut stem = match self.file_stem() {
1130 Some(stem) => stem.to_os_string(),
1131 None => OsString::new(),
1134 if !os_str_as_u8_slice(extension).is_empty() {
1136 stem.push(extension);
1138 self.set_file_name(&stem);
1143 /// Consumes the `PathBuf`, yielding its internal `OsString` storage.
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn into_os_string(self) -> OsString {
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1152 fn from(s: &'a T) -> PathBuf {
1153 PathBuf::from(s.as_ref().to_os_string())
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 impl From<OsString> for PathBuf {
1159 fn from(s: OsString) -> PathBuf {
1160 PathBuf { inner: s }
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl From<String> for PathBuf {
1166 fn from(s: String) -> PathBuf {
1167 PathBuf::from(OsString::from(s))
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1173 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1174 let mut buf = PathBuf::new();
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1182 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1184 self.push(p.as_ref())
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl fmt::Debug for PathBuf {
1191 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1192 fmt::Debug::fmt(&**self, formatter)
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 impl ops::Deref for PathBuf {
1200 fn deref(&self) -> &Path {
1201 Path::new(&self.inner)
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl Borrow<Path> for PathBuf {
1207 fn borrow(&self) -> &Path {
1212 #[stable(feature = "cow_from_path", since = "1.6.0")]
1213 impl<'a> From<&'a Path> for Cow<'a, Path> {
1215 fn from(s: &'a Path) -> Cow<'a, Path> {
1220 #[stable(feature = "cow_from_path", since = "1.6.0")]
1221 impl<'a> From<PathBuf> for Cow<'a, Path> {
1223 fn from(s: PathBuf) -> Cow<'a, Path> {
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl ToOwned for Path {
1230 type Owned = PathBuf;
1231 fn to_owned(&self) -> PathBuf {
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl cmp::PartialEq for PathBuf {
1238 fn eq(&self, other: &PathBuf) -> bool {
1239 self.components() == other.components()
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl Hash for PathBuf {
1245 fn hash<H: Hasher>(&self, h: &mut H) {
1246 self.as_path().hash(h)
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl cmp::Eq for PathBuf {}
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 impl cmp::PartialOrd for PathBuf {
1255 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1256 self.components().partial_cmp(other.components())
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl cmp::Ord for PathBuf {
1262 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1263 self.components().cmp(other.components())
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 impl AsRef<OsStr> for PathBuf {
1269 fn as_ref(&self) -> &OsStr {
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl Into<OsString> for PathBuf {
1276 fn into(self) -> OsString {
1281 /// A slice of a path (akin to `str`).
1283 /// This type supports a number of operations for inspecting a path, including
1284 /// breaking the path into its components (separated by `/` or `\`, depending on
1285 /// the platform), extracting the file name, determining whether the path is
1286 /// absolute, and so on. More details about the overall approach can be found in
1287 /// the module documentation.
1289 /// This is an *unsized* type, meaning that it must always be used behind a
1290 /// pointer like `&` or `Box`.
1295 /// use std::path::Path;
1297 /// let path = Path::new("/tmp/foo/bar.txt");
1298 /// let file = path.file_name();
1299 /// let extension = path.extension();
1300 /// let parent_dir = path.parent();
1303 #[stable(feature = "rust1", since = "1.0.0")]
1308 /// An error returned from the `Path::strip_prefix` method indicating that the
1309 /// prefix was not found in `self`.
1310 #[derive(Debug, Clone, PartialEq, Eq)]
1311 #[stable(since = "1.7.0", feature = "strip_prefix")]
1312 pub struct StripPrefixError(());
1315 // The following (private!) function allows construction of a path from a u8
1316 // slice, which is only safe when it is known to follow the OsStr encoding.
1317 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1318 Path::new(u8_slice_as_os_str(s))
1320 // The following (private!) function reveals the byte encoding used for OsStr.
1321 fn as_u8_slice(&self) -> &[u8] {
1322 os_str_as_u8_slice(&self.inner)
1325 /// Directly wrap a string slice as a `Path` slice.
1327 /// This is a cost-free conversion.
1332 /// use std::path::Path;
1334 /// Path::new("foo.txt");
1337 /// You can create `Path`s from `String`s, or even other `Path`s:
1340 /// use std::path::Path;
1342 /// let string = String::from("foo.txt");
1343 /// let from_string = Path::new(&string);
1344 /// let from_path = Path::new(&from_string);
1345 /// assert_eq!(from_string, from_path);
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1349 unsafe { mem::transmute(s.as_ref()) }
1352 /// Yields the underlying `OsStr` slice.
1357 /// use std::path::Path;
1359 /// let os_str = Path::new("foo.txt").as_os_str();
1360 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 pub fn as_os_str(&self) -> &OsStr {
1367 /// Yields a `&str` slice if the `Path` is valid unicode.
1369 /// This conversion may entail doing a check for UTF-8 validity.
1374 /// use std::path::Path;
1376 /// let path_str = Path::new("foo.txt").to_str();
1377 /// assert_eq!(path_str, Some("foo.txt"));
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 pub fn to_str(&self) -> Option<&str> {
1384 /// Converts a `Path` to a `Cow<str>`.
1386 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1391 /// use std::path::Path;
1393 /// let path_str = Path::new("foo.txt").to_string_lossy();
1394 /// assert_eq!(path_str, "foo.txt");
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 pub fn to_string_lossy(&self) -> Cow<str> {
1398 self.inner.to_string_lossy()
1401 /// Converts a `Path` to an owned `PathBuf`.
1406 /// use std::path::Path;
1408 /// let path_buf = Path::new("foo.txt").to_path_buf();
1409 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 pub fn to_path_buf(&self) -> PathBuf {
1413 PathBuf::from(self.inner.to_os_string())
1416 /// A path is *absolute* if it is independent of the current directory.
1418 /// * On Unix, a path is absolute if it starts with the root, so
1419 /// `is_absolute` and `has_root` are equivalent.
1421 /// * On Windows, a path is absolute if it has a prefix and starts with the
1422 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1423 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1428 /// use std::path::Path;
1430 /// assert!(!Path::new("foo.txt").is_absolute());
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 #[allow(deprecated)]
1434 pub fn is_absolute(&self) -> bool {
1435 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1438 /// A path is *relative* if it is not absolute.
1443 /// use std::path::Path;
1445 /// assert!(Path::new("foo.txt").is_relative());
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub fn is_relative(&self) -> bool {
1452 fn prefix(&self) -> Option<Prefix> {
1453 self.components().prefix
1456 /// A path has a root if the body of the path begins with the directory separator.
1458 /// * On Unix, a path has a root if it begins with `/`.
1460 /// * On Windows, a path has a root if it:
1461 /// * has no prefix and begins with a separator, e.g. `\\windows`
1462 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1463 /// * has any non-disk prefix, e.g. `\\server\share`
1468 /// use std::path::Path;
1470 /// assert!(Path::new("/etc/passwd").has_root());
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn has_root(&self) -> bool {
1474 self.components().has_root()
1477 /// The path without its final component, if any.
1479 /// Returns `None` if the path terminates in a root or prefix.
1484 /// use std::path::Path;
1486 /// let path = Path::new("/foo/bar");
1487 /// let parent = path.parent().unwrap();
1488 /// assert_eq!(parent, Path::new("/foo"));
1490 /// let grand_parent = parent.parent().unwrap();
1491 /// assert_eq!(grand_parent, Path::new("/"));
1492 /// assert_eq!(grand_parent.parent(), None);
1494 #[stable(feature = "rust1", since = "1.0.0")]
1495 pub fn parent(&self) -> Option<&Path> {
1496 let mut comps = self.components();
1497 let comp = comps.next_back();
1500 Component::Normal(_) |
1502 Component::ParentDir => Some(comps.as_path()),
1508 /// The final component of the path, if it is a normal file.
1510 /// If the path terminates in `.`, `..`, or consists solely of a root of
1511 /// prefix, `file_name` will return `None`.
1516 /// use std::path::Path;
1517 /// use std::ffi::OsStr;
1519 /// let path = Path::new("foo.txt");
1520 /// let os_str = OsStr::new("foo.txt");
1522 /// assert_eq!(Some(os_str), path.file_name());
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 pub fn file_name(&self) -> Option<&OsStr> {
1526 self.components().next_back().and_then(|p| {
1528 Component::Normal(p) => Some(p.as_ref()),
1534 /// Returns a path that, when joined onto `base`, yields `self`.
1538 /// If `base` is not a prefix of `self` (i.e. `starts_with`
1539 /// returns `false`), returns `Err`.
1540 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1541 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1542 -> Result<&'a Path, StripPrefixError>
1543 where P: AsRef<Path>
1545 self._strip_prefix(base.as_ref())
1548 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1549 -> Result<&'a Path, StripPrefixError> {
1550 iter_after(self.components(), base.components())
1551 .map(|c| c.as_path())
1552 .ok_or(StripPrefixError(()))
1555 /// Determines whether `base` is a prefix of `self`.
1557 /// Only considers whole path components to match.
1562 /// use std::path::Path;
1564 /// let path = Path::new("/etc/passwd");
1566 /// assert!(path.starts_with("/etc"));
1568 /// assert!(!path.starts_with("/e"));
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1572 self._starts_with(base.as_ref())
1575 fn _starts_with(&self, base: &Path) -> bool {
1576 iter_after(self.components(), base.components()).is_some()
1579 /// Determines whether `child` is a suffix 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.ends_with("passwd"));
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1594 self._ends_with(child.as_ref())
1597 fn _ends_with(&self, child: &Path) -> bool {
1598 iter_after(self.components().rev(), child.components().rev()).is_some()
1601 /// Extracts the stem (non-extension) portion of `self.file_name()`.
1605 /// * None, if there is no file name;
1606 /// * The entire file name if there is no embedded `.`;
1607 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1608 /// * Otherwise, the portion of the file name before the final `.`
1613 /// use std::path::Path;
1615 /// let path = Path::new("foo.rs");
1617 /// assert_eq!("foo", path.file_stem().unwrap());
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 pub fn file_stem(&self) -> Option<&OsStr> {
1621 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1624 /// Extracts the extension of `self.file_name()`, if possible.
1626 /// The extension is:
1628 /// * None, if there is no file name;
1629 /// * None, if there is no embedded `.`;
1630 /// * None, if the file name begins with `.` and has no other `.`s within;
1631 /// * Otherwise, the portion of the file name after the final `.`
1636 /// use std::path::Path;
1638 /// let path = Path::new("foo.rs");
1640 /// assert_eq!("rs", path.extension().unwrap());
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 pub fn extension(&self) -> Option<&OsStr> {
1644 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1647 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1649 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1654 /// use std::path::{Path, PathBuf};
1656 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1658 #[stable(feature = "rust1", since = "1.0.0")]
1659 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1660 self._join(path.as_ref())
1663 fn _join(&self, path: &Path) -> PathBuf {
1664 let mut buf = self.to_path_buf();
1669 /// Creates an owned `PathBuf` like `self` but with the given file name.
1671 /// See `PathBuf::set_file_name` for more details.
1676 /// use std::path::{Path, PathBuf};
1678 /// let path = Path::new("/tmp/foo.txt");
1679 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1683 self._with_file_name(file_name.as_ref())
1686 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1687 let mut buf = self.to_path_buf();
1688 buf.set_file_name(file_name);
1692 /// Creates an owned `PathBuf` like `self` but with the given extension.
1694 /// See `PathBuf::set_extension` for more details.
1699 /// use std::path::{Path, PathBuf};
1701 /// let path = Path::new("foo.rs");
1702 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1706 self._with_extension(extension.as_ref())
1709 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1710 let mut buf = self.to_path_buf();
1711 buf.set_extension(extension);
1715 /// Produce an iterator over the components of the path.
1720 /// use std::path::{Path, Component};
1721 /// use std::ffi::OsStr;
1723 /// let mut components = Path::new("/tmp/foo.txt").components();
1725 /// assert_eq!(components.next(), Some(Component::RootDir));
1726 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1727 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1728 /// assert_eq!(components.next(), None)
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 pub fn components(&self) -> Components {
1732 let prefix = parse_prefix(self.as_os_str());
1734 path: self.as_u8_slice(),
1736 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1737 front: State::Prefix,
1742 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1747 /// use std::path::{self, Path};
1748 /// use std::ffi::OsStr;
1750 /// let mut it = Path::new("/tmp/foo.txt").iter();
1751 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1752 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1753 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1754 /// assert_eq!(it.next(), None)
1756 #[stable(feature = "rust1", since = "1.0.0")]
1757 pub fn iter(&self) -> Iter {
1758 Iter { inner: self.components() }
1761 /// Returns an object that implements `Display` for safely printing paths
1762 /// that may contain non-Unicode data.
1767 /// use std::path::Path;
1769 /// let path = Path::new("/tmp/foo.rs");
1771 /// println!("{}", path.display());
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 pub fn display(&self) -> Display {
1775 Display { path: self }
1779 /// Query the file system to get information about a file, directory, etc.
1781 /// This function will traverse symbolic links to query information about the
1782 /// destination file.
1784 /// This is an alias to `fs::metadata`.
1785 #[stable(feature = "path_ext", since = "1.5.0")]
1786 pub fn metadata(&self) -> io::Result<fs::Metadata> {
1790 /// Query the metadata about a file without following symlinks.
1792 /// This is an alias to `fs::symlink_metadata`.
1793 #[stable(feature = "path_ext", since = "1.5.0")]
1794 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1795 fs::symlink_metadata(self)
1798 /// Returns the canonical form of the path with all intermediate components
1799 /// normalized and symbolic links resolved.
1801 /// This is an alias to `fs::canonicalize`.
1802 #[stable(feature = "path_ext", since = "1.5.0")]
1803 pub fn canonicalize(&self) -> io::Result<PathBuf> {
1804 fs::canonicalize(self)
1807 /// Reads a symbolic link, returning the file that the link points to.
1809 /// This is an alias to `fs::read_link`.
1810 #[stable(feature = "path_ext", since = "1.5.0")]
1811 pub fn read_link(&self) -> io::Result<PathBuf> {
1815 /// Returns an iterator over the entries within a directory.
1817 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1818 /// be encountered after an iterator is initially constructed.
1820 /// This is an alias to `fs::read_dir`.
1821 #[stable(feature = "path_ext", since = "1.5.0")]
1822 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
1826 /// Returns whether the path points at an existing entity.
1828 /// This function will traverse symbolic links to query information about the
1829 /// destination file. In case of broken symbolic links this will return `false`.
1834 /// use std::path::Path;
1835 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
1837 #[stable(feature = "path_ext", since = "1.5.0")]
1838 pub fn exists(&self) -> bool {
1839 fs::metadata(self).is_ok()
1842 /// Returns whether the path is pointing at a regular file.
1844 /// This function will traverse symbolic links to query information about the
1845 /// destination file. In case of broken symbolic links this will return `false`.
1850 /// use std::path::Path;
1851 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
1852 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
1854 #[stable(feature = "path_ext", since = "1.5.0")]
1855 pub fn is_file(&self) -> bool {
1856 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
1859 /// Returns whether the path is pointing at a directory.
1861 /// This function will traverse symbolic links to query information about the
1862 /// destination file. In case of broken symbolic links this will return `false`.
1867 /// use std::path::Path;
1868 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
1869 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
1871 #[stable(feature = "path_ext", since = "1.5.0")]
1872 pub fn is_dir(&self) -> bool {
1873 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl AsRef<OsStr> for Path {
1879 fn as_ref(&self) -> &OsStr {
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl fmt::Debug for Path {
1886 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1887 self.inner.fmt(formatter)
1891 /// Helper struct for safely printing paths with `format!()` and `{}`
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 pub struct Display<'a> {
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 impl<'a> fmt::Debug for Display<'a> {
1899 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1900 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 impl<'a> fmt::Display for Display<'a> {
1906 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1907 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 impl cmp::PartialEq for Path {
1913 fn eq(&self, other: &Path) -> bool {
1914 self.components().eq(other.components())
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl Hash for Path {
1920 fn hash<H: Hasher>(&self, h: &mut H) {
1921 for component in self.components() {
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 impl cmp::Eq for Path {}
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 impl cmp::PartialOrd for Path {
1932 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1933 self.components().partial_cmp(other.components())
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl cmp::Ord for Path {
1939 fn cmp(&self, other: &Path) -> cmp::Ordering {
1940 self.components().cmp(other.components())
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl AsRef<Path> for Path {
1946 fn as_ref(&self) -> &Path {
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl AsRef<Path> for OsStr {
1953 fn as_ref(&self) -> &Path {
1958 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
1959 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
1960 fn as_ref(&self) -> &Path {
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 impl AsRef<Path> for OsString {
1967 fn as_ref(&self) -> &Path {
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl AsRef<Path> for str {
1974 fn as_ref(&self) -> &Path {
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 impl AsRef<Path> for String {
1981 fn as_ref(&self) -> &Path {
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl AsRef<Path> for PathBuf {
1988 fn as_ref(&self) -> &Path {
1993 #[stable(feature = "path_into_iter", since = "1.6.0")]
1994 impl<'a> IntoIterator for &'a PathBuf {
1995 type Item = &'a OsStr;
1996 type IntoIter = Iter<'a>;
1997 fn into_iter(self) -> Iter<'a> { self.iter() }
2000 #[stable(feature = "path_into_iter", since = "1.6.0")]
2001 impl<'a> IntoIterator for &'a Path {
2002 type Item = &'a OsStr;
2003 type IntoIter = Iter<'a>;
2004 fn into_iter(self) -> Iter<'a> { self.iter() }
2007 macro_rules! impl_cmp {
2008 ($lhs:ty, $rhs: ty) => {
2009 #[stable(feature = "partialeq_path", since = "1.6.0")]
2010 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2012 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2015 #[stable(feature = "partialeq_path", since = "1.6.0")]
2016 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2018 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2021 #[stable(feature = "cmp_path", since = "1.8.0")]
2022 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2024 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2025 <Path as PartialOrd>::partial_cmp(self, other)
2029 #[stable(feature = "cmp_path", since = "1.8.0")]
2030 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2032 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2033 <Path as PartialOrd>::partial_cmp(self, other)
2039 impl_cmp!(PathBuf, Path);
2040 impl_cmp!(PathBuf, &'a Path);
2041 impl_cmp!(Cow<'a, Path>, Path);
2042 impl_cmp!(Cow<'a, Path>, &'b Path);
2043 impl_cmp!(Cow<'a, Path>, PathBuf);
2045 macro_rules! impl_cmp_os_str {
2046 ($lhs:ty, $rhs: ty) => {
2047 #[stable(feature = "cmp_path", since = "1.8.0")]
2048 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2050 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2053 #[stable(feature = "cmp_path", since = "1.8.0")]
2054 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2056 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2059 #[stable(feature = "cmp_path", since = "1.8.0")]
2060 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2062 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2063 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2067 #[stable(feature = "cmp_path", since = "1.8.0")]
2068 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2070 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2071 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2077 impl_cmp_os_str!(PathBuf, OsStr);
2078 impl_cmp_os_str!(PathBuf, &'a OsStr);
2079 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2080 impl_cmp_os_str!(PathBuf, OsString);
2081 impl_cmp_os_str!(Path, OsStr);
2082 impl_cmp_os_str!(Path, &'a OsStr);
2083 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2084 impl_cmp_os_str!(Path, OsString);
2085 impl_cmp_os_str!(&'a Path, OsStr);
2086 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2087 impl_cmp_os_str!(&'a Path, OsString);
2088 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2089 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2090 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2092 #[stable(since = "1.7.0", feature = "strip_prefix")]
2093 impl fmt::Display for StripPrefixError {
2094 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2095 self.description().fmt(f)
2099 #[stable(since = "1.7.0", feature = "strip_prefix")]
2100 impl Error for StripPrefixError {
2101 fn description(&self) -> &str { "prefix not found" }
2107 use string::{ToString, String};
2111 ($path:expr, iter: $iter:expr) => (
2113 let path = Path::new($path);
2115 // Forward iteration
2116 let comps = path.iter()
2117 .map(|p| p.to_string_lossy().into_owned())
2118 .collect::<Vec<String>>();
2119 let exp: &[&str] = &$iter;
2120 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2121 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2124 // Reverse iteration
2125 let comps = Path::new($path).iter().rev()
2126 .map(|p| p.to_string_lossy().into_owned())
2127 .collect::<Vec<String>>();
2128 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2129 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2134 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2136 let path = Path::new($path);
2138 let act_root = path.has_root();
2139 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2140 $has_root, act_root);
2142 let act_abs = path.is_absolute();
2143 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2144 $is_absolute, act_abs);
2148 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2150 let path = Path::new($path);
2152 let parent = path.parent().map(|p| p.to_str().unwrap());
2153 let exp_parent: Option<&str> = $parent;
2154 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2155 exp_parent, parent);
2157 let file = path.file_name().map(|p| p.to_str().unwrap());
2158 let exp_file: Option<&str> = $file;
2159 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2164 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2166 let path = Path::new($path);
2168 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2169 let exp_stem: Option<&str> = $file_stem;
2170 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2173 let ext = path.extension().map(|p| p.to_str().unwrap());
2174 let exp_ext: Option<&str> = $extension;
2175 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2180 ($path:expr, iter: $iter:expr,
2181 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2182 parent: $parent:expr, file_name: $file:expr,
2183 file_stem: $file_stem:expr, extension: $extension:expr) => (
2185 t!($path, iter: $iter);
2186 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2187 t!($path, parent: $parent, file_name: $file);
2188 t!($path, file_stem: $file_stem, extension: $extension);
2197 let static_path = Path::new("/home/foo");
2198 let static_cow_path: Cow<'static, Path> = static_path.into();
2199 let pathbuf = PathBuf::from("/home/foo");
2202 let path: &Path = &pathbuf;
2203 let borrowed_cow_path: Cow<Path> = path.into();
2205 assert_eq!(static_cow_path, borrowed_cow_path);
2208 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2210 assert_eq!(static_cow_path, owned_cow_path);
2215 pub fn test_decompositions_unix() {
2231 file_name: Some("foo"),
2232 file_stem: Some("foo"),
2251 file_name: Some("foo"),
2252 file_stem: Some("foo"),
2261 file_name: Some("foo"),
2262 file_stem: Some("foo"),
2271 file_name: Some("foo"),
2272 file_stem: Some("foo"),
2277 iter: ["foo", "bar"],
2280 parent: Some("foo"),
2281 file_name: Some("bar"),
2282 file_stem: Some("bar"),
2287 iter: ["/", "foo", "bar"],
2290 parent: Some("/foo"),
2291 file_name: Some("bar"),
2292 file_stem: Some("bar"),
2301 file_name: Some("foo"),
2302 file_stem: Some("foo"),
2307 iter: ["/", "foo", "bar"],
2310 parent: Some("///foo"),
2311 file_name: Some("bar"),
2312 file_stem: Some("bar"),
2351 file_name: Some("foo"),
2352 file_stem: Some("foo"),
2357 iter: ["foo", ".."],
2360 parent: Some("foo"),
2371 file_name: Some("foo"),
2372 file_stem: Some("foo"),
2377 iter: ["foo", "bar"],
2380 parent: Some("foo"),
2381 file_name: Some("bar"),
2382 file_stem: Some("bar"),
2387 iter: ["foo", ".."],
2390 parent: Some("foo"),
2397 iter: ["foo", "..", "bar"],
2400 parent: Some("foo/.."),
2401 file_name: Some("bar"),
2402 file_stem: Some("bar"),
2411 file_name: Some("a"),
2412 file_stem: Some("a"),
2441 file_name: Some("b"),
2442 file_stem: Some("b"),
2451 file_name: Some("b"),
2452 file_stem: Some("b"),
2461 file_name: Some("b"),
2462 file_stem: Some("b"),
2467 iter: ["a", "b", "c"],
2470 parent: Some("a/b"),
2471 file_name: Some("c"),
2472 file_stem: Some("c"),
2481 file_name: Some(".foo"),
2482 file_stem: Some(".foo"),
2489 pub fn test_decompositions_windows() {
2505 file_name: Some("foo"),
2506 file_stem: Some("foo"),
2561 iter: ["\\", "foo"],
2565 file_name: Some("foo"),
2566 file_stem: Some("foo"),
2575 file_name: Some("foo"),
2576 file_stem: Some("foo"),
2581 iter: ["\\", "foo"],
2585 file_name: Some("foo"),
2586 file_stem: Some("foo"),
2591 iter: ["foo", "bar"],
2594 parent: Some("foo"),
2595 file_name: Some("bar"),
2596 file_stem: Some("bar"),
2601 iter: ["\\", "foo", "bar"],
2604 parent: Some("/foo"),
2605 file_name: Some("bar"),
2606 file_stem: Some("bar"),
2611 iter: ["\\", "foo"],
2615 file_name: Some("foo"),
2616 file_stem: Some("foo"),
2621 iter: ["\\", "foo", "bar"],
2624 parent: Some("///foo"),
2625 file_name: Some("bar"),
2626 file_stem: Some("bar"),
2665 file_name: Some("foo"),
2666 file_stem: Some("foo"),
2671 iter: ["foo", ".."],
2674 parent: Some("foo"),
2685 file_name: Some("foo"),
2686 file_stem: Some("foo"),
2691 iter: ["foo", "bar"],
2694 parent: Some("foo"),
2695 file_name: Some("bar"),
2696 file_stem: Some("bar"),
2701 iter: ["foo", ".."],
2704 parent: Some("foo"),
2711 iter: ["foo", "..", "bar"],
2714 parent: Some("foo/.."),
2715 file_name: Some("bar"),
2716 file_stem: Some("bar"),
2725 file_name: Some("a"),
2726 file_stem: Some("a"),
2755 file_name: Some("b"),
2756 file_stem: Some("b"),
2765 file_name: Some("b"),
2766 file_stem: Some("b"),
2775 file_name: Some("b"),
2776 file_stem: Some("b"),
2781 iter: ["a", "b", "c"],
2784 parent: Some("a/b"),
2785 file_name: Some("c"),
2786 file_stem: Some("c"),
2790 iter: ["a", "b", "c"],
2793 parent: Some("a\\b"),
2794 file_name: Some("c"),
2795 file_stem: Some("c"),
2804 file_name: Some("a"),
2805 file_stem: Some("a"),
2810 iter: ["c:", "\\", "foo.txt"],
2813 parent: Some("c:\\"),
2814 file_name: Some("foo.txt"),
2815 file_stem: Some("foo"),
2816 extension: Some("txt")
2819 t!("\\\\server\\share\\foo.txt",
2820 iter: ["\\\\server\\share", "\\", "foo.txt"],
2823 parent: Some("\\\\server\\share\\"),
2824 file_name: Some("foo.txt"),
2825 file_stem: Some("foo"),
2826 extension: Some("txt")
2829 t!("\\\\server\\share",
2830 iter: ["\\\\server\\share", "\\"],
2840 iter: ["\\", "server"],
2844 file_name: Some("server"),
2845 file_stem: Some("server"),
2849 t!("\\\\?\\bar\\foo.txt",
2850 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2853 parent: Some("\\\\?\\bar\\"),
2854 file_name: Some("foo.txt"),
2855 file_stem: Some("foo"),
2856 extension: Some("txt")
2860 iter: ["\\\\?\\bar"],
2879 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2880 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2883 parent: Some("\\\\?\\UNC\\server\\share\\"),
2884 file_name: Some("foo.txt"),
2885 file_stem: Some("foo"),
2886 extension: Some("txt")
2889 t!("\\\\?\\UNC\\server",
2890 iter: ["\\\\?\\UNC\\server"],
2900 iter: ["\\\\?\\UNC\\"],
2909 t!("\\\\?\\C:\\foo.txt",
2910 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2913 parent: Some("\\\\?\\C:\\"),
2914 file_name: Some("foo.txt"),
2915 file_stem: Some("foo"),
2916 extension: Some("txt")
2921 iter: ["\\\\?\\C:", "\\"],
2932 iter: ["\\\\?\\C:"],
2942 t!("\\\\?\\foo/bar",
2943 iter: ["\\\\?\\foo/bar"],
2954 iter: ["\\\\?\\C:/foo"],
2964 t!("\\\\.\\foo\\bar",
2965 iter: ["\\\\.\\foo", "\\", "bar"],
2968 parent: Some("\\\\.\\foo\\"),
2969 file_name: Some("bar"),
2970 file_stem: Some("bar"),
2976 iter: ["\\\\.\\foo", "\\"],
2986 t!("\\\\.\\foo/bar",
2987 iter: ["\\\\.\\foo/bar", "\\"],
2997 t!("\\\\.\\foo\\bar/baz",
2998 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3001 parent: Some("\\\\.\\foo\\bar"),
3002 file_name: Some("baz"),
3003 file_stem: Some("baz"),
3009 iter: ["\\\\.\\", "\\"],
3019 iter: ["\\\\?\\a", "\\", "b"],
3022 parent: Some("\\\\?\\a\\"),
3023 file_name: Some("b"),
3024 file_stem: Some("b"),
3030 pub fn test_stem_ext() {
3032 file_stem: Some("foo"),
3037 file_stem: Some("foo"),
3042 file_stem: Some(".foo"),
3047 file_stem: Some("foo"),
3048 extension: Some("txt")
3052 file_stem: Some("foo.bar"),
3053 extension: Some("txt")
3057 file_stem: Some("foo.bar"),
3078 pub fn test_push() {
3080 ($path:expr, $push:expr, $expected:expr) => ( {
3081 let mut actual = PathBuf::from($path);
3083 assert!(actual.to_str() == Some($expected),
3084 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3085 $push, $path, $expected, actual.to_str().unwrap());
3090 tp!("", "foo", "foo");
3091 tp!("foo", "bar", "foo/bar");
3092 tp!("foo/", "bar", "foo/bar");
3093 tp!("foo//", "bar", "foo//bar");
3094 tp!("foo/.", "bar", "foo/./bar");
3095 tp!("foo./.", "bar", "foo././bar");
3096 tp!("foo", "", "foo/");
3097 tp!("foo", ".", "foo/.");
3098 tp!("foo", "..", "foo/..");
3099 tp!("foo", "/", "/");
3100 tp!("/foo/bar", "/", "/");
3101 tp!("/foo/bar", "/baz", "/baz");
3102 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3104 tp!("", "foo", "foo");
3105 tp!("foo", "bar", r"foo\bar");
3106 tp!("foo/", "bar", r"foo/bar");
3107 tp!(r"foo\", "bar", r"foo\bar");
3108 tp!("foo//", "bar", r"foo//bar");
3109 tp!(r"foo\\", "bar", r"foo\\bar");
3110 tp!("foo/.", "bar", r"foo/.\bar");
3111 tp!("foo./.", "bar", r"foo./.\bar");
3112 tp!(r"foo\.", "bar", r"foo\.\bar");
3113 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3114 tp!("foo", "", "foo\\");
3115 tp!("foo", ".", r"foo\.");
3116 tp!("foo", "..", r"foo\..");
3117 tp!("foo", "/", "/");
3118 tp!("foo", r"\", r"\");
3119 tp!("/foo/bar", "/", "/");
3120 tp!(r"\foo\bar", r"\", r"\");
3121 tp!("/foo/bar", "/baz", "/baz");
3122 tp!("/foo/bar", r"\baz", r"\baz");
3123 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3124 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3126 tp!("c:\\", "windows", "c:\\windows");
3127 tp!("c:", "windows", "c:windows");
3129 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3130 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3131 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3132 tp!("a\\b", "\\c\\d", "\\c\\d");
3133 tp!("a\\b", ".", "a\\b\\.");
3134 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3135 tp!("a\\b", "C:a.txt", "C:a.txt");
3136 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3137 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3138 tp!("C:\\a\\b\\c", "C:d", "C:d");
3139 tp!("C:a\\b\\c", "C:d", "C:d");
3140 tp!("C:", r"a\b\c", r"C:a\b\c");
3141 tp!("C:", r"..\a", r"C:..\a");
3142 tp!("\\\\server\\share\\foo",
3144 "\\\\server\\share\\foo\\bar");
3145 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3146 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3147 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3148 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3149 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3150 tp!("\\\\?\\UNC\\server\\share\\foo",
3152 "\\\\?\\UNC\\server\\share\\foo\\bar");
3153 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3154 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3156 // Note: modified from old path API
3157 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3160 "\\\\?\\UNC\\server\\share",
3161 "\\\\?\\UNC\\server\\share");
3162 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3163 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3164 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3165 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3167 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3174 ($path:expr, $expected:expr, $output:expr) => ( {
3175 let mut actual = PathBuf::from($path);
3176 let output = actual.pop();
3177 assert!(actual.to_str() == Some($expected) && output == $output,
3178 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3179 $path, $expected, $output,
3180 actual.to_str().unwrap(), output);
3185 tp!("/", "/", false);
3186 tp!("foo", "", true);
3188 tp!("/foo", "/", true);
3189 tp!("/foo/bar", "/foo", true);
3190 tp!("foo/bar", "foo", true);
3191 tp!("foo/.", "", true);
3192 tp!("foo//bar", "foo", true);
3195 tp!("a\\b\\c", "a\\b", true);
3196 tp!("\\a", "\\", true);
3197 tp!("\\", "\\", false);
3199 tp!("C:\\a\\b", "C:\\a", true);
3200 tp!("C:\\a", "C:\\", true);
3201 tp!("C:\\", "C:\\", false);
3202 tp!("C:a\\b", "C:a", true);
3203 tp!("C:a", "C:", true);
3204 tp!("C:", "C:", false);
3205 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3206 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3207 tp!("\\\\server\\share", "\\\\server\\share", false);
3208 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3209 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3210 tp!("\\\\?\\a", "\\\\?\\a", false);
3211 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3212 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3213 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3214 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3215 "\\\\?\\UNC\\server\\share\\a",
3217 tp!("\\\\?\\UNC\\server\\share\\a",
3218 "\\\\?\\UNC\\server\\share\\",
3220 tp!("\\\\?\\UNC\\server\\share",
3221 "\\\\?\\UNC\\server\\share",
3223 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3224 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3225 tp!("\\\\.\\a", "\\\\.\\a", false);
3227 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3232 pub fn test_set_file_name() {
3234 ($path:expr, $file:expr, $expected:expr) => ( {
3235 let mut p = PathBuf::from($path);
3236 p.set_file_name($file);
3237 assert!(p.to_str() == Some($expected),
3238 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3239 $path, $file, $expected,
3240 p.to_str().unwrap());
3244 tfn!("foo", "foo", "foo");
3245 tfn!("foo", "bar", "bar");
3246 tfn!("foo", "", "");
3247 tfn!("", "foo", "foo");
3249 tfn!(".", "foo", "./foo");
3250 tfn!("foo/", "bar", "bar");
3251 tfn!("foo/.", "bar", "bar");
3252 tfn!("..", "foo", "../foo");
3253 tfn!("foo/..", "bar", "foo/../bar");
3254 tfn!("/", "foo", "/foo");
3256 tfn!(".", "foo", r".\foo");
3257 tfn!(r"foo\", "bar", r"bar");
3258 tfn!(r"foo\.", "bar", r"bar");
3259 tfn!("..", "foo", r"..\foo");
3260 tfn!(r"foo\..", "bar", r"foo\..\bar");
3261 tfn!(r"\", "foo", r"\foo");
3266 pub fn test_set_extension() {
3268 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3269 let mut p = PathBuf::from($path);
3270 let output = p.set_extension($ext);
3271 assert!(p.to_str() == Some($expected) && output == $output,
3272 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3273 $path, $ext, $expected, $output,
3274 p.to_str().unwrap(), output);
3278 tfe!("foo", "txt", "foo.txt", true);
3279 tfe!("foo.bar", "txt", "foo.txt", true);
3280 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3281 tfe!(".test", "txt", ".test.txt", true);
3282 tfe!("foo.txt", "", "foo", true);
3283 tfe!("foo", "", "foo", true);
3284 tfe!("", "foo", "", false);
3285 tfe!(".", "foo", ".", false);
3286 tfe!("foo/", "bar", "foo.bar", true);
3287 tfe!("foo/.", "bar", "foo.bar", true);
3288 tfe!("..", "foo", "..", false);
3289 tfe!("foo/..", "bar", "foo/..", false);
3290 tfe!("/", "foo", "/", false);
3294 fn test_eq_recievers() {
3297 let borrowed: &Path = Path::new("foo/bar");
3298 let mut owned: PathBuf = PathBuf::new();
3301 let borrowed_cow: Cow<Path> = borrowed.into();
3302 let owned_cow: Cow<Path> = owned.clone().into();
3305 ($($current:expr),+) => {
3307 assert_eq!($current, borrowed);
3308 assert_eq!($current, owned);
3309 assert_eq!($current, borrowed_cow);
3310 assert_eq!($current, owned_cow);
3315 t!(borrowed, owned, borrowed_cow, owned_cow);
3319 pub fn test_compare() {
3320 use hash::{Hash, Hasher, SipHasher};
3322 fn hash<T: Hash>(t: T) -> u64 {
3323 let mut s = SipHasher::new_with_keys(0, 0);
3329 ($path1:expr, $path2:expr, eq: $eq:expr,
3330 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3331 relative_from: $relative_from:expr) => ({
3332 let path1 = Path::new($path1);
3333 let path2 = Path::new($path2);
3335 let eq = path1 == path2;
3336 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3337 $path1, $path2, $eq, eq);
3338 assert!($eq == (hash(path1) == hash(path2)),
3339 "{:?} == {:?}, expected {:?}, got {} and {}",
3340 $path1, $path2, $eq, hash(path1), hash(path2));
3342 let starts_with = path1.starts_with(path2);
3343 assert!(starts_with == $starts_with,
3344 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3345 $starts_with, starts_with);
3347 let ends_with = path1.ends_with(path2);
3348 assert!(ends_with == $ends_with,
3349 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3350 $ends_with, ends_with);
3352 let relative_from = path1.strip_prefix(path2)
3353 .map(|p| p.to_str().unwrap())
3355 let exp: Option<&str> = $relative_from;
3356 assert!(relative_from == exp,
3357 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3358 $path1, $path2, exp, relative_from);
3366 relative_from: Some("")
3373 relative_from: Some("foo")
3387 relative_from: Some("")
3394 relative_from: Some("")
3397 tc!("foo/bar", "foo",
3401 relative_from: Some("bar")
3404 tc!("foo/bar/baz", "foo/bar",
3408 relative_from: Some("baz")
3411 tc!("foo/bar", "foo/bar/baz",
3418 tc!("./foo/bar/", ".",
3422 relative_from: Some("foo/bar")
3426 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3427 r"c:\src\rust\cargo-test\test",
3431 relative_from: Some("Cargo.toml")
3434 tc!(r"c:\foo", r"C:\foo",
3438 relative_from: Some("")