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.get(1) == Some(& 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(#[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 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
277 #[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(#[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(#[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 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
292 #[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(#[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(ref x), Some(ref y)) if x == y => (),
397 (Some(_), Some(_)) => return None,
398 (Some(_), None) => return Some(iter),
399 (None, None) => return Some(iter),
400 (None, Some(_)) => return None,
406 // See note at the top of this module to understand why these are used:
407 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
408 unsafe { mem::transmute(s) }
410 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
414 ////////////////////////////////////////////////////////////////////////////////
415 // Cross-platform, iterator-independent parsing
416 ////////////////////////////////////////////////////////////////////////////////
418 /// Says whether the first byte after the prefix is a separator.
419 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
420 let path = if let Some(p) = prefix {
425 !path.is_empty() && is_sep_byte(path[0])
428 // basic workhorse for splitting stem and extension
429 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
431 if os_str_as_u8_slice(file) == b".." {
432 return (Some(file), None);
435 // The unsafety here stems from converting between &OsStr and &[u8]
436 // and back. This is safe to do because (1) we only look at ASCII
437 // contents of the encoding and (2) new &OsStr values are produced
438 // only from ASCII-bounded slices of existing &OsStr values.
440 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
441 let after = iter.next();
442 let before = iter.next();
443 if before == Some(b"") {
446 (before.map(|s| u8_slice_as_os_str(s)),
447 after.map(|s| u8_slice_as_os_str(s)))
452 ////////////////////////////////////////////////////////////////////////////////
453 // The core iterators
454 ////////////////////////////////////////////////////////////////////////////////
456 /// Component parsing works by a double-ended state machine; the cursors at the
457 /// front and back of the path each keep track of what parts of the path have
458 /// been consumed so far.
460 /// Going front to back, a path is made up of a prefix, a starting
461 /// directory component, and a body (of normal components)
462 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
465 StartDir = 1, // / or . or nothing
466 Body = 2, // foo/bar/baz
470 /// A Windows path prefix, e.g. `C:` or `\server\share`.
472 /// Does not occur on Unix.
473 #[stable(feature = "rust1", since = "1.0.0")]
474 #[derive(Copy, Clone, Eq, Debug)]
475 pub struct PrefixComponent<'a> {
476 /// The prefix as an unparsed `OsStr` slice.
479 /// The parsed prefix data.
483 impl<'a> PrefixComponent<'a> {
484 /// The parsed prefix data.
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn kind(&self) -> Prefix<'a> {
490 /// The raw `OsStr` slice for this prefix.
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn as_os_str(&self) -> &'a OsStr {
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
499 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
500 cmp::PartialEq::eq(&self.parsed, &other.parsed)
504 #[stable(feature = "rust1", since = "1.0.0")]
505 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
506 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
507 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
511 #[stable(feature = "rust1", since = "1.0.0")]
512 impl<'a> cmp::Ord for PrefixComponent<'a> {
513 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
514 cmp::Ord::cmp(&self.parsed, &other.parsed)
518 #[stable(feature = "rust1", since = "1.0.0")]
519 impl<'a> Hash for PrefixComponent<'a> {
520 fn hash<H: Hasher>(&self, h: &mut H) {
525 /// A single component of a path.
527 /// See the module documentation for an in-depth explanation of components and
528 /// their role in the API.
529 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub enum Component<'a> {
532 /// A Windows path prefix, e.g. `C:` or `\server\share`.
534 /// Does not occur on Unix.
535 #[stable(feature = "rust1", since = "1.0.0")]
537 #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
540 /// The root directory component, appears after any prefix and before anything else
541 #[stable(feature = "rust1", since = "1.0.0")]
544 /// A reference to the current directory, i.e. `.`
545 #[stable(feature = "rust1", since = "1.0.0")]
548 /// A reference to the parent directory, i.e. `..`
549 #[stable(feature = "rust1", since = "1.0.0")]
552 /// A normal component, i.e. `a` and `b` in `a/b`
553 #[stable(feature = "rust1", since = "1.0.0")]
554 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
557 impl<'a> Component<'a> {
558 /// Extracts the underlying `OsStr` slice
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn as_os_str(self) -> &'a OsStr {
562 Component::Prefix(p) => p.as_os_str(),
563 Component::RootDir => OsStr::new(MAIN_SEP_STR),
564 Component::CurDir => OsStr::new("."),
565 Component::ParentDir => OsStr::new(".."),
566 Component::Normal(path) => path,
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl<'a> AsRef<OsStr> for Component<'a> {
573 fn as_ref(&self) -> &OsStr {
578 /// The core iterator giving the components of a path.
580 /// See the module documentation for an in-depth explanation of components and
581 /// their role in the API.
586 /// use std::path::Path;
588 /// let path = Path::new("/tmp/foo/bar.txt");
590 /// for component in path.components() {
591 /// println!("{:?}", component);
595 #[stable(feature = "rust1", since = "1.0.0")]
596 pub struct Components<'a> {
597 // The path left to parse components from
600 // The prefix as it was originally parsed, if any
601 prefix: Option<Prefix<'a>>,
603 // true if path *physically* has a root separator; for most Windows
604 // prefixes, it may have a "logical" rootseparator for the purposes of
605 // normalization, e.g. \\server\share == \\server\share\.
606 has_physical_root: bool,
608 // The iterator is double-ended, and these two states keep track of what has
609 // been produced from either end
614 /// An iterator over the components of a path, as `OsStr` slices.
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub struct Iter<'a> {
618 inner: Components<'a>,
621 impl<'a> Components<'a> {
622 // how long is the prefix, if any?
624 fn prefix_len(&self) -> usize {
625 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
629 fn prefix_verbatim(&self) -> bool {
630 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
633 /// how much of the prefix is left from the point of view of iteration?
635 fn prefix_remaining(&self) -> usize {
636 if self.front == State::Prefix {
643 // Given the iteration so far, how much of the pre-State::Body path is left?
645 fn len_before_body(&self) -> usize {
646 let root = if self.front <= State::StartDir && self.has_physical_root {
651 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
656 self.prefix_remaining() + root + cur_dir
659 // is the iteration complete?
661 fn finished(&self) -> bool {
662 self.front == State::Done || self.back == State::Done || self.front > self.back
666 fn is_sep_byte(&self, b: u8) -> bool {
667 if self.prefix_verbatim() {
674 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
679 /// use std::path::Path;
681 /// let mut components = Path::new("/tmp/foo/bar.txt").components();
682 /// components.next();
683 /// components.next();
685 /// assert_eq!(Path::new("foo/bar.txt"), components.as_path());
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn as_path(&self) -> &'a Path {
689 let mut comps = self.clone();
690 if comps.front == State::Body {
693 if comps.back == State::Body {
696 unsafe { Path::from_u8_slice(comps.path) }
699 /// Is the *original* path rooted?
700 fn has_root(&self) -> bool {
701 if self.has_physical_root {
704 if let Some(p) = self.prefix {
705 if p.has_implicit_root() {
712 /// Should the normalized path include a leading . ?
713 fn include_cur_dir(&self) -> bool {
717 let mut iter = self.path[self.prefix_len()..].iter();
718 match (iter.next(), iter.next()) {
719 (Some(&b'.'), None) => true,
720 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
725 // parse a given byte sequence into the corresponding path component
726 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
728 b"." if self.prefix_verbatim() => Some(Component::CurDir),
729 b"." => None, // . components are normalized away, except at
730 // the beginning of a path, which is treated
731 // separately via `include_cur_dir`
732 b".." => Some(Component::ParentDir),
734 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
738 // parse a component from the left, saying how many bytes to consume to
739 // remove the component
740 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
741 debug_assert!(self.front == State::Body);
742 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
743 None => (0, self.path),
744 Some(i) => (1, &self.path[..i]),
746 (comp.len() + extra, self.parse_single_component(comp))
749 // parse a component from the right, saying how many bytes to consume to
750 // remove the component
751 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
752 debug_assert!(self.back == State::Body);
753 let start = self.len_before_body();
754 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
755 None => (0, &self.path[start..]),
756 Some(i) => (1, &self.path[start + i + 1..]),
758 (comp.len() + extra, self.parse_single_component(comp))
761 // trim away repeated separators (i.e. empty components) on the left
762 fn trim_left(&mut self) {
763 while !self.path.is_empty() {
764 let (size, comp) = self.parse_next_component();
768 self.path = &self.path[size..];
773 // trim away repeated separators (i.e. empty components) on the right
774 fn trim_right(&mut self) {
775 while self.path.len() > self.len_before_body() {
776 let (size, comp) = self.parse_next_component_back();
780 self.path = &self.path[..self.path.len() - size];
785 /// Examine the next component without consuming it.
786 #[unstable(feature = "path_components_peek", issue = "27727")]
787 #[rustc_deprecated(reason = "use peekable() instead",
789 pub fn peek(&self) -> Option<Component<'a>> {
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl<'a> AsRef<Path> for Components<'a> {
796 fn as_ref(&self) -> &Path {
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl<'a> AsRef<OsStr> for Components<'a> {
803 fn as_ref(&self) -> &OsStr {
804 self.as_path().as_os_str()
809 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn as_path(&self) -> &'a Path {
816 #[stable(feature = "rust1", since = "1.0.0")]
817 impl<'a> AsRef<Path> for Iter<'a> {
818 fn as_ref(&self) -> &Path {
823 #[stable(feature = "rust1", since = "1.0.0")]
824 impl<'a> AsRef<OsStr> for Iter<'a> {
825 fn as_ref(&self) -> &OsStr {
826 self.as_path().as_os_str()
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl<'a> Iterator for Iter<'a> {
832 type Item = &'a OsStr;
834 fn next(&mut self) -> Option<&'a OsStr> {
835 self.inner.next().map(Component::as_os_str)
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<'a> DoubleEndedIterator for Iter<'a> {
841 fn next_back(&mut self) -> Option<&'a OsStr> {
842 self.inner.next_back().map(Component::as_os_str)
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<'a> Iterator for Components<'a> {
848 type Item = Component<'a>;
850 fn next(&mut self) -> Option<Component<'a>> {
851 while !self.finished() {
853 State::Prefix if self.prefix_len() > 0 => {
854 self.front = State::StartDir;
855 debug_assert!(self.prefix_len() <= self.path.len());
856 let raw = &self.path[..self.prefix_len()];
857 self.path = &self.path[self.prefix_len()..];
858 return Some(Component::Prefix(PrefixComponent {
859 raw: unsafe { u8_slice_as_os_str(raw) },
860 parsed: self.prefix.unwrap(),
864 self.front = State::StartDir;
867 self.front = State::Body;
868 if self.has_physical_root {
869 debug_assert!(!self.path.is_empty());
870 self.path = &self.path[1..];
871 return Some(Component::RootDir);
872 } else if let Some(p) = self.prefix {
873 if p.has_implicit_root() && !p.is_verbatim() {
874 return Some(Component::RootDir);
876 } else if self.include_cur_dir() {
877 debug_assert!(!self.path.is_empty());
878 self.path = &self.path[1..];
879 return Some(Component::CurDir);
882 State::Body if !self.path.is_empty() => {
883 let (size, comp) = self.parse_next_component();
884 self.path = &self.path[size..];
890 self.front = State::Done;
892 State::Done => unreachable!(),
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl<'a> DoubleEndedIterator for Components<'a> {
901 fn next_back(&mut self) -> Option<Component<'a>> {
902 while !self.finished() {
904 State::Body if self.path.len() > self.len_before_body() => {
905 let (size, comp) = self.parse_next_component_back();
906 self.path = &self.path[..self.path.len() - size];
912 self.back = State::StartDir;
915 self.back = State::Prefix;
916 if self.has_physical_root {
917 self.path = &self.path[..self.path.len() - 1];
918 return Some(Component::RootDir);
919 } else if let Some(p) = self.prefix {
920 if p.has_implicit_root() && !p.is_verbatim() {
921 return Some(Component::RootDir);
923 } else if self.include_cur_dir() {
924 self.path = &self.path[..self.path.len() - 1];
925 return Some(Component::CurDir);
928 State::Prefix if self.prefix_len() > 0 => {
929 self.back = State::Done;
930 return Some(Component::Prefix(PrefixComponent {
931 raw: unsafe { u8_slice_as_os_str(self.path) },
932 parsed: self.prefix.unwrap(),
936 self.back = State::Done;
939 State::Done => unreachable!(),
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<'a> cmp::PartialEq for Components<'a> {
948 fn eq(&self, other: &Components<'a>) -> bool {
949 Iterator::eq(self.clone(), other.clone())
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl<'a> cmp::Eq for Components<'a> {}
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<'a> cmp::PartialOrd for Components<'a> {
958 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
959 Iterator::partial_cmp(self.clone(), other.clone())
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl<'a> cmp::Ord for Components<'a> {
965 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
966 Iterator::cmp(self.clone(), other.clone())
970 ////////////////////////////////////////////////////////////////////////////////
971 // Basic types and traits
972 ////////////////////////////////////////////////////////////////////////////////
974 /// An owned, mutable path (akin to `String`).
976 /// This type provides methods like `push` and `set_extension` that mutate the
977 /// path in place. It also implements `Deref` to `Path`, meaning that all
978 /// methods on `Path` slices are available on `PathBuf` values as well.
980 /// More details about the overall approach can be found in
981 /// the module documentation.
986 /// use std::path::PathBuf;
988 /// let mut path = PathBuf::from("c:\\");
989 /// path.push("windows");
990 /// path.push("system32");
991 /// path.set_extension("dll");
994 #[stable(feature = "rust1", since = "1.0.0")]
1000 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
1001 unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) }
1004 /// Allocates an empty `PathBuf`.
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub fn new() -> PathBuf {
1007 PathBuf { inner: OsString::new() }
1010 /// Coerces to a `Path` slice.
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 pub fn as_path(&self) -> &Path {
1016 /// Extends `self` with `path`.
1018 /// If `path` is absolute, it replaces the current path.
1022 /// * if `path` has a root but no prefix (e.g. `\windows`), it
1023 /// replaces everything except for the prefix (if any) of `self`.
1024 /// * if `path` has a prefix but no root, it replaces `self`.
1029 /// use std::path::PathBuf;
1031 /// let mut path = PathBuf::new();
1032 /// path.push("/tmp");
1033 /// path.push("file.bk");
1034 /// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
1036 /// // Pushing an absolute path replaces the current path
1037 /// path.push("/etc/passwd");
1038 /// assert_eq!(path, PathBuf::from("/etc/passwd"));
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1042 self._push(path.as_ref())
1045 #[allow(deprecated)]
1046 fn _push(&mut self, path: &Path) {
1047 // in general, a separator is needed if the rightmost byte is not a separator
1048 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1050 // in the special case of `C:` on Windows, do *not* add a separator
1052 let comps = self.components();
1053 if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
1054 comps.prefix.unwrap().is_drive() {
1059 // absolute `path` replaces `self`
1060 if path.is_absolute() || path.prefix().is_some() {
1061 self.as_mut_vec().truncate(0);
1063 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
1064 } else if path.has_root() {
1065 let prefix_len = self.components().prefix_remaining();
1066 self.as_mut_vec().truncate(prefix_len);
1068 // `path` is a pure relative path
1069 } else if need_sep {
1070 self.inner.push(MAIN_SEP_STR);
1073 self.inner.push(path);
1076 /// Truncate `self` to `self.parent()`.
1078 /// Returns false and does nothing if `self.file_name()` is `None`.
1079 /// Otherwise, returns `true`.
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 pub fn pop(&mut self) -> bool {
1082 match self.parent().map(|p| p.as_u8_slice().len()) {
1084 self.as_mut_vec().truncate(len);
1091 /// Updates `self.file_name()` to `file_name`.
1093 /// If `self.file_name()` was `None`, this is equivalent to pushing
1099 /// use std::path::PathBuf;
1101 /// let mut buf = PathBuf::from("/");
1102 /// assert!(buf.file_name() == None);
1103 /// buf.set_file_name("bar");
1104 /// assert!(buf == PathBuf::from("/bar"));
1105 /// assert!(buf.file_name().is_some());
1106 /// buf.set_file_name("baz.txt");
1107 /// assert!(buf == PathBuf::from("/baz.txt"));
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1111 self._set_file_name(file_name.as_ref())
1114 fn _set_file_name(&mut self, file_name: &OsStr) {
1115 if self.file_name().is_some() {
1116 let popped = self.pop();
1117 debug_assert!(popped);
1119 self.push(file_name);
1122 /// Updates `self.extension()` to `extension`.
1124 /// If `self.file_name()` is `None`, does nothing and returns `false`.
1126 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
1127 /// is added; otherwise it is replaced.
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1130 self._set_extension(extension.as_ref())
1133 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1134 if self.file_name().is_none() {
1138 let mut stem = match self.file_stem() {
1139 Some(stem) => stem.to_os_string(),
1140 None => OsString::new(),
1143 if !os_str_as_u8_slice(extension).is_empty() {
1145 stem.push(extension);
1147 self.set_file_name(&stem);
1152 /// Consumes the `PathBuf`, yielding its internal `OsString` storage.
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn into_os_string(self) -> OsString {
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1161 fn from(s: &'a T) -> PathBuf {
1162 PathBuf::from(s.as_ref().to_os_string())
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl From<OsString> for PathBuf {
1168 fn from(s: OsString) -> PathBuf {
1169 PathBuf { inner: s }
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 impl From<String> for PathBuf {
1175 fn from(s: String) -> PathBuf {
1176 PathBuf::from(OsString::from(s))
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1182 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1183 let mut buf = PathBuf::new();
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1191 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1193 self.push(p.as_ref())
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 impl fmt::Debug for PathBuf {
1200 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1201 fmt::Debug::fmt(&**self, formatter)
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl ops::Deref for PathBuf {
1209 fn deref(&self) -> &Path {
1210 Path::new(&self.inner)
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl Borrow<Path> for PathBuf {
1216 fn borrow(&self) -> &Path {
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 #[allow(deprecated)]
1223 impl IntoCow<'static, Path> for PathBuf {
1224 fn into_cow(self) -> Cow<'static, Path> {
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 #[allow(deprecated)]
1231 impl<'a> IntoCow<'a, Path> for &'a Path {
1232 fn into_cow(self) -> Cow<'a, Path> {
1237 #[stable(feature = "cow_from_path", since = "1.6.0")]
1238 impl<'a> From<&'a Path> for Cow<'a, Path> {
1240 fn from(s: &'a Path) -> Cow<'a, Path> {
1245 #[stable(feature = "cow_from_path", since = "1.6.0")]
1246 impl<'a> From<PathBuf> for Cow<'a, Path> {
1248 fn from(s: PathBuf) -> Cow<'a, Path> {
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 impl ToOwned for Path {
1255 type Owned = PathBuf;
1256 fn to_owned(&self) -> PathBuf {
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl cmp::PartialEq for PathBuf {
1263 fn eq(&self, other: &PathBuf) -> bool {
1264 self.components() == other.components()
1268 #[stable(feature = "rust1", since = "1.0.0")]
1269 impl Hash for PathBuf {
1270 fn hash<H: Hasher>(&self, h: &mut H) {
1271 self.as_path().hash(h)
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl cmp::Eq for PathBuf {}
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl cmp::PartialOrd for PathBuf {
1280 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1281 self.components().partial_cmp(other.components())
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl cmp::Ord for PathBuf {
1287 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1288 self.components().cmp(other.components())
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl AsRef<OsStr> for PathBuf {
1294 fn as_ref(&self) -> &OsStr {
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl Into<OsString> for PathBuf {
1301 fn into(self) -> OsString {
1306 /// A slice of a path (akin to `str`).
1308 /// This type supports a number of operations for inspecting a path, including
1309 /// breaking the path into its components (separated by `/` or `\`, depending on
1310 /// the platform), extracting the file name, determining whether the path is
1311 /// absolute, and so on. More details about the overall approach can be found in
1312 /// the module documentation.
1314 /// This is an *unsized* type, meaning that it must always be used behind a
1315 /// pointer like `&` or `Box`.
1320 /// use std::path::Path;
1322 /// let path = Path::new("/tmp/foo/bar.txt");
1323 /// let file = path.file_name();
1324 /// let extension = path.extension();
1325 /// let parent_dir = path.parent();
1328 #[stable(feature = "rust1", since = "1.0.0")]
1333 /// An error returned from the `Path::strip_prefix` method indicating that the
1334 /// prefix was not found in `self`.
1335 #[derive(Debug, Clone, PartialEq, Eq)]
1336 #[stable(since = "1.7.0", feature = "strip_prefix")]
1337 pub struct StripPrefixError(());
1340 // The following (private!) function allows construction of a path from a u8
1341 // slice, which is only safe when it is known to follow the OsStr encoding.
1342 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1343 Path::new(u8_slice_as_os_str(s))
1345 // The following (private!) function reveals the byte encoding used for OsStr.
1346 fn as_u8_slice(&self) -> &[u8] {
1347 os_str_as_u8_slice(&self.inner)
1350 /// Directly wrap a string slice as a `Path` slice.
1352 /// This is a cost-free conversion.
1357 /// use std::path::Path;
1359 /// Path::new("foo.txt");
1362 /// You can create `Path`s from `String`s, or even other `Path`s:
1365 /// use std::path::Path;
1367 /// let string = String::from("foo.txt");
1368 /// let from_string = Path::new(&string);
1369 /// let from_path = Path::new(&from_string);
1370 /// assert_eq!(from_string, from_path);
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1374 unsafe { mem::transmute(s.as_ref()) }
1377 /// Yields the underlying `OsStr` slice.
1382 /// use std::path::Path;
1384 /// let os_str = Path::new("foo.txt").as_os_str();
1385 /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 pub fn as_os_str(&self) -> &OsStr {
1392 /// Yields a `&str` slice if the `Path` is valid unicode.
1394 /// This conversion may entail doing a check for UTF-8 validity.
1399 /// use std::path::Path;
1401 /// let path_str = Path::new("foo.txt").to_str();
1402 /// assert_eq!(path_str, Some("foo.txt"));
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub fn to_str(&self) -> Option<&str> {
1409 /// Converts a `Path` to a `Cow<str>`.
1411 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1416 /// use std::path::Path;
1418 /// let path_str = Path::new("foo.txt").to_string_lossy();
1419 /// assert_eq!(path_str, "foo.txt");
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub fn to_string_lossy(&self) -> Cow<str> {
1423 self.inner.to_string_lossy()
1426 /// Converts a `Path` to an owned `PathBuf`.
1431 /// use std::path::Path;
1433 /// let path_buf = Path::new("foo.txt").to_path_buf();
1434 /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt"));
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 pub fn to_path_buf(&self) -> PathBuf {
1438 PathBuf::from(self.inner.to_os_string())
1441 /// A path is *absolute* if it is independent of the current directory.
1443 /// * On Unix, a path is absolute if it starts with the root, so
1444 /// `is_absolute` and `has_root` are equivalent.
1446 /// * On Windows, a path is absolute if it has a prefix and starts with the
1447 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1448 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1453 /// use std::path::Path;
1455 /// assert!(!Path::new("foo.txt").is_absolute());
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 #[allow(deprecated)]
1459 pub fn is_absolute(&self) -> bool {
1460 self.has_root() && (cfg!(unix) || self.prefix().is_some())
1463 /// A path is *relative* if it is not absolute.
1468 /// use std::path::Path;
1470 /// assert!(Path::new("foo.txt").is_relative());
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn is_relative(&self) -> bool {
1477 /// Returns the *prefix* of a path, if any.
1479 /// Prefixes are relevant only for Windows paths, and consist of volumes
1480 /// like `C:`, UNC prefixes like `\\server`, and others described in more
1481 /// detail in `std::os::windows::PathExt`.
1482 #[unstable(feature = "path_prefix",
1483 reason = "uncertain whether to expose this convenience",
1485 #[rustc_deprecated(since = "1.7.0",
1486 reason = "inspect components().next() instead")]
1487 pub fn prefix(&self) -> Option<Prefix> {
1488 self.components().prefix
1491 /// A path has a root if the body of the path begins with the directory separator.
1493 /// * On Unix, a path has a root if it begins with `/`.
1495 /// * On Windows, a path has a root if it:
1496 /// * has no prefix and begins with a separator, e.g. `\\windows`
1497 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1498 /// * has any non-disk prefix, e.g. `\\server\share`
1503 /// use std::path::Path;
1505 /// assert!(Path::new("/etc/passwd").has_root());
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 pub fn has_root(&self) -> bool {
1509 self.components().has_root()
1512 /// The path without its final component, if any.
1514 /// Returns `None` if the path terminates in a root or prefix.
1519 /// use std::path::Path;
1521 /// let path = Path::new("/foo/bar");
1522 /// let parent = path.parent().unwrap();
1523 /// assert_eq!(parent, Path::new("/foo"));
1525 /// let grand_parent = parent.parent().unwrap();
1526 /// assert_eq!(grand_parent, Path::new("/"));
1527 /// assert_eq!(grand_parent.parent(), None);
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 pub fn parent(&self) -> Option<&Path> {
1531 let mut comps = self.components();
1532 let comp = comps.next_back();
1535 Component::Normal(_) |
1537 Component::ParentDir => Some(comps.as_path()),
1543 /// The final component of the path, if it is a normal file.
1545 /// If the path terminates in `.`, `..`, or consists solely of a root of
1546 /// prefix, `file_name` will return `None`.
1551 /// use std::path::Path;
1552 /// use std::ffi::OsStr;
1554 /// let path = Path::new("foo.txt");
1555 /// let os_str = OsStr::new("foo.txt");
1557 /// assert_eq!(Some(os_str), path.file_name());
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 pub fn file_name(&self) -> Option<&OsStr> {
1561 self.components().next_back().and_then(|p| {
1563 Component::Normal(p) => Some(p.as_ref()),
1569 /// Returns a path that, when joined onto `base`, yields `self`.
1571 /// If `base` is not a prefix of `self` (i.e. `starts_with`
1572 /// returns false), then `relative_from` returns `None`.
1573 #[unstable(feature = "path_relative_from", reason = "see #23284",
1575 #[rustc_deprecated(since = "1.7.0", reason = "renamed to strip_prefix")]
1576 pub fn relative_from<'a, P: ?Sized + AsRef<Path>>(&'a self, base: &'a P) -> Option<&Path> {
1577 self._strip_prefix(base.as_ref()).ok()
1580 /// Returns a path that, when joined onto `base`, yields `self`.
1584 /// If `base` is not a prefix of `self` (i.e. `starts_with`
1585 /// returns `false`), returns `Err`.
1586 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
1587 pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P)
1588 -> Result<&'a Path, StripPrefixError>
1589 where P: AsRef<Path>
1591 self._strip_prefix(base.as_ref())
1594 fn _strip_prefix<'a>(&'a self, base: &'a Path)
1595 -> Result<&'a Path, StripPrefixError> {
1596 iter_after(self.components(), base.components())
1597 .map(|c| c.as_path())
1598 .ok_or(StripPrefixError(()))
1601 /// Determines whether `base` is a prefix of `self`.
1603 /// Only considers whole path components to match.
1608 /// use std::path::Path;
1610 /// let path = Path::new("/etc/passwd");
1612 /// assert!(path.starts_with("/etc"));
1614 /// assert!(!path.starts_with("/e"));
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1618 self._starts_with(base.as_ref())
1621 fn _starts_with(&self, base: &Path) -> bool {
1622 iter_after(self.components(), base.components()).is_some()
1625 /// Determines whether `child` is a suffix of `self`.
1627 /// Only considers whole path components to match.
1632 /// use std::path::Path;
1634 /// let path = Path::new("/etc/passwd");
1636 /// assert!(path.ends_with("passwd"));
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1640 self._ends_with(child.as_ref())
1643 fn _ends_with(&self, child: &Path) -> bool {
1644 iter_after(self.components().rev(), child.components().rev()).is_some()
1647 /// Extracts the stem (non-extension) portion of `self.file_name()`.
1651 /// * None, if there is no file name;
1652 /// * The entire file name if there is no embedded `.`;
1653 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1654 /// * Otherwise, the portion of the file name before the final `.`
1659 /// use std::path::Path;
1661 /// let path = Path::new("foo.rs");
1663 /// assert_eq!("foo", path.file_stem().unwrap());
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 pub fn file_stem(&self) -> Option<&OsStr> {
1667 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1670 /// Extracts the extension of `self.file_name()`, if possible.
1672 /// The extension is:
1674 /// * None, if there is no file name;
1675 /// * None, if there is no embedded `.`;
1676 /// * None, if the file name begins with `.` and has no other `.`s within;
1677 /// * Otherwise, the portion of the file name after the final `.`
1682 /// use std::path::Path;
1684 /// let path = Path::new("foo.rs");
1686 /// assert_eq!("rs", path.extension().unwrap());
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 pub fn extension(&self) -> Option<&OsStr> {
1690 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1693 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1695 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1700 /// use std::path::{Path, PathBuf};
1702 /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1706 self._join(path.as_ref())
1709 fn _join(&self, path: &Path) -> PathBuf {
1710 let mut buf = self.to_path_buf();
1715 /// Creates an owned `PathBuf` like `self` but with the given file name.
1717 /// See `PathBuf::set_file_name` for more details.
1722 /// use std::path::{Path, PathBuf};
1724 /// let path = Path::new("/tmp/foo.txt");
1725 /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1729 self._with_file_name(file_name.as_ref())
1732 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
1733 let mut buf = self.to_path_buf();
1734 buf.set_file_name(file_name);
1738 /// Creates an owned `PathBuf` like `self` but with the given extension.
1740 /// See `PathBuf::set_extension` for more details.
1745 /// use std::path::{Path, PathBuf};
1747 /// let path = Path::new("foo.rs");
1748 /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1752 self._with_extension(extension.as_ref())
1755 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
1756 let mut buf = self.to_path_buf();
1757 buf.set_extension(extension);
1761 /// Produce an iterator over the components of the path.
1766 /// use std::path::{Path, Component};
1767 /// use std::ffi::OsStr;
1769 /// let mut components = Path::new("/tmp/foo.txt").components();
1771 /// assert_eq!(components.next(), Some(Component::RootDir));
1772 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
1773 /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
1774 /// assert_eq!(components.next(), None)
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 pub fn components(&self) -> Components {
1778 let prefix = parse_prefix(self.as_os_str());
1780 path: self.as_u8_slice(),
1782 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1783 front: State::Prefix,
1788 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1793 /// use std::path::{self, Path};
1794 /// use std::ffi::OsStr;
1796 /// let mut it = Path::new("/tmp/foo.txt").iter();
1797 /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
1798 /// assert_eq!(it.next(), Some(OsStr::new("tmp")));
1799 /// assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
1800 /// assert_eq!(it.next(), None)
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 pub fn iter(&self) -> Iter {
1804 Iter { inner: self.components() }
1807 /// Returns an object that implements `Display` for safely printing paths
1808 /// that may contain non-Unicode data.
1813 /// use std::path::Path;
1815 /// let path = Path::new("/tmp/foo.rs");
1817 /// println!("{}", path.display());
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 pub fn display(&self) -> Display {
1821 Display { path: self }
1825 /// Query the file system to get information about a file, directory, etc.
1827 /// This function will traverse symbolic links to query information about the
1828 /// destination file.
1830 /// This is an alias to `fs::metadata`.
1831 #[stable(feature = "path_ext", since = "1.5.0")]
1832 pub fn metadata(&self) -> io::Result<fs::Metadata> {
1836 /// Query the metadata about a file without following symlinks.
1838 /// This is an alias to `fs::symlink_metadata`.
1839 #[stable(feature = "path_ext", since = "1.5.0")]
1840 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1841 fs::symlink_metadata(self)
1844 /// Returns the canonical form of the path with all intermediate components
1845 /// normalized and symbolic links resolved.
1847 /// This is an alias to `fs::canonicalize`.
1848 #[stable(feature = "path_ext", since = "1.5.0")]
1849 pub fn canonicalize(&self) -> io::Result<PathBuf> {
1850 fs::canonicalize(self)
1853 /// Reads a symbolic link, returning the file that the link points to.
1855 /// This is an alias to `fs::read_link`.
1856 #[stable(feature = "path_ext", since = "1.5.0")]
1857 pub fn read_link(&self) -> io::Result<PathBuf> {
1861 /// Returns an iterator over the entries within a directory.
1863 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1864 /// be encountered after an iterator is initially constructed.
1866 /// This is an alias to `fs::read_dir`.
1867 #[stable(feature = "path_ext", since = "1.5.0")]
1868 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
1872 /// Returns whether the path points at an existing entity.
1874 /// This function will traverse symbolic links to query information about the
1875 /// destination file. In case of broken symbolic links this will return `false`.
1880 /// use std::path::Path;
1881 /// assert_eq!(Path::new("does_not_exist.txt").exists(), false);
1883 #[stable(feature = "path_ext", since = "1.5.0")]
1884 pub fn exists(&self) -> bool {
1885 fs::metadata(self).is_ok()
1888 /// Returns whether the path is pointing at a regular file.
1890 /// This function will traverse symbolic links to query information about the
1891 /// destination file. In case of broken symbolic links this will return `false`.
1896 /// use std::path::Path;
1897 /// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
1898 /// assert_eq!(Path::new("a_file.txt").is_file(), true);
1900 #[stable(feature = "path_ext", since = "1.5.0")]
1901 pub fn is_file(&self) -> bool {
1902 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
1905 /// Returns whether the path is pointing at a directory.
1907 /// This function will traverse symbolic links to query information about the
1908 /// destination file. In case of broken symbolic links this will return `false`.
1913 /// use std::path::Path;
1914 /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
1915 /// assert_eq!(Path::new("a_file.txt").is_dir(), false);
1917 #[stable(feature = "path_ext", since = "1.5.0")]
1918 pub fn is_dir(&self) -> bool {
1919 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
1923 #[stable(feature = "rust1", since = "1.0.0")]
1924 impl AsRef<OsStr> for Path {
1925 fn as_ref(&self) -> &OsStr {
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 impl fmt::Debug for Path {
1932 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1933 self.inner.fmt(formatter)
1937 /// Helper struct for safely printing paths with `format!()` and `{}`
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 pub struct Display<'a> {
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl<'a> fmt::Debug for Display<'a> {
1945 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1946 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1950 #[stable(feature = "rust1", since = "1.0.0")]
1951 impl<'a> fmt::Display for Display<'a> {
1952 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1953 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 impl cmp::PartialEq for Path {
1959 fn eq(&self, other: &Path) -> bool {
1960 self.components().eq(other.components())
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl Hash for Path {
1966 fn hash<H: Hasher>(&self, h: &mut H) {
1967 for component in self.components() {
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl cmp::Eq for Path {}
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl cmp::PartialOrd for Path {
1978 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1979 self.components().partial_cmp(other.components())
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl cmp::Ord for Path {
1985 fn cmp(&self, other: &Path) -> cmp::Ordering {
1986 self.components().cmp(other.components())
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl AsRef<Path> for Path {
1992 fn as_ref(&self) -> &Path {
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 impl AsRef<Path> for OsStr {
1999 fn as_ref(&self) -> &Path {
2004 #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
2005 impl<'a> AsRef<Path> for Cow<'a, OsStr> {
2006 fn as_ref(&self) -> &Path {
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 impl AsRef<Path> for OsString {
2013 fn as_ref(&self) -> &Path {
2018 #[stable(feature = "rust1", since = "1.0.0")]
2019 impl AsRef<Path> for str {
2020 fn as_ref(&self) -> &Path {
2025 #[stable(feature = "rust1", since = "1.0.0")]
2026 impl AsRef<Path> for String {
2027 fn as_ref(&self) -> &Path {
2032 #[stable(feature = "rust1", since = "1.0.0")]
2033 impl AsRef<Path> for PathBuf {
2034 fn as_ref(&self) -> &Path {
2039 #[stable(feature = "path_into_iter", since = "1.6.0")]
2040 impl<'a> IntoIterator for &'a PathBuf {
2041 type Item = &'a OsStr;
2042 type IntoIter = Iter<'a>;
2043 fn into_iter(self) -> Iter<'a> { self.iter() }
2046 #[stable(feature = "path_into_iter", since = "1.6.0")]
2047 impl<'a> IntoIterator for &'a Path {
2048 type Item = &'a OsStr;
2049 type IntoIter = Iter<'a>;
2050 fn into_iter(self) -> Iter<'a> { self.iter() }
2053 macro_rules! impl_cmp {
2054 ($lhs:ty, $rhs: ty) => {
2055 #[stable(feature = "partialeq_path", since = "1.6.0")]
2056 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2058 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
2061 #[stable(feature = "partialeq_path", since = "1.6.0")]
2062 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2064 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
2067 #[stable(feature = "cmp_path", since = "1.8.0")]
2068 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2070 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2071 <Path as PartialOrd>::partial_cmp(self, other)
2075 #[stable(feature = "cmp_path", since = "1.8.0")]
2076 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2078 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2079 <Path as PartialOrd>::partial_cmp(self, other)
2085 impl_cmp!(PathBuf, Path);
2086 impl_cmp!(PathBuf, &'a Path);
2087 impl_cmp!(Cow<'a, Path>, Path);
2088 impl_cmp!(Cow<'a, Path>, &'b Path);
2089 impl_cmp!(Cow<'a, Path>, PathBuf);
2091 macro_rules! impl_cmp_os_str {
2092 ($lhs:ty, $rhs: ty) => {
2093 #[stable(feature = "cmp_path", since = "1.8.0")]
2094 impl<'a, 'b> PartialEq<$rhs> for $lhs {
2096 fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
2099 #[stable(feature = "cmp_path", since = "1.8.0")]
2100 impl<'a, 'b> PartialEq<$lhs> for $rhs {
2102 fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
2105 #[stable(feature = "cmp_path", since = "1.8.0")]
2106 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
2108 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
2109 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
2113 #[stable(feature = "cmp_path", since = "1.8.0")]
2114 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
2116 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
2117 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
2123 impl_cmp_os_str!(PathBuf, OsStr);
2124 impl_cmp_os_str!(PathBuf, &'a OsStr);
2125 impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>);
2126 impl_cmp_os_str!(PathBuf, OsString);
2127 impl_cmp_os_str!(Path, OsStr);
2128 impl_cmp_os_str!(Path, &'a OsStr);
2129 impl_cmp_os_str!(Path, Cow<'a, OsStr>);
2130 impl_cmp_os_str!(Path, OsString);
2131 impl_cmp_os_str!(&'a Path, OsStr);
2132 impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>);
2133 impl_cmp_os_str!(&'a Path, OsString);
2134 impl_cmp_os_str!(Cow<'a, Path>, OsStr);
2135 impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr);
2136 impl_cmp_os_str!(Cow<'a, Path>, OsString);
2138 #[stable(since = "1.7.0", feature = "strip_prefix")]
2139 impl fmt::Display for StripPrefixError {
2140 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2141 self.description().fmt(f)
2145 #[stable(since = "1.7.0", feature = "strip_prefix")]
2146 impl Error for StripPrefixError {
2147 fn description(&self) -> &str { "prefix not found" }
2153 use string::{ToString, String};
2157 ($path:expr, iter: $iter:expr) => (
2159 let path = Path::new($path);
2161 // Forward iteration
2162 let comps = path.iter()
2163 .map(|p| p.to_string_lossy().into_owned())
2164 .collect::<Vec<String>>();
2165 let exp: &[&str] = &$iter;
2166 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
2167 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
2170 // Reverse iteration
2171 let comps = Path::new($path).iter().rev()
2172 .map(|p| p.to_string_lossy().into_owned())
2173 .collect::<Vec<String>>();
2174 let exps = exps.into_iter().rev().collect::<Vec<String>>();
2175 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
2180 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
2182 let path = Path::new($path);
2184 let act_root = path.has_root();
2185 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
2186 $has_root, act_root);
2188 let act_abs = path.is_absolute();
2189 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
2190 $is_absolute, act_abs);
2194 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
2196 let path = Path::new($path);
2198 let parent = path.parent().map(|p| p.to_str().unwrap());
2199 let exp_parent: Option<&str> = $parent;
2200 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
2201 exp_parent, parent);
2203 let file = path.file_name().map(|p| p.to_str().unwrap());
2204 let exp_file: Option<&str> = $file;
2205 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
2210 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
2212 let path = Path::new($path);
2214 let stem = path.file_stem().map(|p| p.to_str().unwrap());
2215 let exp_stem: Option<&str> = $file_stem;
2216 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
2219 let ext = path.extension().map(|p| p.to_str().unwrap());
2220 let exp_ext: Option<&str> = $extension;
2221 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
2226 ($path:expr, iter: $iter:expr,
2227 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
2228 parent: $parent:expr, file_name: $file:expr,
2229 file_stem: $file_stem:expr, extension: $extension:expr) => (
2231 t!($path, iter: $iter);
2232 t!($path, has_root: $has_root, is_absolute: $is_absolute);
2233 t!($path, parent: $parent, file_name: $file);
2234 t!($path, file_stem: $file_stem, extension: $extension);
2240 #[allow(deprecated)]
2242 use borrow::{Cow, IntoCow};
2244 let static_path = Path::new("/home/foo");
2245 let static_cow_path: Cow<'static, Path> = static_path.into_cow();
2246 let pathbuf = PathBuf::from("/home/foo");
2249 let path: &Path = &pathbuf;
2250 let borrowed_cow_path: Cow<Path> = path.into_cow();
2252 assert_eq!(static_cow_path, borrowed_cow_path);
2255 let owned_cow_path: Cow<'static, Path> = pathbuf.into_cow();
2257 assert_eq!(static_cow_path, owned_cow_path);
2264 let static_path = Path::new("/home/foo");
2265 let static_cow_path: Cow<'static, Path> = static_path.into();
2266 let pathbuf = PathBuf::from("/home/foo");
2269 let path: &Path = &pathbuf;
2270 let borrowed_cow_path: Cow<Path> = path.into();
2272 assert_eq!(static_cow_path, borrowed_cow_path);
2275 let owned_cow_path: Cow<'static, Path> = pathbuf.into();
2277 assert_eq!(static_cow_path, owned_cow_path);
2282 pub fn test_decompositions_unix() {
2298 file_name: Some("foo"),
2299 file_stem: Some("foo"),
2318 file_name: Some("foo"),
2319 file_stem: Some("foo"),
2328 file_name: Some("foo"),
2329 file_stem: Some("foo"),
2338 file_name: Some("foo"),
2339 file_stem: Some("foo"),
2344 iter: ["foo", "bar"],
2347 parent: Some("foo"),
2348 file_name: Some("bar"),
2349 file_stem: Some("bar"),
2354 iter: ["/", "foo", "bar"],
2357 parent: Some("/foo"),
2358 file_name: Some("bar"),
2359 file_stem: Some("bar"),
2368 file_name: Some("foo"),
2369 file_stem: Some("foo"),
2374 iter: ["/", "foo", "bar"],
2377 parent: Some("///foo"),
2378 file_name: Some("bar"),
2379 file_stem: Some("bar"),
2418 file_name: Some("foo"),
2419 file_stem: Some("foo"),
2424 iter: ["foo", ".."],
2427 parent: Some("foo"),
2438 file_name: Some("foo"),
2439 file_stem: Some("foo"),
2444 iter: ["foo", "bar"],
2447 parent: Some("foo"),
2448 file_name: Some("bar"),
2449 file_stem: Some("bar"),
2454 iter: ["foo", ".."],
2457 parent: Some("foo"),
2464 iter: ["foo", "..", "bar"],
2467 parent: Some("foo/.."),
2468 file_name: Some("bar"),
2469 file_stem: Some("bar"),
2478 file_name: Some("a"),
2479 file_stem: Some("a"),
2508 file_name: Some("b"),
2509 file_stem: Some("b"),
2518 file_name: Some("b"),
2519 file_stem: Some("b"),
2528 file_name: Some("b"),
2529 file_stem: Some("b"),
2534 iter: ["a", "b", "c"],
2537 parent: Some("a/b"),
2538 file_name: Some("c"),
2539 file_stem: Some("c"),
2548 file_name: Some(".foo"),
2549 file_stem: Some(".foo"),
2556 pub fn test_decompositions_windows() {
2572 file_name: Some("foo"),
2573 file_stem: Some("foo"),
2628 iter: ["\\", "foo"],
2632 file_name: Some("foo"),
2633 file_stem: Some("foo"),
2642 file_name: Some("foo"),
2643 file_stem: Some("foo"),
2648 iter: ["\\", "foo"],
2652 file_name: Some("foo"),
2653 file_stem: Some("foo"),
2658 iter: ["foo", "bar"],
2661 parent: Some("foo"),
2662 file_name: Some("bar"),
2663 file_stem: Some("bar"),
2668 iter: ["\\", "foo", "bar"],
2671 parent: Some("/foo"),
2672 file_name: Some("bar"),
2673 file_stem: Some("bar"),
2678 iter: ["\\", "foo"],
2682 file_name: Some("foo"),
2683 file_stem: Some("foo"),
2688 iter: ["\\", "foo", "bar"],
2691 parent: Some("///foo"),
2692 file_name: Some("bar"),
2693 file_stem: Some("bar"),
2732 file_name: Some("foo"),
2733 file_stem: Some("foo"),
2738 iter: ["foo", ".."],
2741 parent: Some("foo"),
2752 file_name: Some("foo"),
2753 file_stem: Some("foo"),
2758 iter: ["foo", "bar"],
2761 parent: Some("foo"),
2762 file_name: Some("bar"),
2763 file_stem: Some("bar"),
2768 iter: ["foo", ".."],
2771 parent: Some("foo"),
2778 iter: ["foo", "..", "bar"],
2781 parent: Some("foo/.."),
2782 file_name: Some("bar"),
2783 file_stem: Some("bar"),
2792 file_name: Some("a"),
2793 file_stem: Some("a"),
2822 file_name: Some("b"),
2823 file_stem: Some("b"),
2832 file_name: Some("b"),
2833 file_stem: Some("b"),
2842 file_name: Some("b"),
2843 file_stem: Some("b"),
2848 iter: ["a", "b", "c"],
2851 parent: Some("a/b"),
2852 file_name: Some("c"),
2853 file_stem: Some("c"),
2857 iter: ["a", "b", "c"],
2860 parent: Some("a\\b"),
2861 file_name: Some("c"),
2862 file_stem: Some("c"),
2871 file_name: Some("a"),
2872 file_stem: Some("a"),
2877 iter: ["c:", "\\", "foo.txt"],
2880 parent: Some("c:\\"),
2881 file_name: Some("foo.txt"),
2882 file_stem: Some("foo"),
2883 extension: Some("txt")
2886 t!("\\\\server\\share\\foo.txt",
2887 iter: ["\\\\server\\share", "\\", "foo.txt"],
2890 parent: Some("\\\\server\\share\\"),
2891 file_name: Some("foo.txt"),
2892 file_stem: Some("foo"),
2893 extension: Some("txt")
2896 t!("\\\\server\\share",
2897 iter: ["\\\\server\\share", "\\"],
2907 iter: ["\\", "server"],
2911 file_name: Some("server"),
2912 file_stem: Some("server"),
2916 t!("\\\\?\\bar\\foo.txt",
2917 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2920 parent: Some("\\\\?\\bar\\"),
2921 file_name: Some("foo.txt"),
2922 file_stem: Some("foo"),
2923 extension: Some("txt")
2927 iter: ["\\\\?\\bar"],
2946 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2947 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2950 parent: Some("\\\\?\\UNC\\server\\share\\"),
2951 file_name: Some("foo.txt"),
2952 file_stem: Some("foo"),
2953 extension: Some("txt")
2956 t!("\\\\?\\UNC\\server",
2957 iter: ["\\\\?\\UNC\\server"],
2967 iter: ["\\\\?\\UNC\\"],
2976 t!("\\\\?\\C:\\foo.txt",
2977 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2980 parent: Some("\\\\?\\C:\\"),
2981 file_name: Some("foo.txt"),
2982 file_stem: Some("foo"),
2983 extension: Some("txt")
2988 iter: ["\\\\?\\C:", "\\"],
2999 iter: ["\\\\?\\C:"],
3009 t!("\\\\?\\foo/bar",
3010 iter: ["\\\\?\\foo/bar"],
3021 iter: ["\\\\?\\C:/foo"],
3031 t!("\\\\.\\foo\\bar",
3032 iter: ["\\\\.\\foo", "\\", "bar"],
3035 parent: Some("\\\\.\\foo\\"),
3036 file_name: Some("bar"),
3037 file_stem: Some("bar"),
3043 iter: ["\\\\.\\foo", "\\"],
3053 t!("\\\\.\\foo/bar",
3054 iter: ["\\\\.\\foo/bar", "\\"],
3064 t!("\\\\.\\foo\\bar/baz",
3065 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
3068 parent: Some("\\\\.\\foo\\bar"),
3069 file_name: Some("baz"),
3070 file_stem: Some("baz"),
3076 iter: ["\\\\.\\", "\\"],
3086 iter: ["\\\\?\\a", "\\", "b"],
3089 parent: Some("\\\\?\\a\\"),
3090 file_name: Some("b"),
3091 file_stem: Some("b"),
3097 pub fn test_stem_ext() {
3099 file_stem: Some("foo"),
3104 file_stem: Some("foo"),
3109 file_stem: Some(".foo"),
3114 file_stem: Some("foo"),
3115 extension: Some("txt")
3119 file_stem: Some("foo.bar"),
3120 extension: Some("txt")
3124 file_stem: Some("foo.bar"),
3145 pub fn test_push() {
3147 ($path:expr, $push:expr, $expected:expr) => ( {
3148 let mut actual = PathBuf::from($path);
3150 assert!(actual.to_str() == Some($expected),
3151 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
3152 $push, $path, $expected, actual.to_str().unwrap());
3157 tp!("", "foo", "foo");
3158 tp!("foo", "bar", "foo/bar");
3159 tp!("foo/", "bar", "foo/bar");
3160 tp!("foo//", "bar", "foo//bar");
3161 tp!("foo/.", "bar", "foo/./bar");
3162 tp!("foo./.", "bar", "foo././bar");
3163 tp!("foo", "", "foo/");
3164 tp!("foo", ".", "foo/.");
3165 tp!("foo", "..", "foo/..");
3166 tp!("foo", "/", "/");
3167 tp!("/foo/bar", "/", "/");
3168 tp!("/foo/bar", "/baz", "/baz");
3169 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
3171 tp!("", "foo", "foo");
3172 tp!("foo", "bar", r"foo\bar");
3173 tp!("foo/", "bar", r"foo/bar");
3174 tp!(r"foo\", "bar", r"foo\bar");
3175 tp!("foo//", "bar", r"foo//bar");
3176 tp!(r"foo\\", "bar", r"foo\\bar");
3177 tp!("foo/.", "bar", r"foo/.\bar");
3178 tp!("foo./.", "bar", r"foo./.\bar");
3179 tp!(r"foo\.", "bar", r"foo\.\bar");
3180 tp!(r"foo.\.", "bar", r"foo.\.\bar");
3181 tp!("foo", "", "foo\\");
3182 tp!("foo", ".", r"foo\.");
3183 tp!("foo", "..", r"foo\..");
3184 tp!("foo", "/", "/");
3185 tp!("foo", r"\", r"\");
3186 tp!("/foo/bar", "/", "/");
3187 tp!(r"\foo\bar", r"\", r"\");
3188 tp!("/foo/bar", "/baz", "/baz");
3189 tp!("/foo/bar", r"\baz", r"\baz");
3190 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
3191 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
3193 tp!("c:\\", "windows", "c:\\windows");
3194 tp!("c:", "windows", "c:windows");
3196 tp!("a\\b\\c", "d", "a\\b\\c\\d");
3197 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
3198 tp!("a\\b", "c\\d", "a\\b\\c\\d");
3199 tp!("a\\b", "\\c\\d", "\\c\\d");
3200 tp!("a\\b", ".", "a\\b\\.");
3201 tp!("a\\b", "..\\c", "a\\b\\..\\c");
3202 tp!("a\\b", "C:a.txt", "C:a.txt");
3203 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
3204 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
3205 tp!("C:\\a\\b\\c", "C:d", "C:d");
3206 tp!("C:a\\b\\c", "C:d", "C:d");
3207 tp!("C:", r"a\b\c", r"C:a\b\c");
3208 tp!("C:", r"..\a", r"C:..\a");
3209 tp!("\\\\server\\share\\foo",
3211 "\\\\server\\share\\foo\\bar");
3212 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
3213 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
3214 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
3215 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
3216 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
3217 tp!("\\\\?\\UNC\\server\\share\\foo",
3219 "\\\\?\\UNC\\server\\share\\foo\\bar");
3220 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
3221 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
3223 // Note: modified from old path API
3224 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
3227 "\\\\?\\UNC\\server\\share",
3228 "\\\\?\\UNC\\server\\share");
3229 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
3230 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
3231 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
3232 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
3234 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
3241 ($path:expr, $expected:expr, $output:expr) => ( {
3242 let mut actual = PathBuf::from($path);
3243 let output = actual.pop();
3244 assert!(actual.to_str() == Some($expected) && output == $output,
3245 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3246 $path, $expected, $output,
3247 actual.to_str().unwrap(), output);
3252 tp!("/", "/", false);
3253 tp!("foo", "", true);
3255 tp!("/foo", "/", true);
3256 tp!("/foo/bar", "/foo", true);
3257 tp!("foo/bar", "foo", true);
3258 tp!("foo/.", "", true);
3259 tp!("foo//bar", "foo", true);
3262 tp!("a\\b\\c", "a\\b", true);
3263 tp!("\\a", "\\", true);
3264 tp!("\\", "\\", false);
3266 tp!("C:\\a\\b", "C:\\a", true);
3267 tp!("C:\\a", "C:\\", true);
3268 tp!("C:\\", "C:\\", false);
3269 tp!("C:a\\b", "C:a", true);
3270 tp!("C:a", "C:", true);
3271 tp!("C:", "C:", false);
3272 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
3273 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
3274 tp!("\\\\server\\share", "\\\\server\\share", false);
3275 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
3276 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
3277 tp!("\\\\?\\a", "\\\\?\\a", false);
3278 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
3279 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
3280 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
3281 tp!("\\\\?\\UNC\\server\\share\\a\\b",
3282 "\\\\?\\UNC\\server\\share\\a",
3284 tp!("\\\\?\\UNC\\server\\share\\a",
3285 "\\\\?\\UNC\\server\\share\\",
3287 tp!("\\\\?\\UNC\\server\\share",
3288 "\\\\?\\UNC\\server\\share",
3290 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
3291 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
3292 tp!("\\\\.\\a", "\\\\.\\a", false);
3294 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
3299 pub fn test_set_file_name() {
3301 ($path:expr, $file:expr, $expected:expr) => ( {
3302 let mut p = PathBuf::from($path);
3303 p.set_file_name($file);
3304 assert!(p.to_str() == Some($expected),
3305 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
3306 $path, $file, $expected,
3307 p.to_str().unwrap());
3311 tfn!("foo", "foo", "foo");
3312 tfn!("foo", "bar", "bar");
3313 tfn!("foo", "", "");
3314 tfn!("", "foo", "foo");
3316 tfn!(".", "foo", "./foo");
3317 tfn!("foo/", "bar", "bar");
3318 tfn!("foo/.", "bar", "bar");
3319 tfn!("..", "foo", "../foo");
3320 tfn!("foo/..", "bar", "foo/../bar");
3321 tfn!("/", "foo", "/foo");
3323 tfn!(".", "foo", r".\foo");
3324 tfn!(r"foo\", "bar", r"bar");
3325 tfn!(r"foo\.", "bar", r"bar");
3326 tfn!("..", "foo", r"..\foo");
3327 tfn!(r"foo\..", "bar", r"foo\..\bar");
3328 tfn!(r"\", "foo", r"\foo");
3333 pub fn test_set_extension() {
3335 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
3336 let mut p = PathBuf::from($path);
3337 let output = p.set_extension($ext);
3338 assert!(p.to_str() == Some($expected) && output == $output,
3339 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
3340 $path, $ext, $expected, $output,
3341 p.to_str().unwrap(), output);
3345 tfe!("foo", "txt", "foo.txt", true);
3346 tfe!("foo.bar", "txt", "foo.txt", true);
3347 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
3348 tfe!(".test", "txt", ".test.txt", true);
3349 tfe!("foo.txt", "", "foo", true);
3350 tfe!("foo", "", "foo", true);
3351 tfe!("", "foo", "", false);
3352 tfe!(".", "foo", ".", false);
3353 tfe!("foo/", "bar", "foo.bar", true);
3354 tfe!("foo/.", "bar", "foo.bar", true);
3355 tfe!("..", "foo", "..", false);
3356 tfe!("foo/..", "bar", "foo/..", false);
3357 tfe!("/", "foo", "/", false);
3361 fn test_eq_recievers() {
3364 let borrowed: &Path = Path::new("foo/bar");
3365 let mut owned: PathBuf = PathBuf::new();
3368 let borrowed_cow: Cow<Path> = borrowed.into();
3369 let owned_cow: Cow<Path> = owned.clone().into();
3372 ($($current:expr),+) => {
3374 assert_eq!($current, borrowed);
3375 assert_eq!($current, owned);
3376 assert_eq!($current, borrowed_cow);
3377 assert_eq!($current, owned_cow);
3382 t!(borrowed, owned, borrowed_cow, owned_cow);
3386 pub fn test_compare() {
3387 use hash::{Hash, Hasher, SipHasher};
3389 fn hash<T: Hash>(t: T) -> u64 {
3390 let mut s = SipHasher::new_with_keys(0, 0);
3396 ($path1:expr, $path2:expr, eq: $eq:expr,
3397 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
3398 relative_from: $relative_from:expr) => ({
3399 let path1 = Path::new($path1);
3400 let path2 = Path::new($path2);
3402 let eq = path1 == path2;
3403 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
3404 $path1, $path2, $eq, eq);
3405 assert!($eq == (hash(path1) == hash(path2)),
3406 "{:?} == {:?}, expected {:?}, got {} and {}",
3407 $path1, $path2, $eq, hash(path1), hash(path2));
3409 let starts_with = path1.starts_with(path2);
3410 assert!(starts_with == $starts_with,
3411 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3412 $starts_with, starts_with);
3414 let ends_with = path1.ends_with(path2);
3415 assert!(ends_with == $ends_with,
3416 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
3417 $ends_with, ends_with);
3419 let relative_from = path1.strip_prefix(path2)
3420 .map(|p| p.to_str().unwrap())
3422 let exp: Option<&str> = $relative_from;
3423 assert!(relative_from == exp,
3424 "{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
3425 $path1, $path2, exp, relative_from);
3433 relative_from: Some("")
3440 relative_from: Some("foo")
3454 relative_from: Some("")
3461 relative_from: Some("")
3464 tc!("foo/bar", "foo",
3468 relative_from: Some("bar")
3471 tc!("foo/bar/baz", "foo/bar",
3475 relative_from: Some("baz")
3478 tc!("foo/bar", "foo/bar/baz",
3485 tc!("./foo/bar/", ".",
3489 relative_from: Some("foo/bar")
3493 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3494 r"c:\src\rust\cargo-test\test",
3498 relative_from: Some("Cargo.toml")
3501 tc!(r"c:\foo", r"C:\foo",
3505 relative_from: Some("")