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 determined.
53 //! A path can always be reconstructed into an *equivalent* path by
54 //! putting together its components via `push`. Syntactically, the
55 //! paths may differ by the normalization described below.
57 //! ### Component types
59 //! Components come in several types:
61 //! * Normal components are the default: standard references to files or
62 //! directories. The path `a/b` has two normal components, `a` and `b`.
64 //! * Current directory components represent the `.` character. For example,
65 //! `./a` has a current directory component and a normal component `a`.
67 //! * The root directory component represents a separator that designates
68 //! starting from root. For example, `/a/b` has a root directory component
69 //! followed by normal components `a` and `b`.
71 //! On Windows, an additional component type comes into play:
73 //! * Prefix components, of which there is a large variety. For example, `C:`
74 //! and `\\server\share` are prefixes. The path `C:windows` has a prefix
75 //! component `C:` and a normal component `windows`; the path `C:\windows` has a
76 //! prefix component `C:`, a root directory component, and a normal component
81 //! Aside from splitting on the separator(s), there is a small amount of
84 //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
87 //! * Occurrences of `.` are normalized away, *except* if they are at
88 //! the beginning of the path (in which case they are often meaningful
89 //! in terms of path searching). So, for example, `a/./b`, `a/b/`,
90 //! `/a/b/.` and `a/b` all have components `a` and `b`, but `./a/b`
91 //! has a leading current directory component.
93 //! No other normalization takes place by default. In particular,
94 //! `a/c` and `a/b/../c` are distinct, to account for the possibility
95 //! that `b` is a symbolic link (so its parent isn't `a`). Further
96 //! normalization is possible to build on top of the components APIs,
97 //! and will be included in this library in the near future.
99 #![stable(feature = "rust1", since = "1.0.0")]
101 use core::prelude::*;
104 use borrow::{Borrow, IntoCow, ToOwned, Cow};
108 use ops::{self, Deref};
113 use ffi::{OsStr, OsString};
115 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
117 ////////////////////////////////////////////////////////////////////////////////
119 ////////////////////////////////////////////////////////////////////////////////
121 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
122 // taking advantage of the fact that OsStr always encodes ASCII characters
123 // as-is. Eventually, this transmutation should be replaced by direct uses of
124 // OsStr APIs for parsing, but it will take a while for those to become
127 ////////////////////////////////////////////////////////////////////////////////
128 // Platform-specific definitions
129 ////////////////////////////////////////////////////////////////////////////////
131 // The following modules give the most basic tools for parsing paths on various
132 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
137 use core::prelude::*;
141 pub fn is_sep_byte(b: u8) -> bool {
146 pub fn is_verbatim_sep(b: u8) -> bool {
150 pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
154 pub const MAIN_SEP_STR: &'static str = "/";
155 pub const MAIN_SEP: char = '/';
160 use core::prelude::*;
163 use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
167 pub fn is_sep_byte(b: u8) -> bool {
168 b == b'/' || b == b'\\'
172 pub fn is_verbatim_sep(b: u8) -> bool {
176 pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
177 use super::Prefix::*;
179 // The unsafety here stems from converting between &OsStr and &[u8]
180 // and back. This is safe to do because (1) we only look at ASCII
181 // contents of the encoding and (2) new &OsStr values are produced
182 // only from ASCII-bounded slices of existing &OsStr values.
183 let mut path = os_str_as_u8_slice(path);
185 if path.starts_with(br"\\") {
188 if path.starts_with(br"?\") {
191 if path.starts_with(br"UNC\") {
192 // \\?\UNC\server\share
194 let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
195 Some((server, share)) => (u8_slice_as_os_str(server),
196 u8_slice_as_os_str(share)),
197 None => (u8_slice_as_os_str(path),
198 u8_slice_as_os_str(&[])),
200 return Some(VerbatimUNC(server, share));
203 let idx = path.position_elem(&b'\\');
204 if idx == Some(2) && path[1] == b':' {
206 if c.is_ascii() && (c as char).is_alphabetic() {
208 return Some(VerbatimDisk(c.to_ascii_uppercase()));
211 let slice = &path[.. idx.unwrap_or(path.len())];
212 return Some(Verbatim(u8_slice_as_os_str(slice)));
214 } else if path.starts_with(b".\\") {
217 let slice = &path[.. path.position_elem(&b'\\').unwrap_or(path.len())];
218 return Some(DeviceNS(u8_slice_as_os_str(slice)));
220 match parse_two_comps(path, is_sep_byte) {
221 Some((server, share)) if !server.is_empty() && !share.is_empty() => {
223 return Some(UNC(u8_slice_as_os_str(server),
224 u8_slice_as_os_str(share)));
228 } else if path.len() > 1 && path[1] == b':' {
231 if c.is_ascii() && (c as char).is_alphabetic() {
232 return Some(Disk(c.to_ascii_uppercase()));
238 fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
239 let first = match path.iter().position(|x| f(*x)) {
241 Some(x) => &path[.. x]
243 path = &path[(first.len()+1)..];
244 let idx = path.iter().position(|x| f(*x));
245 let second = &path[.. idx.unwrap_or(path.len())];
246 Some((first, second))
250 pub const MAIN_SEP_STR: &'static str = "\\";
251 pub const MAIN_SEP: char = '\\';
254 ////////////////////////////////////////////////////////////////////////////////
256 ////////////////////////////////////////////////////////////////////////////////
258 /// Path prefixes (Windows only).
260 /// Windows uses a variety of path styles, including references to drive
261 /// volumes (like `C:`), network shared (like `\\server\share`) and
262 /// others. In addition, some path prefixes are "verbatim", in which case
263 /// `/` is *not* treated as a separator and essentially no normalization is
265 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub enum Prefix<'a> {
268 /// Prefix `\\?\`, together with the given component immediately following it.
269 #[stable(feature = "rust1", since = "1.0.0")]
272 /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
273 #[stable(feature = "rust1", since = "1.0.0")]
274 VerbatimUNC(&'a OsStr, &'a OsStr),
276 /// Prefix like `\\?\C:\`, for the given drive letter
277 #[stable(feature = "rust1", since = "1.0.0")]
280 /// Prefix `\\.\`, together with the given component immediately following it.
281 #[stable(feature = "rust1", since = "1.0.0")]
284 /// Prefix `\\server\share`, with the given "server" and "share" components.
285 #[stable(feature = "rust1", since = "1.0.0")]
286 UNC(&'a OsStr, &'a OsStr),
288 /// Prefix `C:` for the given disk drive.
289 #[stable(feature = "rust1", since = "1.0.0")]
293 impl<'a> Prefix<'a> {
295 fn len(&self) -> usize {
297 fn os_str_len(s: &OsStr) -> usize {
298 os_str_as_u8_slice(s).len()
301 Verbatim(x) => 4 + os_str_len(x),
302 VerbatimUNC(x,y) => 8 + os_str_len(x) +
303 if os_str_len(y) > 0 { 1 + os_str_len(y) }
305 VerbatimDisk(_) => 6,
306 UNC(x,y) => 2 + os_str_len(x) +
307 if os_str_len(y) > 0 { 1 + os_str_len(y) }
309 DeviceNS(x) => 4 + os_str_len(x),
315 /// Determines if the prefix is verbatim, i.e. begins `\\?\`.
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub fn is_verbatim(&self) -> bool {
321 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
327 fn is_drive(&self) -> bool {
329 Prefix::Disk(_) => true,
335 fn has_implicit_root(&self) -> bool {
340 ////////////////////////////////////////////////////////////////////////////////
341 // Exposed parsing helpers
342 ////////////////////////////////////////////////////////////////////////////////
344 /// Determines whether the character is one of the permitted path
345 /// separators for the current platform.
352 /// assert!(path::is_separator('/'));
353 /// assert!(!path::is_separator('❤'));
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn is_separator(c: char) -> bool {
358 c.is_ascii() && is_sep_byte(c as u8)
361 /// The primary sperator for the current platform
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
365 ////////////////////////////////////////////////////////////////////////////////
367 ////////////////////////////////////////////////////////////////////////////////
369 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
370 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
371 // `iter` after having exhausted `prefix`.
372 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where
373 I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq
376 let mut iter_next = iter.clone();
377 match (iter_next.next(), prefix.next()) {
378 (Some(x), Some(y)) => {
379 if x != y { return None }
381 (Some(_), None) => return Some(iter),
382 (None, None) => return Some(iter),
383 (None, Some(_)) => return None,
389 // See note at the top of this module to understand why these are used:
390 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
391 unsafe { mem::transmute(s) }
393 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
397 ////////////////////////////////////////////////////////////////////////////////
398 // Cross-platform, iterator-independent parsing
399 ////////////////////////////////////////////////////////////////////////////////
401 /// Says whether the first byte after the prefix is a separator.
402 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
403 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
404 !path.is_empty() && is_sep_byte(path[0])
407 // basic workhorse for splitting stem and extension
408 #[allow(unused_unsafe)] // FIXME
409 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
411 if os_str_as_u8_slice(file) == b".." { return (Some(file), None) }
413 // The unsafety here stems from converting between &OsStr and &[u8]
414 // and back. This is safe to do because (1) we only look at ASCII
415 // contents of the encoding and (2) new &OsStr values are produced
416 // only from ASCII-bounded slices of existing &OsStr values.
418 let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
419 let after = iter.next();
420 let before = iter.next();
421 if before == Some(b"") {
424 (before.map(|s| u8_slice_as_os_str(s)),
425 after.map(|s| u8_slice_as_os_str(s)))
430 ////////////////////////////////////////////////////////////////////////////////
431 // The core iterators
432 ////////////////////////////////////////////////////////////////////////////////
434 /// Component parsing works by a double-ended state machine; the cursors at the
435 /// front and back of the path each keep track of what parts of the path have
436 /// been consumed so far.
438 /// Going front to back, a path is made up of a prefix, a starting
439 /// directory component, and a body (of normal components)
440 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
443 StartDir = 1, // / or . or nothing
444 Body = 2, // foo/bar/baz
448 /// A Windows path prefix, e.g. `C:` or `\server\share`.
450 /// Does not occur on Unix.
451 #[stable(feature = "rust1", since = "1.0.0")]
452 #[derive(Copy, Clone, Eq, Hash, Debug)]
453 pub struct PrefixComponent<'a> {
454 /// The prefix as an unparsed `OsStr` slice.
457 /// The parsed prefix data.
461 impl<'a> PrefixComponent<'a> {
462 /// The parsed prefix data.
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn kind(&self) -> Prefix<'a> {
468 /// The raw `OsStr` slice for this prefix.
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn as_os_str(&self) -> &'a OsStr {
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
477 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
478 cmp::PartialEq::eq(&self.parsed, &other.parsed)
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
484 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
485 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
489 #[stable(feature = "rust1", since = "1.0.0")]
490 impl<'a> cmp::Ord for PrefixComponent<'a> {
491 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
492 cmp::Ord::cmp(&self.parsed, &other.parsed)
496 /// A single component of a path.
498 /// See the module documentation for an in-depth explanation of components and
499 /// their role in the API.
500 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub enum Component<'a> {
503 /// A Windows path prefix, e.g. `C:` or `\server\share`.
505 /// Does not occur on Unix.
506 #[stable(feature = "rust1", since = "1.0.0")]
507 Prefix(PrefixComponent<'a>),
509 /// The root directory component, appears after any prefix and before anything else
510 #[stable(feature = "rust1", since = "1.0.0")]
513 /// A reference to the current directory, i.e. `.`
514 #[stable(feature = "rust1", since = "1.0.0")]
517 /// A reference to the parent directory, i.e. `..`
518 #[stable(feature = "rust1", since = "1.0.0")]
521 /// A normal component, i.e. `a` and `b` in `a/b`
522 #[stable(feature = "rust1", since = "1.0.0")]
526 impl<'a> Component<'a> {
527 /// Extracts the underlying `OsStr` slice
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn as_os_str(self) -> &'a OsStr {
531 Component::Prefix(p) => p.as_os_str(),
532 Component::RootDir => OsStr::new(MAIN_SEP_STR),
533 Component::CurDir => OsStr::new("."),
534 Component::ParentDir => OsStr::new(".."),
535 Component::Normal(path) => path,
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl<'a> AsRef<OsStr> for Component<'a> {
542 fn as_ref(&self) -> &OsStr {
547 /// The core iterator giving the components of a path.
549 /// See the module documentation for an in-depth explanation of components and
550 /// their role in the API.
555 /// use std::path::Path;
557 /// let path = Path::new("/tmp/foo/bar.txt");
559 /// for component in path.components() {
560 /// println!("{:?}", component);
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub struct Components<'a> {
566 // The path left to parse components from
569 // The prefix as it was originally parsed, if any
570 prefix: Option<Prefix<'a>>,
572 // true if path *physically* has a root separator; for most Windows
573 // prefixes, it may have a "logical" rootseparator for the purposes of
574 // normalization, e.g. \\server\share == \\server\share\.
575 has_physical_root: bool,
577 // The iterator is double-ended, and these two states keep track of what has
578 // been produced from either end
583 /// An iterator over the components of a path, as `OsStr` slices.
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub struct Iter<'a> {
587 inner: Components<'a>
590 impl<'a> Components<'a> {
591 // how long is the prefix, if any?
593 fn prefix_len(&self) -> usize {
594 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
598 fn prefix_verbatim(&self) -> bool {
599 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
602 /// how much of the prefix is left from the point of view of iteration?
604 fn prefix_remaining(&self) -> usize {
605 if self.front == State::Prefix { self.prefix_len() }
609 // Given the iteration so far, how much of the pre-State::Body path is left?
611 fn len_before_body(&self) -> usize {
612 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
613 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
614 self.prefix_remaining() + root + cur_dir
617 // is the iteration complete?
619 fn finished(&self) -> bool {
620 self.front == State::Done || self.back == State::Done || self.front > self.back
624 fn is_sep_byte(&self, b: u8) -> bool {
625 if self.prefix_verbatim() {
632 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
637 /// use std::path::Path;
639 /// let path = Path::new("/tmp/foo/bar.txt");
641 /// println!("{:?}", path.components().as_path());
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn as_path(&self) -> &'a Path {
645 let mut comps = self.clone();
646 if comps.front == State::Body { comps.trim_left(); }
647 if comps.back == State::Body { comps.trim_right(); }
648 unsafe { Path::from_u8_slice(comps.path) }
651 /// Is the *original* path rooted?
652 fn has_root(&self) -> bool {
653 if self.has_physical_root { return true }
654 if let Some(p) = self.prefix {
655 if p.has_implicit_root() { return true }
660 /// Should the normalized path include a leading . ?
661 fn include_cur_dir(&self) -> bool {
662 if self.has_root() { return false }
663 let mut iter = self.path[self.prefix_len()..].iter();
664 match (iter.next(), iter.next()) {
665 (Some(&b'.'), None) => true,
666 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
671 // parse a given byte sequence into the corresponding path component
672 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
674 b"." if self.prefix_verbatim() => Some(Component::CurDir),
675 b"." => None, // . components are normalized away, except at
676 // the beginning of a path, which is treated
677 // separately via `include_cur_dir`
678 b".." => Some(Component::ParentDir),
680 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) }))
684 // parse a component from the left, saying how many bytes to consume to
685 // remove the component
686 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
687 debug_assert!(self.front == State::Body);
688 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
689 None => (0, self.path),
690 Some(i) => (1, &self.path[.. i]),
692 (comp.len() + extra, self.parse_single_component(comp))
695 // parse a component from the right, saying how many bytes to consume to
696 // remove the component
697 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
698 debug_assert!(self.back == State::Body);
699 let start = self.len_before_body();
700 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
701 None => (0, &self.path[start ..]),
702 Some(i) => (1, &self.path[start + i + 1 ..]),
704 (comp.len() + extra, self.parse_single_component(comp))
707 // trim away repeated separators (i.e. empty components) on the left
708 fn trim_left(&mut self) {
709 while !self.path.is_empty() {
710 let (size, comp) = self.parse_next_component();
714 self.path = &self.path[size ..];
719 // trim away repeated separators (i.e. empty components) on the right
720 fn trim_right(&mut self) {
721 while self.path.len() > self.len_before_body() {
722 let (size, comp) = self.parse_next_component_back();
726 self.path = &self.path[.. self.path.len() - size];
731 /// Examine the next component without consuming it.
732 #[unstable(feature = "path_components_peek")]
733 pub fn peek(&self) -> Option<Component<'a>> {
738 #[stable(feature = "rust1", since = "1.0.0")]
739 impl<'a> AsRef<Path> for Components<'a> {
740 fn as_ref(&self) -> &Path {
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl<'a> AsRef<OsStr> for Components<'a> {
747 fn as_ref(&self) -> &OsStr {
748 self.as_path().as_os_str()
753 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
754 #[stable(feature = "rust1", since = "1.0.0")]
755 pub fn as_path(&self) -> &'a Path {
760 #[stable(feature = "rust1", since = "1.0.0")]
761 impl<'a> AsRef<Path> for Iter<'a> {
762 fn as_ref(&self) -> &Path {
767 #[stable(feature = "rust1", since = "1.0.0")]
768 impl<'a> AsRef<OsStr> for Iter<'a> {
769 fn as_ref(&self) -> &OsStr {
770 self.as_path().as_os_str()
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl<'a> Iterator for Iter<'a> {
776 type Item = &'a OsStr;
778 fn next(&mut self) -> Option<&'a OsStr> {
779 self.inner.next().map(Component::as_os_str)
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl<'a> DoubleEndedIterator for Iter<'a> {
785 fn next_back(&mut self) -> Option<&'a OsStr> {
786 self.inner.next_back().map(Component::as_os_str)
790 #[stable(feature = "rust1", since = "1.0.0")]
791 impl<'a> Iterator for Components<'a> {
792 type Item = Component<'a>;
794 fn next(&mut self) -> Option<Component<'a>> {
795 while !self.finished() {
797 State::Prefix if self.prefix_len() > 0 => {
798 self.front = State::StartDir;
799 debug_assert!(self.prefix_len() <= self.path.len());
800 let raw = &self.path[.. self.prefix_len()];
801 self.path = &self.path[self.prefix_len() .. ];
802 return Some(Component::Prefix(PrefixComponent {
803 raw: unsafe { u8_slice_as_os_str(raw) },
804 parsed: self.prefix.unwrap()
808 self.front = State::StartDir;
811 self.front = State::Body;
812 if self.has_physical_root {
813 debug_assert!(!self.path.is_empty());
814 self.path = &self.path[1..];
815 return Some(Component::RootDir)
816 } else if let Some(p) = self.prefix {
817 if p.has_implicit_root() && !p.is_verbatim() {
818 return Some(Component::RootDir)
820 } else if self.include_cur_dir() {
821 debug_assert!(!self.path.is_empty());
822 self.path = &self.path[1..];
823 return Some(Component::CurDir)
826 State::Body if !self.path.is_empty() => {
827 let (size, comp) = self.parse_next_component();
828 self.path = &self.path[size ..];
829 if comp.is_some() { return comp }
832 self.front = State::Done;
834 State::Done => unreachable!()
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<'a> DoubleEndedIterator for Components<'a> {
843 fn next_back(&mut self) -> Option<Component<'a>> {
844 while !self.finished() {
846 State::Body if self.path.len() > self.len_before_body() => {
847 let (size, comp) = self.parse_next_component_back();
848 self.path = &self.path[.. self.path.len() - size];
849 if comp.is_some() { return comp }
852 self.back = State::StartDir;
855 self.back = State::Prefix;
856 if self.has_physical_root {
857 self.path = &self.path[.. self.path.len() - 1];
858 return Some(Component::RootDir)
859 } else if let Some(p) = self.prefix {
860 if p.has_implicit_root() && !p.is_verbatim() {
861 return Some(Component::RootDir)
863 } else if self.include_cur_dir() {
864 self.path = &self.path[.. self.path.len() - 1];
865 return Some(Component::CurDir)
868 State::Prefix if self.prefix_len() > 0 => {
869 self.back = State::Done;
870 return Some(Component::Prefix(PrefixComponent {
871 raw: unsafe { u8_slice_as_os_str(self.path) },
872 parsed: self.prefix.unwrap()
876 self.back = State::Done;
879 State::Done => unreachable!()
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<'a> cmp::PartialEq for Components<'a> {
888 fn eq(&self, other: &Components<'a>) -> bool {
889 iter::order::eq(self.clone(), other.clone())
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<'a> cmp::Eq for Components<'a> {}
896 #[stable(feature = "rust1", since = "1.0.0")]
897 impl<'a> cmp::PartialOrd for Components<'a> {
898 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
899 iter::order::partial_cmp(self.clone(), other.clone())
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl<'a> cmp::Ord for Components<'a> {
905 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
906 iter::order::cmp(self.clone(), other.clone())
910 ////////////////////////////////////////////////////////////////////////////////
911 // Basic types and traits
912 ////////////////////////////////////////////////////////////////////////////////
914 /// An owned, mutable path (akin to `String`).
916 /// This type provides methods like `push` and `set_extension` that mutate the
917 /// path in place. It also implements `Deref` to `Path`, meaning that all
918 /// methods on `Path` slices are available on `PathBuf` values as well.
920 /// More details about the overall approach can be found in
921 /// the module documentation.
926 /// use std::path::PathBuf;
928 /// let mut path = PathBuf::from("c:\\");
929 /// path.push("windows");
930 /// path.push("system32");
931 /// path.set_extension("dll");
933 #[derive(Clone, Hash)]
934 #[stable(feature = "rust1", since = "1.0.0")]
940 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
941 unsafe { mem::transmute(self) }
944 /// Allocates an empty `PathBuf`.
945 #[stable(feature = "rust1", since = "1.0.0")]
946 pub fn new() -> PathBuf {
947 PathBuf { inner: OsString::new() }
950 /// Coerces to a `Path` slice.
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn as_path(&self) -> &Path {
956 /// Extends `self` with `path`.
958 /// If `path` is absolute, it replaces the current path.
962 /// * if `path` has a root but no prefix (e.g. `\windows`), it
963 /// replaces everything except for the prefix (if any) of `self`.
964 /// * if `path` has a prefix but no root, it replaces `self.
965 #[stable(feature = "rust1", since = "1.0.0")]
966 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
967 let path = path.as_ref();
969 // in general, a separator is needed if the rightmost byte is not a separator
970 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
972 // in the special case of `C:` on Windows, do *not* add a separator
974 let comps = self.components();
975 if comps.prefix_len() > 0 &&
976 comps.prefix_len() == comps.path.len() &&
977 comps.prefix.unwrap().is_drive()
983 // absolute `path` replaces `self`
984 if path.is_absolute() || path.prefix().is_some() {
985 self.as_mut_vec().truncate(0);
987 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
988 } else if path.has_root() {
989 let prefix_len = self.components().prefix_remaining();
990 self.as_mut_vec().truncate(prefix_len);
992 // `path` is a pure relative path
994 self.inner.push(MAIN_SEP_STR);
997 self.inner.push(path);
1000 /// Truncate `self` to `self.parent()`.
1002 /// Returns false and does nothing if `self.file_name()` is `None`.
1003 /// Otherwise, returns `true`.
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 pub fn pop(&mut self) -> bool {
1006 match self.parent().map(|p| p.as_u8_slice().len()) {
1008 self.as_mut_vec().truncate(len);
1015 /// Updates `self.file_name()` to `file_name`.
1017 /// If `self.file_name()` was `None`, this is equivalent to pushing
1023 /// use std::path::PathBuf;
1025 /// let mut buf = PathBuf::from("/");
1026 /// assert!(buf.file_name() == None);
1027 /// buf.set_file_name("bar");
1028 /// assert!(buf == PathBuf::from("/bar"));
1029 /// assert!(buf.file_name().is_some());
1030 /// buf.set_file_name("baz.txt");
1031 /// assert!(buf == PathBuf::from("/baz.txt"));
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1035 if self.file_name().is_some() {
1036 let popped = self.pop();
1037 debug_assert!(popped);
1039 self.push(file_name.as_ref());
1042 /// Updates `self.extension()` to `extension`.
1044 /// If `self.file_name()` is `None`, does nothing and returns `false`.
1046 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
1047 /// is added; otherwise it is replaced.
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1050 if self.file_name().is_none() { return false; }
1052 let mut stem = match self.file_stem() {
1053 Some(stem) => stem.to_os_string(),
1054 None => OsString::new(),
1057 let extension = extension.as_ref();
1058 if !os_str_as_u8_slice(extension).is_empty() {
1060 stem.push(extension);
1062 self.set_file_name(&stem);
1067 /// Consumes the `PathBuf`, yielding its internal `OsString` storage.
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 pub fn into_os_string(self) -> OsString {
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf {
1076 fn from(s: &'a T) -> PathBuf {
1077 PathBuf::from(s.as_ref().to_os_string())
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl From<OsString> for PathBuf {
1083 fn from(s: OsString) -> PathBuf {
1084 PathBuf { inner: s }
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl From<String> for PathBuf {
1090 fn from(s: String) -> PathBuf {
1091 PathBuf::from(OsString::from(s))
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
1097 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1098 let mut buf = PathBuf::new();
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
1106 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl fmt::Debug for PathBuf {
1115 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1116 fmt::Debug::fmt(&**self, formatter)
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 impl ops::Deref for PathBuf {
1124 fn deref(&self) -> &Path {
1125 unsafe { mem::transmute(&self.inner[..]) }
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl Borrow<Path> for PathBuf {
1131 fn borrow(&self) -> &Path {
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl IntoCow<'static, Path> for PathBuf {
1138 fn into_cow(self) -> Cow<'static, Path> {
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl<'a> IntoCow<'a, Path> for &'a Path {
1145 fn into_cow(self) -> Cow<'a, Path> {
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 impl ToOwned for Path {
1152 type Owned = PathBuf;
1153 fn to_owned(&self) -> PathBuf { self.to_path_buf() }
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 impl cmp::PartialEq for PathBuf {
1158 fn eq(&self, other: &PathBuf) -> bool {
1159 self.components() == other.components()
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 impl cmp::Eq for PathBuf {}
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl cmp::PartialOrd for PathBuf {
1168 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1169 self.components().partial_cmp(&other.components())
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 impl cmp::Ord for PathBuf {
1175 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1176 self.components().cmp(&other.components())
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl AsRef<OsStr> for PathBuf {
1182 fn as_ref(&self) -> &OsStr {
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 impl Into<OsString> for PathBuf {
1189 fn into(self) -> OsString {
1194 /// A slice of a path (akin to `str`).
1196 /// This type supports a number of operations for inspecting a path, including
1197 /// breaking the path into its components (separated by `/` or `\`, depending on
1198 /// the platform), extracting the file name, determining whether the path is
1199 /// absolute, and so on. More details about the overall approach can be found in
1200 /// the module documentation.
1202 /// This is an *unsized* type, meaning that it must always be used with behind a
1203 /// pointer like `&` or `Box`.
1208 /// use std::path::Path;
1210 /// let path = Path::new("/tmp/foo/bar.txt");
1211 /// let file = path.file_name();
1212 /// let extension = path.extension();
1213 /// let parent_dir = path.parent();
1217 #[stable(feature = "rust1", since = "1.0.0")]
1223 // The following (private!) function allows construction of a path from a u8
1224 // slice, which is only safe when it is known to follow the OsStr encoding.
1225 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1228 // The following (private!) function reveals the byte encoding used for OsStr.
1229 fn as_u8_slice(&self) -> &[u8] {
1230 unsafe { mem::transmute(self) }
1233 /// Directly wrap a string slice as a `Path` slice.
1235 /// This is a cost-free conversion.
1240 /// use std::path::Path;
1242 /// Path::new("foo.txt");
1245 /// You can create `Path`s from `String`s, or even other `Path`s:
1248 /// use std::path::Path;
1250 /// let s = String::from("bar.txt");
1251 /// let p = Path::new(&s);
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
1256 unsafe { mem::transmute(s.as_ref()) }
1259 /// Yields the underlying `OsStr` slice.
1264 /// use std::path::Path;
1266 /// let os_str = Path::new("foo.txt").as_os_str();
1268 #[stable(feature = "rust1", since = "1.0.0")]
1269 pub fn as_os_str(&self) -> &OsStr {
1273 /// Yields a `&str` slice if the `Path` is valid unicode.
1275 /// This conversion may entail doing a check for UTF-8 validity.
1280 /// use std::path::Path;
1282 /// let path_str = Path::new("foo.txt").to_str();
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 pub fn to_str(&self) -> Option<&str> {
1289 /// Converts a `Path` to a `Cow<str>`.
1291 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1296 /// use std::path::Path;
1298 /// let path_str = Path::new("foo.txt").to_string_lossy();
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 pub fn to_string_lossy(&self) -> Cow<str> {
1302 self.inner.to_string_lossy()
1305 /// Converts a `Path` to an owned `PathBuf`.
1310 /// use std::path::Path;
1312 /// let path_str = Path::new("foo.txt").to_path_buf();
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 pub fn to_path_buf(&self) -> PathBuf {
1316 PathBuf::from(self.inner.to_os_string())
1319 /// A path is *absolute* if it is independent of the current directory.
1321 /// * On Unix, a path is absolute if it starts with the root, so
1322 /// `is_absolute` and `has_root` are equivalent.
1324 /// * On Windows, a path is absolute if it has a prefix and starts with the
1325 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1326 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1331 /// use std::path::Path;
1333 /// assert_eq!(false, Path::new("foo.txt").is_absolute());
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub fn is_absolute(&self) -> bool {
1338 (cfg!(unix) || self.prefix().is_some())
1341 /// A path is *relative* if it is not absolute.
1346 /// use std::path::Path;
1348 /// assert!(Path::new("foo.txt").is_relative());
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 pub fn is_relative(&self) -> bool {
1355 /// Returns the *prefix* of a path, if any.
1357 /// Prefixes are relevant only for Windows paths, and consist of volumes
1358 /// like `C:`, UNC prefixes like `\\server`, and others described in more
1359 /// detail in `std::os::windows::PathExt`.
1360 #[unstable(feature = "path_prefix", reason = "uncertain whether to expose this convenience")]
1361 pub fn prefix(&self) -> Option<Prefix> {
1362 self.components().prefix
1365 /// A path has a root if the body of the path begins with the directory separator.
1367 /// * On Unix, a path has a root if it begins with `/`.
1369 /// * On Windows, a path has a root if it:
1370 /// * has no prefix and begins with a separator, e.g. `\\windows`
1371 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1372 /// * has any non-disk prefix, e.g. `\\server\share`
1377 /// use std::path::Path;
1379 /// assert!(Path::new("/etc/passwd").has_root());
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub fn has_root(&self) -> bool {
1383 self.components().has_root()
1386 /// The path without its final component, if any.
1388 /// Returns `None` if the path terminates in a root or prefix.
1393 /// use std::path::Path;
1395 /// let path = Path::new("/foo/bar");
1396 /// let foo = path.parent().unwrap();
1398 /// assert!(foo == Path::new("/foo"));
1400 /// let root = foo.parent().unwrap();
1402 /// assert!(root == Path::new("/"));
1403 /// assert!(root.parent() == None);
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 pub fn parent(&self) -> Option<&Path> {
1407 let mut comps = self.components();
1408 let comp = comps.next_back();
1409 comp.and_then(|p| match p {
1410 Component::Normal(_) |
1412 Component::ParentDir => Some(comps.as_path()),
1417 /// The final component of the path, if it is a normal file.
1419 /// If the path terminates in `.`, `..`, or consists solely or a root of
1420 /// prefix, `file_name` will return `None`.
1425 /// use std::path::Path;
1427 /// let path = Path::new("hello_world.rs");
1428 /// let filename = "hello_world.rs";
1430 /// assert_eq!(filename, path.file_name().unwrap());
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 pub fn file_name(&self) -> Option<&OsStr> {
1434 self.components().next_back().and_then(|p| match p {
1435 Component::Normal(p) => Some(p.as_ref()),
1440 /// Returns a path that, when joined onto `base`, yields `self`.
1442 /// If `base` is not a prefix of `self` (i.e. `starts_with`
1443 /// returns false), then `relative_from` returns `None`.
1444 #[unstable(feature = "path_relative_from", reason = "see #23284")]
1445 pub fn relative_from<'a, P: ?Sized + AsRef<Path>>(&'a self, base: &'a P) -> Option<&Path>
1447 iter_after(self.components(), base.as_ref().components()).map(|c| c.as_path())
1450 /// Determines whether `base` is a prefix of `self`.
1455 /// use std::path::Path;
1457 /// let path = Path::new("/etc/passwd");
1459 /// assert!(path.starts_with("/etc"));
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
1463 iter_after(self.components(), base.as_ref().components()).is_some()
1466 /// Determines whether `child` is a suffix of `self`.
1471 /// use std::path::Path;
1473 /// let path = Path::new("/etc/passwd");
1475 /// assert!(path.ends_with("passwd"));
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
1479 iter_after(self.components().rev(), child.as_ref().components().rev()).is_some()
1482 /// Extracts the stem (non-extension) portion of `self.file()`.
1486 /// * None, if there is no file name;
1487 /// * The entire file name if there is no embedded `.`;
1488 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1489 /// * Otherwise, the portion of the file name before the final `.`
1494 /// use std::path::Path;
1496 /// let path = Path::new("foo.rs");
1498 /// assert_eq!("foo", path.file_stem().unwrap());
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 pub fn file_stem(&self) -> Option<&OsStr> {
1502 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1505 /// Extracts the extension of `self.file()`, if possible.
1507 /// The extension is:
1509 /// * None, if there is no file name;
1510 /// * None, if there is no embedded `.`;
1511 /// * None, if the file name begins with `.` and has no other `.`s within;
1512 /// * Otherwise, the portion of the file name after the final `.`
1517 /// use std::path::Path;
1519 /// let path = Path::new("foo.rs");
1521 /// assert_eq!("rs", path.extension().unwrap());
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 pub fn extension(&self) -> Option<&OsStr> {
1525 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1528 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1530 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1535 /// use std::path::Path;
1537 /// let path = Path::new("/tmp");
1539 /// let new_path = path.join("foo");
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
1543 let mut buf = self.to_path_buf();
1548 /// Creates an owned `PathBuf` like `self` but with the given file name.
1550 /// See `PathBuf::set_file_name` for more details.
1555 /// use std::path::Path;
1557 /// let path = Path::new("/tmp/foo.rs");
1559 /// let new_path = path.with_file_name("bar.rs");
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
1563 let mut buf = self.to_path_buf();
1564 buf.set_file_name(file_name);
1568 /// Creates an owned `PathBuf` like `self` but with the given extension.
1570 /// See `PathBuf::set_extension` for more details.
1575 /// use std::path::{Path, PathBuf};
1577 /// let path = Path::new("/tmp/foo.rs");
1579 /// let new_path = path.with_extension("txt");
1580 /// assert_eq!(new_path, PathBuf::from("/tmp/foo.txt"));
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
1584 let mut buf = self.to_path_buf();
1585 buf.set_extension(extension);
1589 /// Produce an iterator over the components of the path.
1594 /// use std::path::Path;
1596 /// let path = Path::new("/tmp/foo.rs");
1598 /// for component in path.components() {
1599 /// println!("{:?}", component);
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 pub fn components(&self) -> Components {
1604 let prefix = parse_prefix(self.as_os_str());
1606 path: self.as_u8_slice(),
1608 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1609 front: State::Prefix,
1614 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1619 /// use std::path::Path;
1621 /// let path = Path::new("/tmp/foo.rs");
1623 /// for component in path.iter() {
1624 /// println!("{:?}", component);
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 pub fn iter(&self) -> Iter {
1629 Iter { inner: self.components() }
1632 /// Returns an object that implements `Display` for safely printing paths
1633 /// that may contain non-Unicode data.
1638 /// use std::path::Path;
1640 /// let path = Path::new("/tmp/foo.rs");
1642 /// println!("{}", path.display());
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn display(&self) -> Display {
1646 Display { path: self }
1650 #[stable(feature = "rust1", since = "1.0.0")]
1651 impl AsRef<OsStr> for Path {
1652 fn as_ref(&self) -> &OsStr {
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 impl fmt::Debug for Path {
1659 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1660 self.inner.fmt(formatter)
1664 /// Helper struct for safely printing paths with `format!()` and `{}`
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 pub struct Display<'a> {
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<'a> fmt::Debug for Display<'a> {
1672 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1673 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl<'a> fmt::Display for Display<'a> {
1679 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1680 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1684 #[stable(feature = "rust1", since = "1.0.0")]
1685 impl cmp::PartialEq for Path {
1686 fn eq(&self, other: &Path) -> bool {
1687 iter::order::eq(self.components(), other.components())
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl cmp::Eq for Path {}
1694 #[stable(feature = "rust1", since = "1.0.0")]
1695 impl cmp::PartialOrd for Path {
1696 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1697 self.components().partial_cmp(&other.components())
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 impl cmp::Ord for Path {
1703 fn cmp(&self, other: &Path) -> cmp::Ordering {
1704 self.components().cmp(&other.components())
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl AsRef<Path> for Path {
1710 fn as_ref(&self) -> &Path { self }
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 impl AsRef<Path> for OsStr {
1715 fn as_ref(&self) -> &Path { Path::new(self) }
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl AsRef<Path> for OsString {
1720 fn as_ref(&self) -> &Path { Path::new(self) }
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 impl AsRef<Path> for str {
1725 fn as_ref(&self) -> &Path { Path::new(self) }
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl AsRef<Path> for String {
1730 fn as_ref(&self) -> &Path { Path::new(self) }
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl AsRef<Path> for PathBuf {
1735 fn as_ref(&self) -> &Path { self }
1741 use core::prelude::*;
1742 use string::{ToString, String};
1746 ($path:expr, iter: $iter:expr) => (
1748 let path = Path::new($path);
1750 // Forward iteration
1751 let comps = path.iter()
1752 .map(|p| p.to_string_lossy().into_owned())
1753 .collect::<Vec<String>>();
1754 let exp: &[&str] = &$iter;
1755 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
1756 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
1759 // Reverse iteration
1760 let comps = Path::new($path).iter().rev()
1761 .map(|p| p.to_string_lossy().into_owned())
1762 .collect::<Vec<String>>();
1763 let exps = exps.into_iter().rev().collect::<Vec<String>>();
1764 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
1769 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
1771 let path = Path::new($path);
1773 let act_root = path.has_root();
1774 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
1775 $has_root, act_root);
1777 let act_abs = path.is_absolute();
1778 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
1779 $is_absolute, act_abs);
1783 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
1785 let path = Path::new($path);
1787 let parent = path.parent().map(|p| p.to_str().unwrap());
1788 let exp_parent: Option<&str> = $parent;
1789 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
1790 exp_parent, parent);
1792 let file = path.file_name().map(|p| p.to_str().unwrap());
1793 let exp_file: Option<&str> = $file;
1794 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
1799 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
1801 let path = Path::new($path);
1803 let stem = path.file_stem().map(|p| p.to_str().unwrap());
1804 let exp_stem: Option<&str> = $file_stem;
1805 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
1808 let ext = path.extension().map(|p| p.to_str().unwrap());
1809 let exp_ext: Option<&str> = $extension;
1810 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
1815 ($path:expr, iter: $iter:expr,
1816 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
1817 parent: $parent:expr, file_name: $file:expr,
1818 file_stem: $file_stem:expr, extension: $extension:expr) => (
1820 t!($path, iter: $iter);
1821 t!($path, has_root: $has_root, is_absolute: $is_absolute);
1822 t!($path, parent: $parent, file_name: $file);
1823 t!($path, file_stem: $file_stem, extension: $extension);
1830 use borrow::{Cow, IntoCow};
1832 let static_path = Path::new("/home/foo");
1833 let static_cow_path: Cow<'static, Path> = static_path.into_cow();
1834 let pathbuf = PathBuf::from("/home/foo");
1837 let path: &Path = &pathbuf;
1838 let borrowed_cow_path: Cow<Path> = path.into_cow();
1840 assert_eq!(static_cow_path, borrowed_cow_path);
1843 let owned_cow_path: Cow<'static, Path> = pathbuf.into_cow();
1845 assert_eq!(static_cow_path, owned_cow_path);
1850 pub fn test_decompositions_unix() {
1866 file_name: Some("foo"),
1867 file_stem: Some("foo"),
1886 file_name: Some("foo"),
1887 file_stem: Some("foo"),
1896 file_name: Some("foo"),
1897 file_stem: Some("foo"),
1906 file_name: Some("foo"),
1907 file_stem: Some("foo"),
1912 iter: ["foo", "bar"],
1915 parent: Some("foo"),
1916 file_name: Some("bar"),
1917 file_stem: Some("bar"),
1922 iter: ["/", "foo", "bar"],
1925 parent: Some("/foo"),
1926 file_name: Some("bar"),
1927 file_stem: Some("bar"),
1936 file_name: Some("foo"),
1937 file_stem: Some("foo"),
1942 iter: ["/", "foo", "bar"],
1945 parent: Some("///foo"),
1946 file_name: Some("bar"),
1947 file_stem: Some("bar"),
1986 file_name: Some("foo"),
1987 file_stem: Some("foo"),
1992 iter: ["foo", ".."],
1995 parent: Some("foo"),
2006 file_name: Some("foo"),
2007 file_stem: Some("foo"),
2012 iter: ["foo", "bar"],
2015 parent: Some("foo"),
2016 file_name: Some("bar"),
2017 file_stem: Some("bar"),
2022 iter: ["foo", ".."],
2025 parent: Some("foo"),
2032 iter: ["foo", "..", "bar"],
2035 parent: Some("foo/.."),
2036 file_name: Some("bar"),
2037 file_stem: Some("bar"),
2046 file_name: Some("a"),
2047 file_stem: Some("a"),
2076 file_name: Some("b"),
2077 file_stem: Some("b"),
2086 file_name: Some("b"),
2087 file_stem: Some("b"),
2096 file_name: Some("b"),
2097 file_stem: Some("b"),
2102 iter: ["a", "b", "c"],
2105 parent: Some("a/b"),
2106 file_name: Some("c"),
2107 file_stem: Some("c"),
2116 file_name: Some(".foo"),
2117 file_stem: Some(".foo"),
2124 pub fn test_decompositions_windows() {
2140 file_name: Some("foo"),
2141 file_stem: Some("foo"),
2196 iter: ["\\", "foo"],
2200 file_name: Some("foo"),
2201 file_stem: Some("foo"),
2210 file_name: Some("foo"),
2211 file_stem: Some("foo"),
2216 iter: ["\\", "foo"],
2220 file_name: Some("foo"),
2221 file_stem: Some("foo"),
2226 iter: ["foo", "bar"],
2229 parent: Some("foo"),
2230 file_name: Some("bar"),
2231 file_stem: Some("bar"),
2236 iter: ["\\", "foo", "bar"],
2239 parent: Some("/foo"),
2240 file_name: Some("bar"),
2241 file_stem: Some("bar"),
2246 iter: ["\\", "foo"],
2250 file_name: Some("foo"),
2251 file_stem: Some("foo"),
2256 iter: ["\\", "foo", "bar"],
2259 parent: Some("///foo"),
2260 file_name: Some("bar"),
2261 file_stem: Some("bar"),
2300 file_name: Some("foo"),
2301 file_stem: Some("foo"),
2306 iter: ["foo", ".."],
2309 parent: Some("foo"),
2320 file_name: Some("foo"),
2321 file_stem: Some("foo"),
2326 iter: ["foo", "bar"],
2329 parent: Some("foo"),
2330 file_name: Some("bar"),
2331 file_stem: Some("bar"),
2336 iter: ["foo", ".."],
2339 parent: Some("foo"),
2346 iter: ["foo", "..", "bar"],
2349 parent: Some("foo/.."),
2350 file_name: Some("bar"),
2351 file_stem: Some("bar"),
2360 file_name: Some("a"),
2361 file_stem: Some("a"),
2390 file_name: Some("b"),
2391 file_stem: Some("b"),
2400 file_name: Some("b"),
2401 file_stem: Some("b"),
2410 file_name: Some("b"),
2411 file_stem: Some("b"),
2416 iter: ["a", "b", "c"],
2419 parent: Some("a/b"),
2420 file_name: Some("c"),
2421 file_stem: Some("c"),
2425 iter: ["a", "b", "c"],
2428 parent: Some("a\\b"),
2429 file_name: Some("c"),
2430 file_stem: Some("c"),
2439 file_name: Some("a"),
2440 file_stem: Some("a"),
2445 iter: ["c:", "\\", "foo.txt"],
2448 parent: Some("c:\\"),
2449 file_name: Some("foo.txt"),
2450 file_stem: Some("foo"),
2451 extension: Some("txt")
2454 t!("\\\\server\\share\\foo.txt",
2455 iter: ["\\\\server\\share", "\\", "foo.txt"],
2458 parent: Some("\\\\server\\share\\"),
2459 file_name: Some("foo.txt"),
2460 file_stem: Some("foo"),
2461 extension: Some("txt")
2464 t!("\\\\server\\share",
2465 iter: ["\\\\server\\share", "\\"],
2475 iter: ["\\", "server"],
2479 file_name: Some("server"),
2480 file_stem: Some("server"),
2484 t!("\\\\?\\bar\\foo.txt",
2485 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2488 parent: Some("\\\\?\\bar\\"),
2489 file_name: Some("foo.txt"),
2490 file_stem: Some("foo"),
2491 extension: Some("txt")
2495 iter: ["\\\\?\\bar"],
2514 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2515 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2518 parent: Some("\\\\?\\UNC\\server\\share\\"),
2519 file_name: Some("foo.txt"),
2520 file_stem: Some("foo"),
2521 extension: Some("txt")
2524 t!("\\\\?\\UNC\\server",
2525 iter: ["\\\\?\\UNC\\server"],
2535 iter: ["\\\\?\\UNC\\"],
2544 t!("\\\\?\\C:\\foo.txt",
2545 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2548 parent: Some("\\\\?\\C:\\"),
2549 file_name: Some("foo.txt"),
2550 file_stem: Some("foo"),
2551 extension: Some("txt")
2556 iter: ["\\\\?\\C:", "\\"],
2567 iter: ["\\\\?\\C:"],
2577 t!("\\\\?\\foo/bar",
2578 iter: ["\\\\?\\foo/bar"],
2589 iter: ["\\\\?\\C:/foo"],
2599 t!("\\\\.\\foo\\bar",
2600 iter: ["\\\\.\\foo", "\\", "bar"],
2603 parent: Some("\\\\.\\foo\\"),
2604 file_name: Some("bar"),
2605 file_stem: Some("bar"),
2611 iter: ["\\\\.\\foo", "\\"],
2621 t!("\\\\.\\foo/bar",
2622 iter: ["\\\\.\\foo/bar", "\\"],
2632 t!("\\\\.\\foo\\bar/baz",
2633 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
2636 parent: Some("\\\\.\\foo\\bar"),
2637 file_name: Some("baz"),
2638 file_stem: Some("baz"),
2644 iter: ["\\\\.\\", "\\"],
2654 iter: ["\\\\?\\a", "\\", "b"],
2657 parent: Some("\\\\?\\a\\"),
2658 file_name: Some("b"),
2659 file_stem: Some("b"),
2665 pub fn test_stem_ext() {
2667 file_stem: Some("foo"),
2672 file_stem: Some("foo"),
2677 file_stem: Some(".foo"),
2682 file_stem: Some("foo"),
2683 extension: Some("txt")
2687 file_stem: Some("foo.bar"),
2688 extension: Some("txt")
2692 file_stem: Some("foo.bar"),
2713 pub fn test_push() {
2715 ($path:expr, $push:expr, $expected:expr) => ( {
2716 let mut actual = PathBuf::from($path);
2718 assert!(actual.to_str() == Some($expected),
2719 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
2720 $push, $path, $expected, actual.to_str().unwrap());
2725 tp!("", "foo", "foo");
2726 tp!("foo", "bar", "foo/bar");
2727 tp!("foo/", "bar", "foo/bar");
2728 tp!("foo//", "bar", "foo//bar");
2729 tp!("foo/.", "bar", "foo/./bar");
2730 tp!("foo./.", "bar", "foo././bar");
2731 tp!("foo", "", "foo/");
2732 tp!("foo", ".", "foo/.");
2733 tp!("foo", "..", "foo/..");
2734 tp!("foo", "/", "/");
2735 tp!("/foo/bar", "/", "/");
2736 tp!("/foo/bar", "/baz", "/baz");
2737 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
2739 tp!("", "foo", "foo");
2740 tp!("foo", "bar", r"foo\bar");
2741 tp!("foo/", "bar", r"foo/bar");
2742 tp!(r"foo\", "bar", r"foo\bar");
2743 tp!("foo//", "bar", r"foo//bar");
2744 tp!(r"foo\\", "bar", r"foo\\bar");
2745 tp!("foo/.", "bar", r"foo/.\bar");
2746 tp!("foo./.", "bar", r"foo./.\bar");
2747 tp!(r"foo\.", "bar", r"foo\.\bar");
2748 tp!(r"foo.\.", "bar", r"foo.\.\bar");
2749 tp!("foo", "", "foo\\");
2750 tp!("foo", ".", r"foo\.");
2751 tp!("foo", "..", r"foo\..");
2752 tp!("foo", "/", "/");
2753 tp!("foo", r"\", r"\");
2754 tp!("/foo/bar", "/", "/");
2755 tp!(r"\foo\bar", r"\", r"\");
2756 tp!("/foo/bar", "/baz", "/baz");
2757 tp!("/foo/bar", r"\baz", r"\baz");
2758 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
2759 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
2761 tp!("c:\\", "windows", "c:\\windows");
2762 tp!("c:", "windows", "c:windows");
2764 tp!("a\\b\\c", "d", "a\\b\\c\\d");
2765 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
2766 tp!("a\\b", "c\\d", "a\\b\\c\\d");
2767 tp!("a\\b", "\\c\\d", "\\c\\d");
2768 tp!("a\\b", ".", "a\\b\\.");
2769 tp!("a\\b", "..\\c", "a\\b\\..\\c");
2770 tp!("a\\b", "C:a.txt", "C:a.txt");
2771 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
2772 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
2773 tp!("C:\\a\\b\\c", "C:d", "C:d");
2774 tp!("C:a\\b\\c", "C:d", "C:d");
2775 tp!("C:", r"a\b\c", r"C:a\b\c");
2776 tp!("C:", r"..\a", r"C:..\a");
2777 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
2778 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
2779 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
2780 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
2781 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
2782 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
2783 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
2784 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
2785 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
2787 // Note: modified from old path API
2788 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
2790 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
2791 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
2792 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
2793 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
2794 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
2796 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
2803 ($path:expr, $expected:expr, $output:expr) => ( {
2804 let mut actual = PathBuf::from($path);
2805 let output = actual.pop();
2806 assert!(actual.to_str() == Some($expected) && output == $output,
2807 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2808 $path, $expected, $output,
2809 actual.to_str().unwrap(), output);
2814 tp!("/", "/", false);
2815 tp!("foo", "", true);
2817 tp!("/foo", "/", true);
2818 tp!("/foo/bar", "/foo", true);
2819 tp!("foo/bar", "foo", true);
2820 tp!("foo/.", "", true);
2821 tp!("foo//bar", "foo", true);
2824 tp!("a\\b\\c", "a\\b", true);
2825 tp!("\\a", "\\", true);
2826 tp!("\\", "\\", false);
2828 tp!("C:\\a\\b", "C:\\a", true);
2829 tp!("C:\\a", "C:\\", true);
2830 tp!("C:\\", "C:\\", false);
2831 tp!("C:a\\b", "C:a", true);
2832 tp!("C:a", "C:", true);
2833 tp!("C:", "C:", false);
2834 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
2835 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
2836 tp!("\\\\server\\share", "\\\\server\\share", false);
2837 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
2838 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
2839 tp!("\\\\?\\a", "\\\\?\\a", false);
2840 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
2841 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
2842 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
2843 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
2844 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
2845 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
2846 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
2847 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
2848 tp!("\\\\.\\a", "\\\\.\\a", false);
2850 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
2855 pub fn test_set_file_name() {
2857 ($path:expr, $file:expr, $expected:expr) => ( {
2858 let mut p = PathBuf::from($path);
2859 p.set_file_name($file);
2860 assert!(p.to_str() == Some($expected),
2861 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
2862 $path, $file, $expected,
2863 p.to_str().unwrap());
2867 tfn!("foo", "foo", "foo");
2868 tfn!("foo", "bar", "bar");
2869 tfn!("foo", "", "");
2870 tfn!("", "foo", "foo");
2872 tfn!(".", "foo", "./foo");
2873 tfn!("foo/", "bar", "bar");
2874 tfn!("foo/.", "bar", "bar");
2875 tfn!("..", "foo", "../foo");
2876 tfn!("foo/..", "bar", "foo/../bar");
2877 tfn!("/", "foo", "/foo");
2879 tfn!(".", "foo", r".\foo");
2880 tfn!(r"foo\", "bar", r"bar");
2881 tfn!(r"foo\.", "bar", r"bar");
2882 tfn!("..", "foo", r"..\foo");
2883 tfn!(r"foo\..", "bar", r"foo\..\bar");
2884 tfn!(r"\", "foo", r"\foo");
2889 pub fn test_set_extension() {
2891 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
2892 let mut p = PathBuf::from($path);
2893 let output = p.set_extension($ext);
2894 assert!(p.to_str() == Some($expected) && output == $output,
2895 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2896 $path, $ext, $expected, $output,
2897 p.to_str().unwrap(), output);
2901 tfe!("foo", "txt", "foo.txt", true);
2902 tfe!("foo.bar", "txt", "foo.txt", true);
2903 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
2904 tfe!(".test", "txt", ".test.txt", true);
2905 tfe!("foo.txt", "", "foo", true);
2906 tfe!("foo", "", "foo", true);
2907 tfe!("", "foo", "", false);
2908 tfe!(".", "foo", ".", false);
2909 tfe!("foo/", "bar", "foo.bar", true);
2910 tfe!("foo/.", "bar", "foo.bar", true);
2911 tfe!("..", "foo", "..", false);
2912 tfe!("foo/..", "bar", "foo/..", false);
2913 tfe!("/", "foo", "/", false);
2917 pub fn test_compare() {
2919 ($path1:expr, $path2:expr, eq: $eq:expr,
2920 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
2921 relative_from: $relative_from:expr) => ({
2922 let path1 = Path::new($path1);
2923 let path2 = Path::new($path2);
2925 let eq = path1 == path2;
2926 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
2927 $path1, $path2, $eq, eq);
2929 let starts_with = path1.starts_with(path2);
2930 assert!(starts_with == $starts_with,
2931 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2932 $starts_with, starts_with);
2934 let ends_with = path1.ends_with(path2);
2935 assert!(ends_with == $ends_with,
2936 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2937 $ends_with, ends_with);
2939 let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
2940 let exp: Option<&str> = $relative_from;
2941 assert!(relative_from == exp,
2942 "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
2943 exp, relative_from);
2951 relative_from: Some("")
2958 relative_from: Some("foo")
2972 relative_from: Some("")
2979 relative_from: Some("")
2982 tc!("foo/bar", "foo",
2986 relative_from: Some("bar")
2989 tc!("foo/bar/baz", "foo/bar",
2993 relative_from: Some("baz")
2996 tc!("foo/bar", "foo/bar/baz",
3003 tc!("./foo/bar/", ".",
3007 relative_from: Some("foo/bar")
3011 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
3012 r"c:\src\rust\cargo-test\test",
3016 relative_from: Some("Cargo.toml")
3019 tc!(r"c:\foo", r"C:\foo",
3023 relative_from: Some("")