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")]
104 use borrow::{Borrow, IntoCow, ToOwned, Cow};
109 use hash::{Hash, Hasher};
113 use ops::{self, Deref};
117 use ffi::{OsStr, OsString};
119 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
121 ////////////////////////////////////////////////////////////////////////////////
123 ////////////////////////////////////////////////////////////////////////////////
125 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
126 // taking advantage of the fact that OsStr always encodes ASCII characters
127 // as-is. Eventually, this transmutation should be replaced by direct uses of
128 // OsStr APIs for parsing, but it will take a while for those to become
131 ////////////////////////////////////////////////////////////////////////////////
132 // Platform-specific definitions
133 ////////////////////////////////////////////////////////////////////////////////
135 // The following modules give the most basic tools for parsing paths on various
136 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
144 pub fn is_sep_byte(b: u8) -> bool {
149 pub fn is_verbatim_sep(b: u8) -> bool {
153 pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
157 pub const MAIN_SEP_STR: &'static str = "/";
158 pub const MAIN_SEP: char = '/';
165 use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
169 pub fn is_sep_byte(b: u8) -> bool {
170 b == b'/' || b == b'\\'
174 pub fn is_verbatim_sep(b: u8) -> bool {
178 pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
179 use super::Prefix::*;
181 // The unsafety here stems from converting between &OsStr and &[u8]
182 // and back. This is safe to do because (1) we only look at ASCII
183 // contents of the encoding and (2) new &OsStr values are produced
184 // only from ASCII-bounded slices of existing &OsStr values.
185 let mut path = os_str_as_u8_slice(path);
187 if path.starts_with(br"\\") {
190 if path.starts_with(br"?\") {
193 if path.starts_with(br"UNC\") {
194 // \\?\UNC\server\share
196 let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
197 Some((server, share)) =>
198 (u8_slice_as_os_str(server), u8_slice_as_os_str(share)),
199 None => (u8_slice_as_os_str(path), u8_slice_as_os_str(&[])),
201 return Some(VerbatimUNC(server, share));
204 let idx = path.iter().position(|&b| b == b'\\');
205 if idx == Some(2) && path[1] == b':' {
207 if c.is_ascii() && (c as char).is_alphabetic() {
209 return Some(VerbatimDisk(c.to_ascii_uppercase()));
212 let slice = &path[..idx.unwrap_or(path.len())];
213 return Some(Verbatim(u8_slice_as_os_str(slice)));
215 } else if path.starts_with(b".\\") {
218 let pos = path.iter().position(|&b| b == b'\\');
219 let slice = &path[..pos.unwrap_or(path.len())];
220 return Some(DeviceNS(u8_slice_as_os_str(slice)));
222 match parse_two_comps(path, is_sep_byte) {
223 Some((server, share)) if !server.is_empty() && !share.is_empty() => {
225 return Some(UNC(u8_slice_as_os_str(server), u8_slice_as_os_str(share)));
229 } else if path.len() > 1 && path[1] == b':' {
232 if c.is_ascii() && (c as char).is_alphabetic() {
233 return Some(Disk(c.to_ascii_uppercase()));
239 fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
240 let first = match path.iter().position(|x| f(*x)) {
242 Some(x) => &path[..x],
244 path = &path[(first.len() + 1)..];
245 let idx = path.iter().position(|x| f(*x));
246 let second = &path[..idx.unwrap_or(path.len())];
247 Some((first, second))
251 pub const MAIN_SEP_STR: &'static str = "\\";
252 pub const MAIN_SEP: char = '\\';
255 ////////////////////////////////////////////////////////////////////////////////
257 ////////////////////////////////////////////////////////////////////////////////
259 /// Path prefixes (Windows only).
261 /// Windows uses a variety of path styles, including references to drive
262 /// volumes (like `C:`), network shared folders (like `\\server\share`) and
263 /// others. In addition, some path prefixes are "verbatim", in which case
264 /// `/` is *not* treated as a separator and essentially no normalization is
266 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub enum Prefix<'a> {
269 /// Prefix `\\?\`, together with the given component immediately following it.
270 #[stable(feature = "rust1", since = "1.0.0")]
271 Verbatim(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
273 /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
274 #[stable(feature = "rust1", since = "1.0.0")]
276 #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
277 #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
280 /// Prefix like `\\?\C:\`, for the given drive letter
281 #[stable(feature = "rust1", since = "1.0.0")]
282 VerbatimDisk(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] u8),
284 /// Prefix `\\.\`, together with the given component immediately following it.
285 #[stable(feature = "rust1", since = "1.0.0")]
286 DeviceNS(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
288 /// Prefix `\\server\share`, with the given "server" and "share" components.
289 #[stable(feature = "rust1", since = "1.0.0")]
291 #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
292 #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr,
295 /// Prefix `C:` for the given disk drive.
296 #[stable(feature = "rust1", since = "1.0.0")]
297 Disk(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] u8),
300 impl<'a> Prefix<'a> {
302 fn len(&self) -> usize {
304 fn os_str_len(s: &OsStr) -> usize {
305 os_str_as_u8_slice(s).len()
308 Verbatim(x) => 4 + os_str_len(x),
309 VerbatimUNC(x, y) => {
311 if os_str_len(y) > 0 {
317 VerbatimDisk(_) => 6,
320 if os_str_len(y) > 0 {
326 DeviceNS(x) => 4 + os_str_len(x),
332 /// Determines if the prefix is verbatim, i.e. begins with `\\?\`.
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn is_verbatim(&self) -> bool {
338 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
344 fn is_drive(&self) -> bool {
346 Prefix::Disk(_) => true,
352 fn has_implicit_root(&self) -> bool {
357 ////////////////////////////////////////////////////////////////////////////////
358 // Exposed parsing helpers
359 ////////////////////////////////////////////////////////////////////////////////
361 /// Determines whether the character is one of the permitted path
362 /// separators for the current platform.
369 /// assert!(path::is_separator('/'));
370 /// assert!(!path::is_separator('❤'));
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn is_separator(c: char) -> bool {
374 c.is_ascii() && is_sep_byte(c as u8)
377 /// The primary separator for the current platform
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
381 ////////////////////////////////////////////////////////////////////////////////
383 ////////////////////////////////////////////////////////////////////////////////
385 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
386 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
387 // `iter` after having exhausted `prefix`.
388 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I>
389 where I: Iterator<Item = A> + Clone,
390 J: Iterator<Item = A>,
394 let mut iter_next = iter.clone();
395 match (iter_next.next(), prefix.next()) {
396 (Some(x), Some(y)) => {
401 (Some(_), None) => return Some(iter),
402 (None, None) => return Some(iter),
403 (None, Some(_)) => return None,
409 // See note at the top of this module to understand why these are used:
410 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
411 unsafe { mem::transmute(s) }
413 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
417 ////////////////////////////////////////////////////////////////////////////////
418 // Cross-platform, iterator-independent parsing
419 ////////////////////////////////////////////////////////////////////////////////
421 /// Says whether the first byte after the prefix is a separator.
422 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
423 let path = if let Some(p) = prefix {
428 !path.is_empty() && is_sep_byte(path[0])
431 // basic workhorse for splitting stem and extension
432 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
434 if os_str_as_u8_slice(file) == b".." {
435 return (Some(file), None);
438 // The unsafety here stems from converting between &OsStr and &[u8]
439 // and back. This is safe to do because (1) we only look at ASCII
440 // contents of the encoding and (2) new &OsStr values are produced
441 // only from ASCII-bounded slices of existing &OsStr values.
443 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
444 let after = iter.next();
445 let before = iter.next();
446 if before == Some(b"") {
449 (before.map(|s| u8_slice_as_os_str(s)),
450 after.map(|s| u8_slice_as_os_str(s)))
455 ////////////////////////////////////////////////////////////////////////////////
456 // The core iterators
457 ////////////////////////////////////////////////////////////////////////////////
459 /// Component parsing works by a double-ended state machine; the cursors at the
460 /// front and back of the path each keep track of what parts of the path have
461 /// been consumed so far.
463 /// Going front to back, a path is made up of a prefix, a starting
464 /// directory component, and a body (of normal components)
465 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
468 StartDir = 1, // / or . or nothing
469 Body = 2, // foo/bar/baz
473 /// A Windows path prefix, e.g. `C:` or `\server\share`.
475 /// Does not occur on Unix.
476 #[stable(feature = "rust1", since = "1.0.0")]
477 #[derive(Copy, Clone, Eq, Debug)]
478 pub struct PrefixComponent<'a> {
479 /// The prefix as an unparsed `OsStr` slice.
482 /// The parsed prefix data.
486 impl<'a> PrefixComponent<'a> {
487 /// The parsed prefix data.
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn kind(&self) -> Prefix<'a> {
493 /// The raw `OsStr` slice for this prefix.
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub fn as_os_str(&self) -> &'a OsStr {
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
502 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
503 cmp::PartialEq::eq(&self.parsed, &other.parsed)
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
509 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
510 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<'a> cmp::Ord for PrefixComponent<'a> {
516 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
517 cmp::Ord::cmp(&self.parsed, &other.parsed)
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl<'a> Hash for PrefixComponent<'a> {
523 fn hash<H: Hasher>(&self, h: &mut H) {
528 /// A single component of a path.
530 /// See the module documentation for an in-depth explanation of components and
531 /// their role in the API.
532 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
533 #[stable(feature = "rust1", since = "1.0.0")]
534 pub enum Component<'a> {
535 /// A Windows path prefix, e.g. `C:` or `\server\share`.
537 /// Does not occur on Unix.
538 #[stable(feature = "rust1", since = "1.0.0")]
540 #[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] PrefixComponent<'a>
543 /// The root directory component, appears after any prefix and before anything else
544 #[stable(feature = "rust1", since = "1.0.0")]
547 /// A reference to the current directory, i.e. `.`
548 #[stable(feature = "rust1", since = "1.0.0")]
551 /// A reference to the parent directory, i.e. `..`
552 #[stable(feature = "rust1", since = "1.0.0")]
555 /// A normal component, i.e. `a` and `b` in `a/b`
556 #[stable(feature = "rust1", since = "1.0.0")]
557 Normal(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] &'a OsStr),
560 impl<'a> Component<'a> {
561 /// Extracts the underlying `OsStr` slice
562 #[stable(feature = "rust1", since = "1.0.0")]
563 pub fn as_os_str(self) -> &'a OsStr {
565 Component::Prefix(p) => p.as_os_str(),
566 Component::RootDir => OsStr::new(MAIN_SEP_STR),
567 Component::CurDir => OsStr::new("."),
568 Component::ParentDir => OsStr::new(".."),
569 Component::Normal(path) => path,
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<'a> AsRef<OsStr> for Component<'a> {
576 fn as_ref(&self) -> &OsStr {
581 /// The core iterator giving the components of a path.
583 /// See the module documentation for an in-depth explanation of components and
584 /// their role in the API.
589 /// use std::path::Path;
591 /// let path = Path::new("/tmp/foo/bar.txt");
593 /// for component in path.components() {
594 /// println!("{:?}", component);
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub struct Components<'a> {
600 // The path left to parse components from
603 // The prefix as it was originally parsed, if any
604 prefix: Option<Prefix<'a>>,
606 // true if path *physically* has a root separator; for most Windows
607 // prefixes, it may have a "logical" rootseparator for the purposes of
608 // normalization, e.g. \\server\share == \\server\share\.
609 has_physical_root: bool,
611 // The iterator is double-ended, and these two states keep track of what has
612 // been produced from either end
617 /// An iterator over the components of a path, as `OsStr` slices.
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub struct Iter<'a> {
621 inner: Components<'a>,
624 impl<'a> Components<'a> {
625 // how long is the prefix, if any?
627 fn prefix_len(&self) -> usize {
628 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
632 fn prefix_verbatim(&self) -> bool {
633 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
636 /// how much of the prefix is left from the point of view of iteration?
638 fn prefix_remaining(&self) -> usize {
639 if self.front == State::Prefix {
646 // Given the iteration so far, how much of the pre-State::Body path is left?
648 fn len_before_body(&self) -> usize {
649 let root = if self.front <= State::StartDir && self.has_physical_root {
654 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
659 self.prefix_remaining() + root + cur_dir
662 // is the iteration complete?
664 fn finished(&self) -> bool {
665 self.front == State::Done || self.back == State::Done || self.front > self.back
669 fn is_sep_byte(&self, b: u8) -> bool {
670 if self.prefix_verbatim() {
677 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
682 /// use std::path::Path;
684 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
685 /// components.next();
686 /// components.next();
688 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn as_path(&self) -> &'a Path {
692 let mut comps = self.clone();
693 if comps.front == State::Body {
696 if comps.back == State::Body {
699 unsafe { Path::from_u8_slice(comps.path) }
702 /// Is the *original* path rooted?
703 fn has_root(&self) -> bool {
704 if self.has_physical_root {
707 if let Some(p) = self.prefix {
708 if p.has_implicit_root() {
715 /// Should the normalized path include a leading . ?
716 fn include_cur_dir(&self) -> bool {
720 let mut iter = self.path[self.prefix_len()..].iter();
721 match (iter.next(), iter.next()) {
722 (Some(&b'.'), None) => true,
723 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
728 // parse a given byte sequence into the corresponding path component
729 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
731 b"." if self.prefix_verbatim() => Some(Component::CurDir),
732 b"." => None, // . components are normalized away, except at
733 // the beginning of a path, which is treated
734 // separately via `include_cur_dir`
735 b".." => Some(Component::ParentDir),
737 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
741 // parse a component from the left, saying how many bytes to consume to
742 // remove the component
743 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
744 debug_assert!(self.front == State::Body);
745 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
746 None => (0, self.path),
747 Some(i) => (1, &self.path[..i]),
749 (comp.len() + extra, self.parse_single_component(comp))
752 // parse a component from the right, saying how many bytes to consume to
753 // remove the component
754 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
755 debug_assert!(self.back == State::Body);
756 let start = self.len_before_body();
757 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
758 None => (0, &self.path[start..]),
759 Some(i) => (1, &self.path[start + i + 1..]),
761 (comp.len() + extra, self.parse_single_component(comp))
764 // trim away repeated separators (i.e. empty components) on the left
765 fn trim_left(&mut self) {
766 while !self.path.is_empty() {
767 let (size, comp) = self.parse_next_component();
771 self.path = &self.path[size..];
776 // trim away repeated separators (i.e. empty components) on the right
777 fn trim_right(&mut self) {
778 while self.path.len() > self.len_before_body() {
779 let (size, comp) = self.parse_next_component_back();
783 self.path = &self.path[..self.path.len() - size];
788 /// Examine the next component without consuming it.
789 #[unstable(feature = "path_components_peek", issue = "27727")]
790 #[rustc_deprecated(reason = "use peekable() instead",
792 pub fn peek(&self) -> Option<Component<'a>> {
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<'a> AsRef<Path> for Components<'a> {
799 fn as_ref(&self) -> &Path {
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl<'a> AsRef<OsStr> for Components<'a> {
806 fn as_ref(&self) -> &OsStr {
807 self.as_path().as_os_str()
812 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
813 #[stable(feature = "rust1", since = "1.0.0")]
814 pub fn as_path(&self) -> &'a Path {
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<'a> AsRef<Path> for Iter<'a> {
821 fn as_ref(&self) -> &Path {
826 #[stable(feature = "rust1", since = "1.0.0")]
827 impl<'a> AsRef<OsStr> for Iter<'a> {
828 fn as_ref(&self) -> &OsStr {
829 self.as_path().as_os_str()
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<'a> Iterator for Iter<'a> {
835 type Item = &'a OsStr;
837 fn next(&mut self) -> Option<&'a OsStr> {
838 self.inner.next().map(Component::as_os_str)
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<'a> DoubleEndedIterator for Iter<'a> {
844 fn next_back(&mut self) -> Option<&'a OsStr> {
845 self.inner.next_back().map(Component::as_os_str)
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<'a> Iterator for Components<'a> {
851 type Item = Component<'a>;
853 fn next(&mut self) -> Option<Component<'a>> {
854 while !self.finished() {
856 State::Prefix if self.prefix_len() > 0 => {
857 self.front = State::StartDir;
858 debug_assert!(self.prefix_len() <= self.path.len());
859 let raw = &self.path[..self.prefix_len()];
860 self.path = &self.path[self.prefix_len()..];
861 return Some(Component::Prefix(PrefixComponent {
862 raw: unsafe { u8_slice_as_os_str(raw) },
863 parsed: self.prefix.unwrap(),
867 self.front = State::StartDir;
870 self.front = State::Body;
871 if self.has_physical_root {
872 debug_assert!(!self.path.is_empty());
873 self.path = &self.path[1..];
874 return Some(Component::RootDir);
875 } else if let Some(p) = self.prefix {
876 if p.has_implicit_root() && !p.is_verbatim() {
877 return Some(Component::RootDir);
879 } else if self.include_cur_dir() {
880 debug_assert!(!self.path.is_empty());
881 self.path = &self.path[1..];
882 return Some(Component::CurDir);
885 State::Body if !self.path.is_empty() => {
886 let (size, comp) = self.parse_next_component();
887 self.path = &self.path[size..];
893 self.front = State::Done;
895 State::Done => unreachable!(),
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a> DoubleEndedIterator for Components<'a> {
904 fn next_back(&mut self) -> Option<Component<'a>> {
905 while !self.finished() {
907 State::Body if self.path.len() > self.len_before_body() => {
908 let (size, comp) = self.parse_next_component_back();
909 self.path = &self.path[..self.path.len() - size];
915 self.back = State::StartDir;
918 self.back = State::Prefix;
919 if self.has_physical_root {
920 self.path = &self.path[..self.path.len() - 1];
921 return Some(Component::RootDir);
922 } else if let Some(p) = self.prefix {
923 if p.has_implicit_root() && !p.is_verbatim() {
924 return Some(Component::RootDir);
926 } else if self.include_cur_dir() {
927 self.path = &self.path[..self.path.len() - 1];
928 return Some(Component::CurDir);
931 State::Prefix if self.prefix_len() > 0 => {
932 self.back = State::Done;
933 return Some(Component::Prefix(PrefixComponent {
934 raw: unsafe { u8_slice_as_os_str(self.path) },
935 parsed: self.prefix.unwrap(),
939 self.back = State::Done;
942 State::Done => unreachable!(),
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<'a> cmp::PartialEq for Components<'a> {
951 fn eq(&self, other: &Components<'a>) -> bool {
952 Iterator::eq(self.clone(), other.clone())
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<'a> cmp::Eq for Components<'a> {}
959 #[stable(feature = "rust1", since = "1.0.0")]
960 impl<'a> cmp::PartialOrd for Components<'a> {
961 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
962 Iterator::partial_cmp(self.clone(), other.clone())
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<'a> cmp::Ord for Components<'a> {
968 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
969 Iterator::cmp(self.clone(), other.clone())
973 ////////////////////////////////////////////////////////////////////////////////
974 // Basic types and traits
975 ////////////////////////////////////////////////////////////////////////////////
977 /// An owned, mutable path (akin to `String`).
979 /// This type provides methods like `push` and `set_extension` that mutate the
980 /// path in place. It also implements `Deref` to `Path`, meaning that all
981 /// methods on `Path` slices are available on `PathBuf` values as well.
983 /// More details about the overall approach can be found in
984 /// the module documentation.
989 /// use std::path::PathBuf;
991 /// let mut path = PathBuf::from("c:\\");
992 /// path.push("windows");
993 /// path.push("system32");
994 /// path.set_extension("dll");
997 #[stable(feature = "rust1", since = "1.0.0")]
1003 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1004 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1007 /// Allocates an empty `PathBuf`.
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 pub fn new() -> PathBuf {
1010 PathBuf { inner: OsString::new() }
1013 /// Coerces to a `Path` slice.
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub fn as_path(&self) -> &Path {
1019 /// Extends `self` with `path`.
1021 /// If `path` is absolute, it replaces the current path.
1025 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1026 /// replaces everything except for the prefix (if any) of `self`.
1027 /// * if `path` has a prefix but no root, it replaces `self`.
1032 /// use std::path::PathBuf;
1034 /// let mut path = PathBuf::new();
1035 /// path.push("/tmp");
1036 /// path.push("file.bk");
1037 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1039 /// // Pushing an absolute path replaces the current path
1040 /// path.push("/etc/passwd");
1041 /// assert_eq!(path, PathBuf::from("/etc/passwd"));
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1045 self._push(path.as_ref())
1048 #[allow(deprecated)]
1049 fn _push(&mut self, path: &Path) {
1050 // in general, a separator is needed if the rightmost byte is not a separator
1051 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1053 // in the special case of `C:` on Windows, do *not* add a separator
1055 let comps = self.components();
1056 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1057 comps.prefix.unwrap().is_drive() {
1062 // absolute `path` replaces `self`
1063 if path.is_absolute() || path.prefix().is_some() {
1064 self.as_mut_vec().truncate(0);
1066 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1067 } else if path.has_root() {
1068 let prefix_len = self.components().prefix_remaining();
1069 self.as_mut_vec().truncate(prefix_len);
1071 // `path` is a pure relative path
1072 } else if need_sep {
1073 self.inner.push(MAIN_SEP_STR);
1076 self.inner.push(path);
1079 /// Truncate `self` to `self.parent()`.
1081 /// Returns false and does nothing if `self.file_name()` is `None`.
1082 /// Otherwise, returns `true`.
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 pub fn pop(&mut self) -> bool {
1085 match self.parent().map(|p| p.as_u8_slice().len()) {
1087 self.as_mut_vec().truncate(len);
1094 /// Updates `self.file_name()` to `file_name`.
1096 /// If `self.file_name()` was `None`, this is equivalent to pushing
1102 /// use std::path::PathBuf;
1104 /// let mut buf = PathBuf::from("/");
1105 /// assert!(buf.file_name() == None);
1106 /// buf.set_file_name("bar");
1107 /// assert!(buf == PathBuf::from("/bar"));
1108 /// assert!(buf.file_name().is_some());
1109 /// buf.set_file_name("baz.txt");
1110 /// assert!(buf == PathBuf::from("/baz.txt"));
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1114 self._set_file_name(file_name.as_ref())
1117 fn _set_file_name(&mut self, file_name: &OsStr) {
1118 if self.file_name().is_some() {
1119 let popped = self.pop();
1120 debug_assert!(popped);
1122 self.push(file_name);
1125 /// Updates `self.extension()` to `extension`.
1127 /// If `self.file_name()` is `None`, does nothing and returns `false`.
1129 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
1130 /// is added; otherwise it is replaced.
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1133 self._set_extension(extension.as_ref())
1136 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1137 if self.file_name().is_none() {
1141 let mut stem = match self.file_stem() {
1142 Some(stem) => stem.to_os_string(),
1143 None => OsString::new(),
1146 if !os_str_as_u8_slice(extension).is_empty() {
1148 stem.push(extension);
1150 self.set_file_name(&stem);
1155 /// Consumes the `PathBuf`, yielding its internal `OsString` storage.
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 pub fn into_os_string(self) -> OsString {
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1164 fn from(s: &'a T) -> PathBuf {
1165 PathBuf::from(s.as_ref().to_os_string())
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 impl From<OsString> for PathBuf {
1171 fn from(s: OsString) -> PathBuf {
1172 PathBuf { inner: s }
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl From<String> for PathBuf {
1178 fn from(s: String) -> PathBuf {
1179 PathBuf::from(OsString::from(s))
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1185 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1186 let mut buf = PathBuf::new();
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1194 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1196 self.push(p.as_ref())
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 impl fmt::Debug for PathBuf {
1203 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1204 fmt::Debug::fmt(&**self, formatter)
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 impl ops::Deref for PathBuf {
1212 fn deref(&self) -> &Path {
1213 Path::new(&self.inner)
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl Borrow<Path> for PathBuf {
1219 fn borrow(&self) -> &Path {
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 #[allow(deprecated)]
1226 impl IntoCow<'static, Path> for PathBuf {
1227 fn into_cow(self) -> Cow<'static, Path> {
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 #[allow(deprecated)]
1234 impl<'a> IntoCow<'a, Path> for &'a Path {
1235 fn into_cow(self) -> Cow<'a, Path> {
1240 #[stable(feature = "cow_from_path", since = "1.6.0")]
1241 impl<'a> From<&'a Path> for Cow<'a, Path> {
1243 fn from(s: &'a Path) -> Cow<'a, Path> {
1248 #[stable(feature = "cow_from_path", since = "1.6.0")]
1249 impl<'a> From<PathBuf> for Cow<'a, Path> {
1251 fn from(s: PathBuf) -> Cow<'a, Path> {
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 impl ToOwned for Path {
1258 type Owned = PathBuf;
1259 fn to_owned(&self) -> PathBuf {
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 impl cmp::PartialEq for PathBuf {
1266 fn eq(&self, other: &PathBuf) -> bool {
1267 self.components() == other.components()
1271 #[stable(feature = "rust1", since = "1.0.0")]
1272 impl Hash for PathBuf {
1273 fn hash<H: Hasher>(&self, h: &mut H) {
1274 self.as_path().hash(h)
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl cmp::Eq for PathBuf {}
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl cmp::PartialOrd for PathBuf {
1283 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1284 self.components().partial_cmp(other.components())
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl cmp::Ord for PathBuf {
1290 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1291 self.components().cmp(other.components())
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 impl AsRef<OsStr> for PathBuf {
1297 fn as_ref(&self) -> &OsStr {
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 impl Into<OsString> for PathBuf {
1304 fn into(self) -> OsString {
1309 /// A slice of a path (akin to `str`).
1311 /// This type supports a number of operations for inspecting a path, including
1312 /// breaking the path into its components (separated by `/` or `\`, depending on
1313 /// the platform), extracting the file name, determining whether the path is
1314 /// absolute, and so on. More details about the overall approach can be found in
1315 /// the module documentation.
1317 /// This is an *unsized* type, meaning that it must always be used behind a
1318 /// pointer like `&` or `Box`.
1323 /// use std::path::Path;
1325 /// let path = Path::new("/tmp/foo/bar.txt");
1326 /// let file = path.file_name();
1327 /// let extension = path.extension();
1328 /// let parent_dir = path.parent();
1331 #[stable(feature = "rust1", since = "1.0.0")]
1336 /// An error returned from the `Path::strip_prefix` method indicating that the
1337 /// prefix was not found in `self`.
1338 #[derive(Debug, Clone, PartialEq, Eq)]
1339 #[stable(since = "1.7.0", feature = "strip_prefix")]
1340 pub struct StripPrefixError(());
1343 // The following (private!) function allows construction of a path from a u8
1344 // slice, which is only safe when it is known to follow the OsStr encoding.
1345 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1346 Path::new(u8_slice_as_os_str(s))
1348 // The following (private!) function reveals the byte encoding used for OsStr.
1349 fn as_u8_slice(&self) -> &[u8] {
1350 os_str_as_u8_slice(&self.inner)
1353 /// Directly wrap a string slice as a `Path` slice.
1355 /// This is a cost-free conversion.
1360 /// use std::path::Path;
1362 /// Path::new("foo.txt");
1365 /// You can create `Path`s from `String`s, or even other `Path`s:
1368 /// use std::path::Path;
1370 /// let string = String::from("foo.txt");
1371 /// let from_string = Path::new(&string);
1372 /// let from_path = Path::new(&from_string);
1373 /// assert_eq!(from_string, from_path);
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1377 unsafe { mem::transmute(s.as_ref()) }
1380 /// Yields the underlying `OsStr` slice.
1385 /// use std::path::Path;
1387 /// let os_str = Path::new("foo.txt").as_os_str();
1388 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub fn as_os_str(&self) -> &OsStr {
1395 /// Yields a `&str` slice if the `Path` is valid unicode.
1397 /// This conversion may entail doing a check for UTF-8 validity.
1402 /// use std::path::Path;
1404 /// let path_str = Path::new("foo.txt").to_str();
1405 /// assert_eq!(path_str, Some("foo.txt"));
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 pub fn to_str(&self) -> Option<&str> {
1412 /// Converts a `Path` to a `Cow<str>`.
1414 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1419 /// use std::path::Path;
1421 /// let path_str = Path::new("foo.txt").to_string_lossy();
1422 /// assert_eq!(path_str, "foo.txt");
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 pub fn to_string_lossy(&self) -> Cow<str> {
1426 self.inner.to_string_lossy()
1429 /// Converts a `Path` to an owned `PathBuf`.
1434 /// use std::path::Path;
1436 /// let path_buf = Path::new("foo.txt").to_path_buf();
1437 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 pub fn to_path_buf(&self) -> PathBuf {
1441 PathBuf::from(self.inner.to_os_string())
1444 /// A path is *absolute* if it is independent of the current directory.
1446 /// * On Unix, a path is absolute if it starts with the root, so
1447 /// `is_absolute` and `has_root` are equivalent.
1449 /// * On Windows, a path is absolute if it has a prefix and starts with the
1450 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1451 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1456 /// use std::path::Path;
1458 /// assert!(!Path::new("foo.txt").is_absolute());
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 #[allow(deprecated)]
1462 pub fn is_absolute(&self) -> bool {
1463 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1466 /// A path is *relative* if it is not absolute.
1471 /// use std::path::Path;
1473 /// assert!(Path::new("foo.txt").is_relative());
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 pub fn is_relative(&self) -> bool {
1480 /// Returns the *prefix* of a path, if any.
1482 /// Prefixes are relevant only for Windows paths, and consist of volumes
1483 /// like `C:`, UNC prefixes like `\\server`, and others described in more
1484 /// detail in `std::os::windows::PathExt`.
1485 #[unstable(feature = "path_prefix",
1486 reason = "uncertain whether to expose this convenience",
1488 #[rustc_deprecated(since = "1.7.0",
1489 reason = "inspect components().next() instead")]
1490 pub fn prefix(&self) -> Option<Prefix> {
1491 self.components().prefix
1494 /// A path has a root if the body of the path begins with the directory separator.
1496 /// * On Unix, a path has a root if it begins with `/`.
1498 /// * On Windows, a path has a root if it:
1499 /// * has no prefix and begins with a separator, e.g. `\\windows`
1500 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1501 /// * has any non-disk prefix, e.g. `\\server\share`
1506 /// use std::path::Path;
1508 /// assert!(Path::new("/etc/passwd").has_root());
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 pub fn has_root(&self) -> bool {
1512 self.components().has_root()
1515 /// The path without its final component, if any.
1517 /// Returns `None` if the path terminates in a root or prefix.
1522 /// use std::path::Path;
1524 /// let path = Path::new("/foo/bar");
1525 /// let parent = path.parent().unwrap();
1526 /// assert_eq!(parent, Path::new("/foo"));
1528 /// let grand_parent = parent.parent().unwrap();
1529 /// assert_eq!(grand_parent, Path::new("/"));
1530 /// assert_eq!(grand_parent.parent(), None);
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 pub fn parent(&self) -> Option<&Path> {
1534 let mut comps = self.components();
1535 let comp = comps.next_back();
1538 Component::Normal(_) |
1540 Component::ParentDir => Some(comps.as_path()),
1546 /// The final component of the path, if it is a normal file.
1548 /// If the path terminates in `.`, `..`, or consists solely of a root of
1549 /// prefix, `file_name` will return `None`.
1554 /// use std::path::Path;
1555 /// use std::ffi::OsStr;
1557 /// let path = Path::new("foo.txt");
1558 /// let os_str = OsStr::new("foo.txt");
1560 /// assert_eq!(Some(os_str), path.file_name());
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 pub fn file_name(&self) -> Option<&OsStr> {
1564 self.components().next_back().and_then(|p| {
1566 Component::Normal(p) => Some(p.as_ref()),
1572 /// Returns a path that, when joined onto `base`, yields `self`.
1574 /// If `base` is not a prefix of `self` (i.e. `starts_with`
1575 /// returns false), then `relative_from` returns `None`.
1576 #[unstable(feature = "path_relative_from", reason = "see #23284",
1578 #[rustc_deprecated(since = "1.7.0", reason = "renamed to strip_prefix")]
1579 pub fn relative_from<'a, P: ?Sized + AsRef<Path>>(&'a self, base: &'a P) -> Option<&Path> {
1580 self._strip_prefix(base.as_ref()).ok()
1583 /// Returns a path that, when joined onto `base`, yields `self`.
1585 /// If `base` is not a prefix of `self` (i.e. `starts_with`
1586 /// returns false), then `relative_from` returns `None`.
1587 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1588 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1589 -> Result<&'a Path, StripPrefixError>
1590 where P: AsRef<Path>
1592 self._strip_prefix(base.as_ref())
1595 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1596 -> Result<&'a Path, StripPrefixError> {
1597 iter_after(self.components(), base.components())
1598 .map(|c| c.as_path())
1599 .ok_or(StripPrefixError(()))
1602 /// Determines whether `base` is a prefix of `self`.
1604 /// Only considers whole path components to match.
1609 /// use std::path::Path;
1611 /// let path = Path::new("/etc/passwd");
1613 /// assert!(path.starts_with("/etc"));
1615 /// assert!(!path.starts_with("/e"));
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1619 self._starts_with(base.as_ref())
1622 fn _starts_with(&self, base: &Path) -> bool {
1623 iter_after(self.components(), base.components()).is_some()
1626 /// Determines whether `child` is a suffix of `self`.
1628 /// Only considers whole path components to match.
1633 /// use std::path::Path;
1635 /// let path = Path::new("/etc/passwd");
1637 /// assert!(path.ends_with("passwd"));
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1641 self._ends_with(child.as_ref())
1644 fn _ends_with(&self, child: &Path) -> bool {
1645 iter_after(self.components().rev(), child.components().rev()).is_some()
1648 /// Extracts the stem (non-extension) portion of `self.file_name()`.
1652 /// * None, if there is no file name;
1653 /// * The entire file name if there is no embedded `.`;
1654 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1655 /// * Otherwise, the portion of the file name before the final `.`
1660 /// use std::path::Path;
1662 /// let path = Path::new("foo.rs");
1664 /// assert_eq!("foo", path.file_stem().unwrap());
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 pub fn file_stem(&self) -> Option<&OsStr> {
1668 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1671 /// Extracts the extension of `self.file_name()`, if possible.
1673 /// The extension is:
1675 /// * None, if there is no file name;
1676 /// * None, if there is no embedded `.`;
1677 /// * None, if the file name begins with `.` and has no other `.`s within;
1678 /// * Otherwise, the portion of the file name after the final `.`
1683 /// use std::path::Path;
1685 /// let path = Path::new("foo.rs");
1687 /// assert_eq!("rs", path.extension().unwrap());
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 pub fn extension(&self) -> Option<&OsStr> {
1691 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1694 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1696 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1701 /// use std::path::{Path, PathBuf};
1703 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1707 self._join(path.as_ref())
1710 fn _join(&self, path: &Path) -> PathBuf {
1711 let mut buf = self.to_path_buf();
1716 /// Creates an owned `PathBuf` like `self` but with the given file name.
1718 /// See `PathBuf::set_file_name` for more details.
1723 /// use std::path::{Path, PathBuf};
1725 /// let path = Path::new("/tmp/foo.txt");
1726 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1730 self._with_file_name(file_name.as_ref())
1733 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1734 let mut buf = self.to_path_buf();
1735 buf.set_file_name(file_name);
1739 /// Creates an owned `PathBuf` like `self` but with the given extension.
1741 /// See `PathBuf::set_extension` for more details.
1746 /// use std::path::{Path, PathBuf};
1748 /// let path = Path::new("foo.rs");
1749 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1753 self._with_extension(extension.as_ref())
1756 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1757 let mut buf = self.to_path_buf();
1758 buf.set_extension(extension);
1762 /// Produce an iterator over the components of the path.
1767 /// use std::path::{Path, Component};
1768 /// use std::ffi::OsStr;
1770 /// let mut components = Path::new("/tmp/foo.txt").components();
1772 /// assert_eq!(components.next(), Some(Component::RootDir));
1773 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1774 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1775 /// assert_eq!(components.next(), None)
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub fn components(&self) -> Components {
1779 let prefix = parse_prefix(self.as_os_str());
1781 path: self.as_u8_slice(),
1783 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1784 front: State::Prefix,
1789 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1794 /// use std::path::{self, Path};
1795 /// use std::ffi::OsStr;
1797 /// let mut it = Path::new("/tmp/foo.txt").iter();
1798 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1799 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1800 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1801 /// assert_eq!(it.next(), None)
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 pub fn iter(&self) -> Iter {
1805 Iter { inner: self.components() }
1808 /// Returns an object that implements `Display` for safely printing paths
1809 /// that may contain non-Unicode data.
1814 /// use std::path::Path;
1816 /// let path = Path::new("/tmp/foo.rs");
1818 /// println!("{}", path.display());
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 pub fn display(&self) -> Display {
1822 Display { path: self }
1826 /// Gets information on the file, directory, etc at this path.
1828 /// Consult the `fs::metadata` documentation for more info.
1830 /// This call preserves identical runtime/error semantics with
1832 #[stable(feature = "path_ext", since = "1.5.0")]
1833 pub fn metadata(&self) -> io::Result<fs::Metadata> {
1837 /// Gets information on the file, directory, etc at this path.
1839 /// Consult the `fs::symlink_metadata` documentation for more info.
1841 /// This call preserves identical runtime/error semantics with
1842 /// `fs::symlink_metadata`.
1843 #[stable(feature = "path_ext", since = "1.5.0")]
1844 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1845 fs::symlink_metadata(self)
1848 /// Returns the canonical form of a path, normalizing all components and
1849 /// eliminate all symlinks.
1851 /// This call preserves identical runtime/error semantics with
1852 /// `fs::canonicalize`.
1853 #[stable(feature = "path_ext", since = "1.5.0")]
1854 pub fn canonicalize(&self) -> io::Result<PathBuf> {
1855 fs::canonicalize(self)
1858 /// Reads the symlink at this path.
1860 /// For more information see `fs::read_link`.
1861 #[stable(feature = "path_ext", since = "1.5.0")]
1862 pub fn read_link(&self) -> io::Result<PathBuf> {
1866 /// Reads the directory at this path.
1868 /// For more information see `fs::read_dir`.
1869 #[stable(feature = "path_ext", since = "1.5.0")]
1870 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
1874 /// Boolean value indicator whether the underlying file exists on the local
1875 /// filesystem. Returns false in exactly the cases where `fs::metadata`
1877 #[stable(feature = "path_ext", since = "1.5.0")]
1878 pub fn exists(&self) -> bool {
1879 fs::metadata(self).is_ok()
1882 /// Whether the underlying implementation (be it a file path, or something
1883 /// else) points at a "regular file" on the FS. Will return false for paths
1884 /// to non-existent locations or directories or other non-regular files
1885 /// (named pipes, etc). Follows links when making this determination.
1886 #[stable(feature = "path_ext", since = "1.5.0")]
1887 pub fn is_file(&self) -> bool {
1888 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
1891 /// Whether the underlying implementation (be it a file path, or something
1892 /// else) is pointing at a directory in the underlying FS. Will return
1893 /// false for paths to non-existent locations or if the item is not a
1894 /// directory (eg files, named pipes, etc). Follows links when making this
1896 #[stable(feature = "path_ext", since = "1.5.0")]
1897 pub fn is_dir(&self) -> bool {
1898 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl AsRef<OsStr> for Path {
1904 fn as_ref(&self) -> &OsStr {
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 impl fmt::Debug for Path {
1911 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1912 self.inner.fmt(formatter)
1916 /// Helper struct for safely printing paths with `format!()` and `{}`
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 pub struct Display<'a> {
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<'a> fmt::Debug for Display<'a> {
1924 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1925 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl<'a> fmt::Display for Display<'a> {
1931 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1932 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1936 #[stable(feature = "rust1", since = "1.0.0")]
1937 impl cmp::PartialEq for Path {
1938 fn eq(&self, other: &Path) -> bool {
1939 self.components().eq(other.components())
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl Hash for Path {
1945 fn hash<H: Hasher>(&self, h: &mut H) {
1946 for component in self.components() {
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 impl cmp::Eq for Path {}
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl cmp::PartialOrd for Path {
1957 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1958 self.components().partial_cmp(other.components())
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl cmp::Ord for Path {
1964 fn cmp(&self, other: &Path) -> cmp::Ordering {
1965 self.components().cmp(other.components())
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl AsRef<Path> for Path {
1971 fn as_ref(&self) -> &Path {
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl AsRef<Path> for OsStr {
1978 fn as_ref(&self) -> &Path {
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl AsRef<Path> for OsString {
1985 fn as_ref(&self) -> &Path {
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl AsRef<Path> for str {
1992 fn as_ref(&self) -> &Path {
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 impl AsRef<Path> for String {
1999 fn as_ref(&self) -> &Path {
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 impl AsRef<Path> for PathBuf {
2006 fn as_ref(&self) -> &Path {
2011 #[stable(feature = "path_into_iter", since = "1.6.0")]
2012 impl<'a> IntoIterator for &'a PathBuf {
2013 type Item = &'a OsStr;
2014 type IntoIter = Iter<'a>;
2015 fn into_iter(self) -> Iter<'a> { self.iter() }
2018 #[stable(feature = "path_into_iter", since = "1.6.0")]
2019 impl<'a> IntoIterator for &'a Path {
2020 type Item = &'a OsStr;
2021 type IntoIter = Iter<'a>;
2022 fn into_iter(self) -> Iter<'a> { self.iter() }
2025 macro_rules! impl_eq {
2026 ($lhs:ty, $rhs: ty) => {
2027 #[stable(feature = "partialeq_path", since = "1.6.0")]
2028 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2030 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2033 #[stable(feature = "partialeq_path", since = "1.6.0")]
2034 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2036 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2042 impl_eq!(PathBuf, Path);
2043 impl_eq!(PathBuf, &'a Path);
2044 impl_eq!(Cow<'a, Path>, Path);
2045 impl_eq!(Cow<'a, Path>, &'b Path);
2046 impl_eq!(Cow<'a, Path>, PathBuf);
2048 #[stable(since = "1.7.0", feature = "strip_prefix")]
2049 impl fmt::Display for StripPrefixError {
2050 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2051 self.description().fmt(f)
2055 #[stable(since = "1.7.0", feature = "strip_prefix")]
2056 impl Error for StripPrefixError {
2057 fn description(&self) -> &str { "prefix not found" }
2063 use string::{ToString, String};
2067 ($path:expr, iter: $iter:expr) => (
2069 let path = Path::new($path);
2071 // Forward iteration
2072 let comps = path.iter()
2073 .map(|p| p.to_string_lossy().into_owned())
2074 .collect::<Vec<String>>();
2075 let exp: &[&str] = &$iter;
2076 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2077 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2080 // Reverse iteration
2081 let comps = Path::new($path).iter().rev()
2082 .map(|p| p.to_string_lossy().into_owned())
2083 .collect::<Vec<String>>();
2084 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2085 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2090 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2092 let path = Path::new($path);
2094 let act_root = path.has_root();
2095 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2096 $has_root, act_root);
2098 let act_abs = path.is_absolute();
2099 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2100 $is_absolute, act_abs);
2104 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2106 let path = Path::new($path);
2108 let parent = path.parent().map(|p| p.to_str().unwrap());
2109 let exp_parent: Option<&str> = $parent;
2110 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2111 exp_parent, parent);
2113 let file = path.file_name().map(|p| p.to_str().unwrap());
2114 let exp_file: Option<&str> = $file;
2115 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2120 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2122 let path = Path::new($path);
2124 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2125 let exp_stem: Option<&str> = $file_stem;
2126 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2129 let ext = path.extension().map(|p| p.to_str().unwrap());
2130 let exp_ext: Option<&str> = $extension;
2131 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2136 ($path:expr, iter: $iter:expr,
2137 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2138 parent: $parent:expr, file_name: $file:expr,
2139 file_stem: $file_stem:expr, extension: $extension:expr) => (
2141 t!($path, iter: $iter);
2142 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2143 t!($path, parent: $parent, file_name: $file);
2144 t!($path, file_stem: $file_stem, extension: $extension);
2150 #[allow(deprecated)]
2152 use borrow::{Cow, IntoCow};
2154 let static_path = Path::new("/home/foo");
2155 let static_cow_path: Cow<'static, Path> = static_path.into_cow();
2156 let pathbuf = PathBuf::from("/home/foo");
2159 let path: &Path = &pathbuf;
2160 let borrowed_cow_path: Cow<Path> = path.into_cow();
2162 assert_eq!(static_cow_path, borrowed_cow_path);
2165 let owned_cow_path: Cow<'static, Path> = pathbuf.into_cow();
2167 assert_eq!(static_cow_path, owned_cow_path);
2174 let static_path = Path::new("/home/foo");
2175 let static_cow_path: Cow<'static, Path> = static_path.into();
2176 let pathbuf = PathBuf::from("/home/foo");
2179 let path: &Path = &pathbuf;
2180 let borrowed_cow_path: Cow<Path> = path.into();
2182 assert_eq!(static_cow_path, borrowed_cow_path);
2185 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2187 assert_eq!(static_cow_path, owned_cow_path);
2192 pub fn test_decompositions_unix() {
2208 file_name: Some("foo"),
2209 file_stem: Some("foo"),
2228 file_name: Some("foo"),
2229 file_stem: Some("foo"),
2238 file_name: Some("foo"),
2239 file_stem: Some("foo"),
2248 file_name: Some("foo"),
2249 file_stem: Some("foo"),
2254 iter: ["foo", "bar"],
2257 parent: Some("foo"),
2258 file_name: Some("bar"),
2259 file_stem: Some("bar"),
2264 iter: ["/", "foo", "bar"],
2267 parent: Some("/foo"),
2268 file_name: Some("bar"),
2269 file_stem: Some("bar"),
2278 file_name: Some("foo"),
2279 file_stem: Some("foo"),
2284 iter: ["/", "foo", "bar"],
2287 parent: Some("///foo"),
2288 file_name: Some("bar"),
2289 file_stem: Some("bar"),
2328 file_name: Some("foo"),
2329 file_stem: Some("foo"),
2334 iter: ["foo", ".."],
2337 parent: Some("foo"),
2348 file_name: Some("foo"),
2349 file_stem: Some("foo"),
2354 iter: ["foo", "bar"],
2357 parent: Some("foo"),
2358 file_name: Some("bar"),
2359 file_stem: Some("bar"),
2364 iter: ["foo", ".."],
2367 parent: Some("foo"),
2374 iter: ["foo", "..", "bar"],
2377 parent: Some("foo/.."),
2378 file_name: Some("bar"),
2379 file_stem: Some("bar"),
2388 file_name: Some("a"),
2389 file_stem: Some("a"),
2418 file_name: Some("b"),
2419 file_stem: Some("b"),
2428 file_name: Some("b"),
2429 file_stem: Some("b"),
2438 file_name: Some("b"),
2439 file_stem: Some("b"),
2444 iter: ["a", "b", "c"],
2447 parent: Some("a/b"),
2448 file_name: Some("c"),
2449 file_stem: Some("c"),
2458 file_name: Some(".foo"),
2459 file_stem: Some(".foo"),
2466 pub fn test_decompositions_windows() {
2482 file_name: Some("foo"),
2483 file_stem: Some("foo"),
2538 iter: ["\\", "foo"],
2542 file_name: Some("foo"),
2543 file_stem: Some("foo"),
2552 file_name: Some("foo"),
2553 file_stem: Some("foo"),
2558 iter: ["\\", "foo"],
2562 file_name: Some("foo"),
2563 file_stem: Some("foo"),
2568 iter: ["foo", "bar"],
2571 parent: Some("foo"),
2572 file_name: Some("bar"),
2573 file_stem: Some("bar"),
2578 iter: ["\\", "foo", "bar"],
2581 parent: Some("/foo"),
2582 file_name: Some("bar"),
2583 file_stem: Some("bar"),
2588 iter: ["\\", "foo"],
2592 file_name: Some("foo"),
2593 file_stem: Some("foo"),
2598 iter: ["\\", "foo", "bar"],
2601 parent: Some("///foo"),
2602 file_name: Some("bar"),
2603 file_stem: Some("bar"),
2642 file_name: Some("foo"),
2643 file_stem: Some("foo"),
2648 iter: ["foo", ".."],
2651 parent: Some("foo"),
2662 file_name: Some("foo"),
2663 file_stem: Some("foo"),
2668 iter: ["foo", "bar"],
2671 parent: Some("foo"),
2672 file_name: Some("bar"),
2673 file_stem: Some("bar"),
2678 iter: ["foo", ".."],
2681 parent: Some("foo"),
2688 iter: ["foo", "..", "bar"],
2691 parent: Some("foo/.."),
2692 file_name: Some("bar"),
2693 file_stem: Some("bar"),
2702 file_name: Some("a"),
2703 file_stem: Some("a"),
2732 file_name: Some("b"),
2733 file_stem: Some("b"),
2742 file_name: Some("b"),
2743 file_stem: Some("b"),
2752 file_name: Some("b"),
2753 file_stem: Some("b"),
2758 iter: ["a", "b", "c"],
2761 parent: Some("a/b"),
2762 file_name: Some("c"),
2763 file_stem: Some("c"),
2767 iter: ["a", "b", "c"],
2770 parent: Some("a\\b"),
2771 file_name: Some("c"),
2772 file_stem: Some("c"),
2781 file_name: Some("a"),
2782 file_stem: Some("a"),
2787 iter: ["c:", "\\", "foo.txt"],
2790 parent: Some("c:\\"),
2791 file_name: Some("foo.txt"),
2792 file_stem: Some("foo"),
2793 extension: Some("txt")
2796 t!("\\\\server\\share\\foo.txt",
2797 iter: ["\\\\server\\share", "\\", "foo.txt"],
2800 parent: Some("\\\\server\\share\\"),
2801 file_name: Some("foo.txt"),
2802 file_stem: Some("foo"),
2803 extension: Some("txt")
2806 t!("\\\\server\\share",
2807 iter: ["\\\\server\\share", "\\"],
2817 iter: ["\\", "server"],
2821 file_name: Some("server"),
2822 file_stem: Some("server"),
2826 t!("\\\\?\\bar\\foo.txt",
2827 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2830 parent: Some("\\\\?\\bar\\"),
2831 file_name: Some("foo.txt"),
2832 file_stem: Some("foo"),
2833 extension: Some("txt")
2837 iter: ["\\\\?\\bar"],
2856 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2857 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2860 parent: Some("\\\\?\\UNC\\server\\share\\"),
2861 file_name: Some("foo.txt"),
2862 file_stem: Some("foo"),
2863 extension: Some("txt")
2866 t!("\\\\?\\UNC\\server",
2867 iter: ["\\\\?\\UNC\\server"],
2877 iter: ["\\\\?\\UNC\\"],
2886 t!("\\\\?\\C:\\foo.txt",
2887 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2890 parent: Some("\\\\?\\C:\\"),
2891 file_name: Some("foo.txt"),
2892 file_stem: Some("foo"),
2893 extension: Some("txt")
2898 iter: ["\\\\?\\C:", "\\"],
2909 iter: ["\\\\?\\C:"],
2919 t!("\\\\?\\foo/bar",
2920 iter: ["\\\\?\\foo/bar"],
2931 iter: ["\\\\?\\C:/foo"],
2941 t!("\\\\.\\foo\\bar",
2942 iter: ["\\\\.\\foo", "\\", "bar"],
2945 parent: Some("\\\\.\\foo\\"),
2946 file_name: Some("bar"),
2947 file_stem: Some("bar"),
2953 iter: ["\\\\.\\foo", "\\"],
2963 t!("\\\\.\\foo/bar",
2964 iter: ["\\\\.\\foo/bar", "\\"],
2974 t!("\\\\.\\foo\\bar/baz",
2975 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
2978 parent: Some("\\\\.\\foo\\bar"),
2979 file_name: Some("baz"),
2980 file_stem: Some("baz"),
2986 iter: ["\\\\.\\", "\\"],
2996 iter: ["\\\\?\\a", "\\", "b"],
2999 parent: Some("\\\\?\\a\\"),
3000 file_name: Some("b"),
3001 file_stem: Some("b"),
3007 pub fn test_stem_ext() {
3009 file_stem: Some("foo"),
3014 file_stem: Some("foo"),
3019 file_stem: Some(".foo"),
3024 file_stem: Some("foo"),
3025 extension: Some("txt")
3029 file_stem: Some("foo.bar"),
3030 extension: Some("txt")
3034 file_stem: Some("foo.bar"),
3055 pub fn test_push() {
3057 ($path:expr, $push:expr, $expected:expr) => ( {
3058 let mut actual = PathBuf::from($path);
3060 assert!(actual.to_str() == Some($expected),
3061 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3062 $push, $path, $expected, actual.to_str().unwrap());
3067 tp!("", "foo", "foo");
3068 tp!("foo", "bar", "foo/bar");
3069 tp!("foo/", "bar", "foo/bar");
3070 tp!("foo//", "bar", "foo//bar");
3071 tp!("foo/.", "bar", "foo/./bar");
3072 tp!("foo./.", "bar", "foo././bar");
3073 tp!("foo", "", "foo/");
3074 tp!("foo", ".", "foo/.");
3075 tp!("foo", "..", "foo/..");
3076 tp!("foo", "/", "/");
3077 tp!("/foo/bar", "/", "/");
3078 tp!("/foo/bar", "/baz", "/baz");
3079 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3081 tp!("", "foo", "foo");
3082 tp!("foo", "bar", r"foo\bar");
3083 tp!("foo/", "bar", r"foo/bar");
3084 tp!(r"foo\", "bar", r"foo\bar");
3085 tp!("foo//", "bar", r"foo//bar");
3086 tp!(r"foo\\", "bar", r"foo\\bar");
3087 tp!("foo/.", "bar", r"foo/.\bar");
3088 tp!("foo./.", "bar", r"foo./.\bar");
3089 tp!(r"foo\.", "bar", r"foo\.\bar");
3090 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3091 tp!("foo", "", "foo\\");
3092 tp!("foo", ".", r"foo\.");
3093 tp!("foo", "..", r"foo\..");
3094 tp!("foo", "/", "/");
3095 tp!("foo", r"\", r"\");
3096 tp!("/foo/bar", "/", "/");
3097 tp!(r"\foo\bar", r"\", r"\");
3098 tp!("/foo/bar", "/baz", "/baz");
3099 tp!("/foo/bar", r"\baz", r"\baz");
3100 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3101 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3103 tp!("c:\\", "windows", "c:\\windows");
3104 tp!("c:", "windows", "c:windows");
3106 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3107 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3108 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3109 tp!("a\\b", "\\c\\d", "\\c\\d");
3110 tp!("a\\b", ".", "a\\b\\.");
3111 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3112 tp!("a\\b", "C:a.txt", "C:a.txt");
3113 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3114 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3115 tp!("C:\\a\\b\\c", "C:d", "C:d");
3116 tp!("C:a\\b\\c", "C:d", "C:d");
3117 tp!("C:", r"a\b\c", r"C:a\b\c");
3118 tp!("C:", r"..\a", r"C:..\a");
3119 tp!("\\\\server\\share\\foo",
3121 "\\\\server\\share\\foo\\bar");
3122 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3123 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3124 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3125 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3126 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3127 tp!("\\\\?\\UNC\\server\\share\\foo",
3129 "\\\\?\\UNC\\server\\share\\foo\\bar");
3130 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3131 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3133 // Note: modified from old path API
3134 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3137 "\\\\?\\UNC\\server\\share",
3138 "\\\\?\\UNC\\server\\share");
3139 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3140 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3141 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3142 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3144 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3151 ($path:expr, $expected:expr, $output:expr) => ( {
3152 let mut actual = PathBuf::from($path);
3153 let output = actual.pop();
3154 assert!(actual.to_str() == Some($expected) && output == $output,
3155 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3156 $path, $expected, $output,
3157 actual.to_str().unwrap(), output);
3162 tp!("/", "/", false);
3163 tp!("foo", "", true);
3165 tp!("/foo", "/", true);
3166 tp!("/foo/bar", "/foo", true);
3167 tp!("foo/bar", "foo", true);
3168 tp!("foo/.", "", true);
3169 tp!("foo//bar", "foo", true);
3172 tp!("a\\b\\c", "a\\b", true);
3173 tp!("\\a", "\\", true);
3174 tp!("\\", "\\", false);
3176 tp!("C:\\a\\b", "C:\\a", true);
3177 tp!("C:\\a", "C:\\", true);
3178 tp!("C:\\", "C:\\", false);
3179 tp!("C:a\\b", "C:a", true);
3180 tp!("C:a", "C:", true);
3181 tp!("C:", "C:", false);
3182 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3183 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3184 tp!("\\\\server\\share", "\\\\server\\share", false);
3185 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3186 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3187 tp!("\\\\?\\a", "\\\\?\\a", false);
3188 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3189 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3190 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3191 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3192 "\\\\?\\UNC\\server\\share\\a",
3194 tp!("\\\\?\\UNC\\server\\share\\a",
3195 "\\\\?\\UNC\\server\\share\\",
3197 tp!("\\\\?\\UNC\\server\\share",
3198 "\\\\?\\UNC\\server\\share",
3200 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3201 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3202 tp!("\\\\.\\a", "\\\\.\\a", false);
3204 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3209 pub fn test_set_file_name() {
3211 ($path:expr, $file:expr, $expected:expr) => ( {
3212 let mut p = PathBuf::from($path);
3213 p.set_file_name($file);
3214 assert!(p.to_str() == Some($expected),
3215 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3216 $path, $file, $expected,
3217 p.to_str().unwrap());
3221 tfn!("foo", "foo", "foo");
3222 tfn!("foo", "bar", "bar");
3223 tfn!("foo", "", "");
3224 tfn!("", "foo", "foo");
3226 tfn!(".", "foo", "./foo");
3227 tfn!("foo/", "bar", "bar");
3228 tfn!("foo/.", "bar", "bar");
3229 tfn!("..", "foo", "../foo");
3230 tfn!("foo/..", "bar", "foo/../bar");
3231 tfn!("/", "foo", "/foo");
3233 tfn!(".", "foo", r".\foo");
3234 tfn!(r"foo\", "bar", r"bar");
3235 tfn!(r"foo\.", "bar", r"bar");
3236 tfn!("..", "foo", r"..\foo");
3237 tfn!(r"foo\..", "bar", r"foo\..\bar");
3238 tfn!(r"\", "foo", r"\foo");
3243 pub fn test_set_extension() {
3245 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3246 let mut p = PathBuf::from($path);
3247 let output = p.set_extension($ext);
3248 assert!(p.to_str() == Some($expected) && output == $output,
3249 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3250 $path, $ext, $expected, $output,
3251 p.to_str().unwrap(), output);
3255 tfe!("foo", "txt", "foo.txt", true);
3256 tfe!("foo.bar", "txt", "foo.txt", true);
3257 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3258 tfe!(".test", "txt", ".test.txt", true);
3259 tfe!("foo.txt", "", "foo", true);
3260 tfe!("foo", "", "foo", true);
3261 tfe!("", "foo", "", false);
3262 tfe!(".", "foo", ".", false);
3263 tfe!("foo/", "bar", "foo.bar", true);
3264 tfe!("foo/.", "bar", "foo.bar", true);
3265 tfe!("..", "foo", "..", false);
3266 tfe!("foo/..", "bar", "foo/..", false);
3267 tfe!("/", "foo", "/", false);
3271 fn test_eq_recievers() {
3274 let borrowed: &Path = Path::new("foo/bar");
3275 let mut owned: PathBuf = PathBuf::new();
3278 let borrowed_cow: Cow<Path> = borrowed.into();
3279 let owned_cow: Cow<Path> = owned.clone().into();
3282 ($($current:expr),+) => {
3284 assert_eq!($current, borrowed);
3285 assert_eq!($current, owned);
3286 assert_eq!($current, borrowed_cow);
3287 assert_eq!($current, owned_cow);
3292 t!(borrowed, owned, borrowed_cow, owned_cow);
3296 pub fn test_compare() {
3297 use hash::{Hash, Hasher, SipHasher};
3299 fn hash<T: Hash>(t: T) -> u64 {
3300 let mut s = SipHasher::new_with_keys(0, 0);
3306 ($path1:expr, $path2:expr, eq: $eq:expr,
3307 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3308 relative_from: $relative_from:expr) => ({
3309 let path1 = Path::new($path1);
3310 let path2 = Path::new($path2);
3312 let eq = path1 == path2;
3313 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3314 $path1, $path2, $eq, eq);
3315 assert!($eq == (hash(path1) == hash(path2)),
3316 "{:?} == {:?}, expected {:?}, got {} and {}",
3317 $path1, $path2, $eq, hash(path1), hash(path2));
3319 let starts_with = path1.starts_with(path2);
3320 assert!(starts_with == $starts_with,
3321 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3322 $starts_with, starts_with);
3324 let ends_with = path1.ends_with(path2);
3325 assert!(ends_with == $ends_with,
3326 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3327 $ends_with, ends_with);
3329 let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
3330 let exp: Option<&str> = $relative_from;
3331 assert!(relative_from == exp,
3332 "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
3333 exp, relative_from);
3341 relative_from: Some("")
3348 relative_from: Some("foo")
3362 relative_from: Some("")
3369 relative_from: Some("")
3372 tc!("foo/bar", "foo",
3376 relative_from: Some("bar")
3379 tc!("foo/bar/baz", "foo/bar",
3383 relative_from: Some("baz")
3386 tc!("foo/bar", "foo/bar/baz",
3393 tc!("./foo/bar/", ".",
3397 relative_from: Some("foo/bar")
3401 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3402 r"c:\src\rust\cargo-test\test",
3406 relative_from: Some("Cargo.toml")
3409 tc!(r"c:\foo", r"C:\foo",
3413 relative_from: Some("")