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 /// Query the file system to get information about a file, directory, etc.
1828 /// This function will traverse symbolic links to query information about the
1829 /// destination file.
1831 /// This is an alias to `fs::metadata`.
1832 #[stable(feature = "path_ext", since = "1.5.0")]
1833 pub fn metadata(&self) -> io::Result<fs::Metadata> {
1837 /// Query the metadata about a file without following symlinks.
1839 /// This is an alias to `fs::symlink_metadata`.
1840 #[stable(feature = "path_ext", since = "1.5.0")]
1841 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1842 fs::symlink_metadata(self)
1845 /// Returns the canonical form of the path with all intermediate components
1846 /// normalized and symbolic links resolved.
1848 /// This is an alias to `fs::canonicalize`.
1849 #[stable(feature = "path_ext", since = "1.5.0")]
1850 pub fn canonicalize(&self) -> io::Result<PathBuf> {
1851 fs::canonicalize(self)
1854 /// Reads a symbolic link, returning the file that the link points to.
1856 /// This is an alias to `fs::read_link`.
1857 #[stable(feature = "path_ext", since = "1.5.0")]
1858 pub fn read_link(&self) -> io::Result<PathBuf> {
1862 /// Returns an iterator over the entries within a directory.
1864 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1865 /// be encountered after an iterator is initially constructed.
1867 /// This is an alias to `fs::read_dir`.
1868 #[stable(feature = "path_ext", since = "1.5.0")]
1869 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
1873 /// Returns whether the path points at an existing entity.
1875 /// This function will traverse symbolic links to query information about the
1876 /// destination file. In case of broken symbolic links this will return `false`.
1881 /// use std::path::Path;
1882 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
1884 #[stable(feature = "path_ext", since = "1.5.0")]
1885 pub fn exists(&self) -> bool {
1886 fs::metadata(self).is_ok()
1889 /// Returns whether the path is pointing at a regular file.
1891 /// This function will traverse symbolic links to query information about the
1892 /// destination file. In case of broken symbolic links this will return `false`.
1897 /// use std::path::Path;
1898 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
1899 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
1901 #[stable(feature = "path_ext", since = "1.5.0")]
1902 pub fn is_file(&self) -> bool {
1903 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
1906 /// Returns whether the path is pointing at a directory.
1908 /// This function will traverse symbolic links to query information about the
1909 /// destination file. In case of broken symbolic links this will return `false`.
1914 /// use std::path::Path;
1915 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
1916 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
1918 #[stable(feature = "path_ext", since = "1.5.0")]
1919 pub fn is_dir(&self) -> bool {
1920 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 impl AsRef<OsStr> for Path {
1926 fn as_ref(&self) -> &OsStr {
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl fmt::Debug for Path {
1933 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1934 self.inner.fmt(formatter)
1938 /// Helper struct for safely printing paths with `format!()` and `{}`
1939 #[stable(feature = "rust1", since = "1.0.0")]
1940 pub struct Display<'a> {
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl<'a> fmt::Debug for Display<'a> {
1946 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1947 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl<'a> fmt::Display for Display<'a> {
1953 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1954 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl cmp::PartialEq for Path {
1960 fn eq(&self, other: &Path) -> bool {
1961 self.components().eq(other.components())
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 impl Hash for Path {
1967 fn hash<H: Hasher>(&self, h: &mut H) {
1968 for component in self.components() {
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl cmp::Eq for Path {}
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl cmp::PartialOrd for Path {
1979 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1980 self.components().partial_cmp(other.components())
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 impl cmp::Ord for Path {
1986 fn cmp(&self, other: &Path) -> cmp::Ordering {
1987 self.components().cmp(other.components())
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 impl AsRef<Path> for Path {
1993 fn as_ref(&self) -> &Path {
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 impl AsRef<Path> for OsStr {
2000 fn as_ref(&self) -> &Path {
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 impl AsRef<Path> for OsString {
2007 fn as_ref(&self) -> &Path {
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl AsRef<Path> for str {
2014 fn as_ref(&self) -> &Path {
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 impl AsRef<Path> for String {
2021 fn as_ref(&self) -> &Path {
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 impl AsRef<Path> for PathBuf {
2028 fn as_ref(&self) -> &Path {
2033 #[stable(feature = "path_into_iter", since = "1.6.0")]
2034 impl<'a> IntoIterator for &'a PathBuf {
2035 type Item = &'a OsStr;
2036 type IntoIter = Iter<'a>;
2037 fn into_iter(self) -> Iter<'a> { self.iter() }
2040 #[stable(feature = "path_into_iter", since = "1.6.0")]
2041 impl<'a> IntoIterator for &'a Path {
2042 type Item = &'a OsStr;
2043 type IntoIter = Iter<'a>;
2044 fn into_iter(self) -> Iter<'a> { self.iter() }
2047 macro_rules! impl_eq {
2048 ($lhs:ty, $rhs: ty) => {
2049 #[stable(feature = "partialeq_path", since = "1.6.0")]
2050 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2052 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2055 #[stable(feature = "partialeq_path", since = "1.6.0")]
2056 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2058 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2064 impl_eq!(PathBuf, Path);
2065 impl_eq!(PathBuf, &'a Path);
2066 impl_eq!(Cow<'a, Path>, Path);
2067 impl_eq!(Cow<'a, Path>, &'b Path);
2068 impl_eq!(Cow<'a, Path>, PathBuf);
2070 #[stable(since = "1.7.0", feature = "strip_prefix")]
2071 impl fmt::Display for StripPrefixError {
2072 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2073 self.description().fmt(f)
2077 #[stable(since = "1.7.0", feature = "strip_prefix")]
2078 impl Error for StripPrefixError {
2079 fn description(&self) -> &str { "prefix not found" }
2085 use string::{ToString, String};
2089 ($path:expr, iter: $iter:expr) => (
2091 let path = Path::new($path);
2093 // Forward iteration
2094 let comps = path.iter()
2095 .map(|p| p.to_string_lossy().into_owned())
2096 .collect::<Vec<String>>();
2097 let exp: &[&str] = &$iter;
2098 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2099 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2102 // Reverse iteration
2103 let comps = Path::new($path).iter().rev()
2104 .map(|p| p.to_string_lossy().into_owned())
2105 .collect::<Vec<String>>();
2106 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2107 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2112 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2114 let path = Path::new($path);
2116 let act_root = path.has_root();
2117 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2118 $has_root, act_root);
2120 let act_abs = path.is_absolute();
2121 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2122 $is_absolute, act_abs);
2126 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2128 let path = Path::new($path);
2130 let parent = path.parent().map(|p| p.to_str().unwrap());
2131 let exp_parent: Option<&str> = $parent;
2132 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2133 exp_parent, parent);
2135 let file = path.file_name().map(|p| p.to_str().unwrap());
2136 let exp_file: Option<&str> = $file;
2137 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2142 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2144 let path = Path::new($path);
2146 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2147 let exp_stem: Option<&str> = $file_stem;
2148 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2151 let ext = path.extension().map(|p| p.to_str().unwrap());
2152 let exp_ext: Option<&str> = $extension;
2153 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2158 ($path:expr, iter: $iter:expr,
2159 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2160 parent: $parent:expr, file_name: $file:expr,
2161 file_stem: $file_stem:expr, extension: $extension:expr) => (
2163 t!($path, iter: $iter);
2164 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2165 t!($path, parent: $parent, file_name: $file);
2166 t!($path, file_stem: $file_stem, extension: $extension);
2172 #[allow(deprecated)]
2174 use borrow::{Cow, IntoCow};
2176 let static_path = Path::new("/home/foo");
2177 let static_cow_path: Cow<'static, Path> = static_path.into_cow();
2178 let pathbuf = PathBuf::from("/home/foo");
2181 let path: &Path = &pathbuf;
2182 let borrowed_cow_path: Cow<Path> = path.into_cow();
2184 assert_eq!(static_cow_path, borrowed_cow_path);
2187 let owned_cow_path: Cow<'static, Path> = pathbuf.into_cow();
2189 assert_eq!(static_cow_path, owned_cow_path);
2196 let static_path = Path::new("/home/foo");
2197 let static_cow_path: Cow<'static, Path> = static_path.into();
2198 let pathbuf = PathBuf::from("/home/foo");
2201 let path: &Path = &pathbuf;
2202 let borrowed_cow_path: Cow<Path> = path.into();
2204 assert_eq!(static_cow_path, borrowed_cow_path);
2207 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2209 assert_eq!(static_cow_path, owned_cow_path);
2214 pub fn test_decompositions_unix() {
2230 file_name: Some("foo"),
2231 file_stem: Some("foo"),
2250 file_name: Some("foo"),
2251 file_stem: Some("foo"),
2260 file_name: Some("foo"),
2261 file_stem: Some("foo"),
2270 file_name: Some("foo"),
2271 file_stem: Some("foo"),
2276 iter: ["foo", "bar"],
2279 parent: Some("foo"),
2280 file_name: Some("bar"),
2281 file_stem: Some("bar"),
2286 iter: ["/", "foo", "bar"],
2289 parent: Some("/foo"),
2290 file_name: Some("bar"),
2291 file_stem: Some("bar"),
2300 file_name: Some("foo"),
2301 file_stem: Some("foo"),
2306 iter: ["/", "foo", "bar"],
2309 parent: Some("///foo"),
2310 file_name: Some("bar"),
2311 file_stem: Some("bar"),
2350 file_name: Some("foo"),
2351 file_stem: Some("foo"),
2356 iter: ["foo", ".."],
2359 parent: Some("foo"),
2370 file_name: Some("foo"),
2371 file_stem: Some("foo"),
2376 iter: ["foo", "bar"],
2379 parent: Some("foo"),
2380 file_name: Some("bar"),
2381 file_stem: Some("bar"),
2386 iter: ["foo", ".."],
2389 parent: Some("foo"),
2396 iter: ["foo", "..", "bar"],
2399 parent: Some("foo/.."),
2400 file_name: Some("bar"),
2401 file_stem: Some("bar"),
2410 file_name: Some("a"),
2411 file_stem: Some("a"),
2440 file_name: Some("b"),
2441 file_stem: Some("b"),
2450 file_name: Some("b"),
2451 file_stem: Some("b"),
2460 file_name: Some("b"),
2461 file_stem: Some("b"),
2466 iter: ["a", "b", "c"],
2469 parent: Some("a/b"),
2470 file_name: Some("c"),
2471 file_stem: Some("c"),
2480 file_name: Some(".foo"),
2481 file_stem: Some(".foo"),
2488 pub fn test_decompositions_windows() {
2504 file_name: Some("foo"),
2505 file_stem: Some("foo"),
2560 iter: ["\\", "foo"],
2564 file_name: Some("foo"),
2565 file_stem: Some("foo"),
2574 file_name: Some("foo"),
2575 file_stem: Some("foo"),
2580 iter: ["\\", "foo"],
2584 file_name: Some("foo"),
2585 file_stem: Some("foo"),
2590 iter: ["foo", "bar"],
2593 parent: Some("foo"),
2594 file_name: Some("bar"),
2595 file_stem: Some("bar"),
2600 iter: ["\\", "foo", "bar"],
2603 parent: Some("/foo"),
2604 file_name: Some("bar"),
2605 file_stem: Some("bar"),
2610 iter: ["\\", "foo"],
2614 file_name: Some("foo"),
2615 file_stem: Some("foo"),
2620 iter: ["\\", "foo", "bar"],
2623 parent: Some("///foo"),
2624 file_name: Some("bar"),
2625 file_stem: Some("bar"),
2664 file_name: Some("foo"),
2665 file_stem: Some("foo"),
2670 iter: ["foo", ".."],
2673 parent: Some("foo"),
2684 file_name: Some("foo"),
2685 file_stem: Some("foo"),
2690 iter: ["foo", "bar"],
2693 parent: Some("foo"),
2694 file_name: Some("bar"),
2695 file_stem: Some("bar"),
2700 iter: ["foo", ".."],
2703 parent: Some("foo"),
2710 iter: ["foo", "..", "bar"],
2713 parent: Some("foo/.."),
2714 file_name: Some("bar"),
2715 file_stem: Some("bar"),
2724 file_name: Some("a"),
2725 file_stem: Some("a"),
2754 file_name: Some("b"),
2755 file_stem: Some("b"),
2764 file_name: Some("b"),
2765 file_stem: Some("b"),
2774 file_name: Some("b"),
2775 file_stem: Some("b"),
2780 iter: ["a", "b", "c"],
2783 parent: Some("a/b"),
2784 file_name: Some("c"),
2785 file_stem: Some("c"),
2789 iter: ["a", "b", "c"],
2792 parent: Some("a\\b"),
2793 file_name: Some("c"),
2794 file_stem: Some("c"),
2803 file_name: Some("a"),
2804 file_stem: Some("a"),
2809 iter: ["c:", "\\", "foo.txt"],
2812 parent: Some("c:\\"),
2813 file_name: Some("foo.txt"),
2814 file_stem: Some("foo"),
2815 extension: Some("txt")
2818 t!("\\\\server\\share\\foo.txt",
2819 iter: ["\\\\server\\share", "\\", "foo.txt"],
2822 parent: Some("\\\\server\\share\\"),
2823 file_name: Some("foo.txt"),
2824 file_stem: Some("foo"),
2825 extension: Some("txt")
2828 t!("\\\\server\\share",
2829 iter: ["\\\\server\\share", "\\"],
2839 iter: ["\\", "server"],
2843 file_name: Some("server"),
2844 file_stem: Some("server"),
2848 t!("\\\\?\\bar\\foo.txt",
2849 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2852 parent: Some("\\\\?\\bar\\"),
2853 file_name: Some("foo.txt"),
2854 file_stem: Some("foo"),
2855 extension: Some("txt")
2859 iter: ["\\\\?\\bar"],
2878 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2879 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2882 parent: Some("\\\\?\\UNC\\server\\share\\"),
2883 file_name: Some("foo.txt"),
2884 file_stem: Some("foo"),
2885 extension: Some("txt")
2888 t!("\\\\?\\UNC\\server",
2889 iter: ["\\\\?\\UNC\\server"],
2899 iter: ["\\\\?\\UNC\\"],
2908 t!("\\\\?\\C:\\foo.txt",
2909 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2912 parent: Some("\\\\?\\C:\\"),
2913 file_name: Some("foo.txt"),
2914 file_stem: Some("foo"),
2915 extension: Some("txt")
2920 iter: ["\\\\?\\C:", "\\"],
2931 iter: ["\\\\?\\C:"],
2941 t!("\\\\?\\foo/bar",
2942 iter: ["\\\\?\\foo/bar"],
2953 iter: ["\\\\?\\C:/foo"],
2963 t!("\\\\.\\foo\\bar",
2964 iter: ["\\\\.\\foo", "\\", "bar"],
2967 parent: Some("\\\\.\\foo\\"),
2968 file_name: Some("bar"),
2969 file_stem: Some("bar"),
2975 iter: ["\\\\.\\foo", "\\"],
2985 t!("\\\\.\\foo/bar",
2986 iter: ["\\\\.\\foo/bar", "\\"],
2996 t!("\\\\.\\foo\\bar/baz",
2997 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3000 parent: Some("\\\\.\\foo\\bar"),
3001 file_name: Some("baz"),
3002 file_stem: Some("baz"),
3008 iter: ["\\\\.\\", "\\"],
3018 iter: ["\\\\?\\a", "\\", "b"],
3021 parent: Some("\\\\?\\a\\"),
3022 file_name: Some("b"),
3023 file_stem: Some("b"),
3029 pub fn test_stem_ext() {
3031 file_stem: Some("foo"),
3036 file_stem: Some("foo"),
3041 file_stem: Some(".foo"),
3046 file_stem: Some("foo"),
3047 extension: Some("txt")
3051 file_stem: Some("foo.bar"),
3052 extension: Some("txt")
3056 file_stem: Some("foo.bar"),
3077 pub fn test_push() {
3079 ($path:expr, $push:expr, $expected:expr) => ( {
3080 let mut actual = PathBuf::from($path);
3082 assert!(actual.to_str() == Some($expected),
3083 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3084 $push, $path, $expected, actual.to_str().unwrap());
3089 tp!("", "foo", "foo");
3090 tp!("foo", "bar", "foo/bar");
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", "", "foo/");
3096 tp!("foo", ".", "foo/.");
3097 tp!("foo", "..", "foo/..");
3098 tp!("foo", "/", "/");
3099 tp!("/foo/bar", "/", "/");
3100 tp!("/foo/bar", "/baz", "/baz");
3101 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3103 tp!("", "foo", "foo");
3104 tp!("foo", "bar", r"foo\bar");
3105 tp!("foo/", "bar", r"foo/bar");
3106 tp!(r"foo\", "bar", r"foo\bar");
3107 tp!("foo//", "bar", r"foo//bar");
3108 tp!(r"foo\\", "bar", r"foo\\bar");
3109 tp!("foo/.", "bar", r"foo/.\bar");
3110 tp!("foo./.", "bar", r"foo./.\bar");
3111 tp!(r"foo\.", "bar", r"foo\.\bar");
3112 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3113 tp!("foo", "", "foo\\");
3114 tp!("foo", ".", r"foo\.");
3115 tp!("foo", "..", r"foo\..");
3116 tp!("foo", "/", "/");
3117 tp!("foo", r"\", r"\");
3118 tp!("/foo/bar", "/", "/");
3119 tp!(r"\foo\bar", r"\", r"\");
3120 tp!("/foo/bar", "/baz", "/baz");
3121 tp!("/foo/bar", r"\baz", r"\baz");
3122 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3123 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3125 tp!("c:\\", "windows", "c:\\windows");
3126 tp!("c:", "windows", "c:windows");
3128 tp!("a\\b\\c", "d", "a\\b\\c\\d");
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", "\\c\\d");
3132 tp!("a\\b", ".", "a\\b\\.");
3133 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3134 tp!("a\\b", "C:a.txt", "C:a.txt");
3135 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3136 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3137 tp!("C:\\a\\b\\c", "C:d", "C:d");
3138 tp!("C:a\\b\\c", "C:d", "C:d");
3139 tp!("C:", r"a\b\c", r"C:a\b\c");
3140 tp!("C:", r"..\a", r"C:..\a");
3141 tp!("\\\\server\\share\\foo",
3143 "\\\\server\\share\\foo\\bar");
3144 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3145 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3146 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3147 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3148 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3149 tp!("\\\\?\\UNC\\server\\share\\foo",
3151 "\\\\?\\UNC\\server\\share\\foo\\bar");
3152 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3153 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3155 // Note: modified from old path API
3156 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3159 "\\\\?\\UNC\\server\\share",
3160 "\\\\?\\UNC\\server\\share");
3161 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3162 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3163 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3164 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3166 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3173 ($path:expr, $expected:expr, $output:expr) => ( {
3174 let mut actual = PathBuf::from($path);
3175 let output = actual.pop();
3176 assert!(actual.to_str() == Some($expected) && output == $output,
3177 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3178 $path, $expected, $output,
3179 actual.to_str().unwrap(), output);
3184 tp!("/", "/", false);
3185 tp!("foo", "", true);
3187 tp!("/foo", "/", true);
3188 tp!("/foo/bar", "/foo", true);
3189 tp!("foo/bar", "foo", true);
3190 tp!("foo/.", "", true);
3191 tp!("foo//bar", "foo", true);
3194 tp!("a\\b\\c", "a\\b", true);
3195 tp!("\\a", "\\", true);
3196 tp!("\\", "\\", false);
3198 tp!("C:\\a\\b", "C:\\a", true);
3199 tp!("C:\\a", "C:\\", true);
3200 tp!("C:\\", "C:\\", false);
3201 tp!("C:a\\b", "C:a", true);
3202 tp!("C:a", "C:", true);
3203 tp!("C:", "C:", false);
3204 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3205 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3206 tp!("\\\\server\\share", "\\\\server\\share", false);
3207 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3208 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3209 tp!("\\\\?\\a", "\\\\?\\a", false);
3210 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3211 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3212 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3213 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3214 "\\\\?\\UNC\\server\\share\\a",
3216 tp!("\\\\?\\UNC\\server\\share\\a",
3217 "\\\\?\\UNC\\server\\share\\",
3219 tp!("\\\\?\\UNC\\server\\share",
3220 "\\\\?\\UNC\\server\\share",
3222 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3223 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3224 tp!("\\\\.\\a", "\\\\.\\a", false);
3226 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3231 pub fn test_set_file_name() {
3233 ($path:expr, $file:expr, $expected:expr) => ( {
3234 let mut p = PathBuf::from($path);
3235 p.set_file_name($file);
3236 assert!(p.to_str() == Some($expected),
3237 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3238 $path, $file, $expected,
3239 p.to_str().unwrap());
3243 tfn!("foo", "foo", "foo");
3244 tfn!("foo", "bar", "bar");
3245 tfn!("foo", "", "");
3246 tfn!("", "foo", "foo");
3248 tfn!(".", "foo", "./foo");
3249 tfn!("foo/", "bar", "bar");
3250 tfn!("foo/.", "bar", "bar");
3251 tfn!("..", "foo", "../foo");
3252 tfn!("foo/..", "bar", "foo/../bar");
3253 tfn!("/", "foo", "/foo");
3255 tfn!(".", "foo", r".\foo");
3256 tfn!(r"foo\", "bar", r"bar");
3257 tfn!(r"foo\.", "bar", r"bar");
3258 tfn!("..", "foo", r"..\foo");
3259 tfn!(r"foo\..", "bar", r"foo\..\bar");
3260 tfn!(r"\", "foo", r"\foo");
3265 pub fn test_set_extension() {
3267 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3268 let mut p = PathBuf::from($path);
3269 let output = p.set_extension($ext);
3270 assert!(p.to_str() == Some($expected) && output == $output,
3271 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3272 $path, $ext, $expected, $output,
3273 p.to_str().unwrap(), output);
3277 tfe!("foo", "txt", "foo.txt", true);
3278 tfe!("foo.bar", "txt", "foo.txt", true);
3279 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3280 tfe!(".test", "txt", ".test.txt", true);
3281 tfe!("foo.txt", "", "foo", true);
3282 tfe!("foo", "", "foo", true);
3283 tfe!("", "foo", "", false);
3284 tfe!(".", "foo", ".", false);
3285 tfe!("foo/", "bar", "foo.bar", true);
3286 tfe!("foo/.", "bar", "foo.bar", true);
3287 tfe!("..", "foo", "..", false);
3288 tfe!("foo/..", "bar", "foo/..", false);
3289 tfe!("/", "foo", "/", false);
3293 fn test_eq_recievers() {
3296 let borrowed: &Path = Path::new("foo/bar");
3297 let mut owned: PathBuf = PathBuf::new();
3300 let borrowed_cow: Cow<Path> = borrowed.into();
3301 let owned_cow: Cow<Path> = owned.clone().into();
3304 ($($current:expr),+) => {
3306 assert_eq!($current, borrowed);
3307 assert_eq!($current, owned);
3308 assert_eq!($current, borrowed_cow);
3309 assert_eq!($current, owned_cow);
3314 t!(borrowed, owned, borrowed_cow, owned_cow);
3318 pub fn test_compare() {
3319 use hash::{Hash, Hasher, SipHasher};
3321 fn hash<T: Hash>(t: T) -> u64 {
3322 let mut s = SipHasher::new_with_keys(0, 0);
3328 ($path1:expr, $path2:expr, eq: $eq:expr,
3329 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3330 relative_from: $relative_from:expr) => ({
3331 let path1 = Path::new($path1);
3332 let path2 = Path::new($path2);
3334 let eq = path1 == path2;
3335 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3336 $path1, $path2, $eq, eq);
3337 assert!($eq == (hash(path1) == hash(path2)),
3338 "{:?} == {:?}, expected {:?}, got {} and {}",
3339 $path1, $path2, $eq, hash(path1), hash(path2));
3341 let starts_with = path1.starts_with(path2);
3342 assert!(starts_with == $starts_with,
3343 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3344 $starts_with, starts_with);
3346 let ends_with = path1.ends_with(path2);
3347 assert!(ends_with == $ends_with,
3348 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3349 $ends_with, ends_with);
3351 let relative_from = path1.strip_prefix(path2)
3352 .map(|p| p.to_str().unwrap())
3354 let exp: Option<&str> = $relative_from;
3355 assert!(relative_from == exp,
3356 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3357 $path1, $path2, exp, relative_from);
3365 relative_from: Some("")
3372 relative_from: Some("foo")
3386 relative_from: Some("")
3393 relative_from: Some("")
3396 tc!("foo/bar", "foo",
3400 relative_from: Some("bar")
3403 tc!("foo/bar/baz", "foo/bar",
3407 relative_from: Some("baz")
3410 tc!("foo/bar", "foo/bar/baz",
3417 tc!("./foo/bar/", ".",
3421 relative_from: Some("foo/bar")
3425 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3426 r"c:\src\rust\cargo-test\test",
3430 relative_from: Some("Cargo.toml")
3433 tc!(r"c:\foo", r"C:\foo",
3437 relative_from: Some("")