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::new("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};
106 use iter::{self, IntoIterator};
108 use ops::{self, Deref};
112 use ffi::{OsStr, OsString, AsOsStr};
114 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
116 ////////////////////////////////////////////////////////////////////////////////
118 ////////////////////////////////////////////////////////////////////////////////
120 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
121 // taking advantage of the fact that OsStr always encodes ASCII characters
122 // as-is. Eventually, this transmutation should be replaced by direct uses of
123 // OsStr APIs for parsing, but it will take a while for those to become
126 ////////////////////////////////////////////////////////////////////////////////
127 // Platform-specific definitions
128 ////////////////////////////////////////////////////////////////////////////////
130 // The following modules give the most basic tools for parsing paths on various
131 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
136 use core::prelude::*;
140 pub fn is_sep_byte(b: u8) -> bool {
145 pub fn is_verbatim_sep(b: u8) -> bool {
149 pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
153 pub const MAIN_SEP_STR: &'static str = "/";
154 pub const MAIN_SEP: char = '/';
159 use core::prelude::*;
162 use char::CharExt as UnicodeCharExt;
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.len() > 0 && share.len() > 0 => {
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 /// Determine 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 /// Determine whether the character is one of the permitted path
345 /// separators for the current platform.
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub fn is_separator(c: char) -> bool {
349 c.is_ascii() && is_sep_byte(c as u8)
352 /// The primary sperator for the current platform
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
356 ////////////////////////////////////////////////////////////////////////////////
358 ////////////////////////////////////////////////////////////////////////////////
360 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
361 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
362 // `iter` after having exhausted `prefix`.
363 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where
364 I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq
367 let mut iter_next = iter.clone();
368 match (iter_next.next(), prefix.next()) {
369 (Some(x), Some(y)) => {
370 if x != y { return None }
372 (Some(_), None) => return Some(iter),
373 (None, None) => return Some(iter),
374 (None, Some(_)) => return None,
380 // See note at the top of this module to understand why these are used:
381 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
382 unsafe { mem::transmute(s) }
384 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
388 ////////////////////////////////////////////////////////////////////////////////
389 // Cross-platform, iterator-independent parsing
390 ////////////////////////////////////////////////////////////////////////////////
392 /// Says whether the first byte after the prefix is a separator.
393 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
394 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
395 path.len() > 0 && is_sep_byte(path[0])
398 // basic workhorse for splitting stem and extension
399 #[allow(unused_unsafe)] // FIXME
400 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
402 if os_str_as_u8_slice(file) == b".." { return (Some(file), None) }
404 // The unsafety here stems from converting between &OsStr and &[u8]
405 // and back. This is safe to do because (1) we only look at ASCII
406 // contents of the encoding and (2) new &OsStr values are produced
407 // only from ASCII-bounded slices of existing &OsStr values.
409 let mut iter = os_str_as_u8_slice(file).rsplitn(1, |b| *b == b'.');
410 let after = iter.next();
411 let before = iter.next();
412 if before == Some(b"") {
415 (before.map(|s| u8_slice_as_os_str(s)),
416 after.map(|s| u8_slice_as_os_str(s)))
421 ////////////////////////////////////////////////////////////////////////////////
422 // The core iterators
423 ////////////////////////////////////////////////////////////////////////////////
425 /// Component parsing works by a double-ended state machine; the cursors at the
426 /// front and back of the path each keep track of what parts of the path have
427 /// been consumed so far.
429 /// Going front to back, a path is made up of a prefix, a starting
430 /// directory component, and a body (of normal components)
431 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
434 StartDir = 1, // / or . or nothing
435 Body = 2, // foo/bar/baz
439 /// A Windows path prefix, e.g. `C:` or `\server\share`.
441 /// Does not occur on Unix.
442 #[stable(feature = "rust1", since = "1.0.0")]
443 #[derive(Copy, Clone, Eq, Hash, Debug)]
444 pub struct PrefixComponent<'a> {
445 /// The prefix as an unparsed `OsStr` slice.
448 /// The parsed prefix data.
452 impl<'a> PrefixComponent<'a> {
453 /// The parsed prefix data.
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn kind(&self) -> Prefix<'a> {
459 /// The raw `OsStr` slice for this prefix.
460 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn as_os_str(&self) -> &'a OsStr {
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl<'a> cmp::PartialEq for PrefixComponent<'a> {
468 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
469 cmp::PartialEq::eq(&self.parsed, &other.parsed)
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<'a> cmp::PartialOrd for PrefixComponent<'a> {
475 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
476 cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed)
480 #[stable(feature = "rust1", since = "1.0.0")]
481 impl<'a> cmp::Ord for PrefixComponent<'a> {
482 fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering {
483 cmp::Ord::cmp(&self.parsed, &other.parsed)
487 /// A single component of a path.
489 /// See the module documentation for an in-depth explanation of components and
490 /// their role in the API.
491 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub enum Component<'a> {
494 /// A Windows path prefix, e.g. `C:` or `\server\share`.
496 /// Does not occur on Unix.
497 #[stable(feature = "rust1", since = "1.0.0")]
498 Prefix(PrefixComponent<'a>),
500 /// The root directory component, appears after any prefix and before anything else
501 #[stable(feature = "rust1", since = "1.0.0")]
504 /// A reference to the current directory, i.e. `.`
505 #[stable(feature = "rust1", since = "1.0.0")]
508 /// A reference to the parent directory, i.e. `..`
509 #[stable(feature = "rust1", since = "1.0.0")]
512 /// A normal component, i.e. `a` and `b` in `a/b`
513 #[stable(feature = "rust1", since = "1.0.0")]
517 impl<'a> Component<'a> {
518 /// Extract the underlying `OsStr` slice
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn as_os_str(self) -> &'a OsStr {
522 Component::Prefix(p) => p.as_os_str(),
523 Component::RootDir => OsStr::from_str(MAIN_SEP_STR),
524 Component::CurDir => OsStr::from_str("."),
525 Component::ParentDir => OsStr::from_str(".."),
526 Component::Normal(path) => path,
531 /// The core iterator giving the components of a path.
533 /// See the module documentation for an in-depth explanation of components and
534 /// their role in the API.
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub struct Components<'a> {
538 // The path left to parse components from
541 // The prefix as it was originally parsed, if any
542 prefix: Option<Prefix<'a>>,
544 // true if path *physically* has a root separator; for most Windows
545 // prefixes, it may have a "logical" rootseparator for the purposes of
546 // normalization, e.g. \\server\share == \\server\share\.
547 has_physical_root: bool,
549 // The iterator is double-ended, and these two states keep track of what has
550 // been produced from either end
555 /// An iterator over the components of a path, as `OsStr` slices.
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub struct Iter<'a> {
559 inner: Components<'a>
562 impl<'a> Components<'a> {
563 // how long is the prefix, if any?
565 fn prefix_len(&self) -> usize {
566 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
570 fn prefix_verbatim(&self) -> bool {
571 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
574 /// how much of the prefix is left from the point of view of iteration?
576 fn prefix_remaining(&self) -> usize {
577 if self.front == State::Prefix { self.prefix_len() }
581 // Given the iteration so far, how much of the pre-State::Body path is left?
583 fn len_before_body(&self) -> usize {
584 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
585 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
586 self.prefix_remaining() + root + cur_dir
589 // is the iteration complete?
591 fn finished(&self) -> bool {
592 self.front == State::Done || self.back == State::Done || self.front > self.back
596 fn is_sep_byte(&self, b: u8) -> bool {
597 if self.prefix_verbatim() {
604 /// Extract a slice corresponding to the portion of the path remaining for iteration.
605 pub fn as_path(&self) -> &'a Path {
606 let mut comps = self.clone();
607 if comps.front == State::Body { comps.trim_left(); }
608 if comps.back == State::Body { comps.trim_right(); }
609 unsafe { Path::from_u8_slice(comps.path) }
612 /// Is the *original* path rooted?
613 fn has_root(&self) -> bool {
614 if self.has_physical_root { return true }
615 if let Some(p) = self.prefix {
616 if p.has_implicit_root() { return true }
621 /// Should the normalized path include a leading . ?
622 fn include_cur_dir(&self) -> bool {
623 if self.has_root() { return false }
624 let mut iter = self.path[self.prefix_len()..].iter();
625 match (iter.next(), iter.next()) {
626 (Some(&b'.'), None) => true,
627 (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),
632 // parse a given byte sequence into the corresponding path component
633 fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
635 b"." if self.prefix_verbatim() => Some(Component::CurDir),
636 b"." => None, // . components are normalized away, except at
637 // the beginning of a path, which is treated
638 // separately via `include_cur_dir`
639 b".." => Some(Component::ParentDir),
641 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) }))
645 // parse a component from the left, saying how many bytes to consume to
646 // remove the component
647 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
648 debug_assert!(self.front == State::Body);
649 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
650 None => (0, self.path),
651 Some(i) => (1, &self.path[.. i]),
653 (comp.len() + extra, self.parse_single_component(comp))
656 // parse a component from the right, saying how many bytes to consume to
657 // remove the component
658 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
659 debug_assert!(self.back == State::Body);
660 let start = self.len_before_body();
661 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
662 None => (0, &self.path[start ..]),
663 Some(i) => (1, &self.path[start + i + 1 ..]),
665 (comp.len() + extra, self.parse_single_component(comp))
668 // trim away repeated separators (i.e. emtpy components) on the left
669 fn trim_left(&mut self) {
670 while !self.path.is_empty() {
671 let (size, comp) = self.parse_next_component();
675 self.path = &self.path[size ..];
680 // trim away repeated separators (i.e. emtpy components) on the right
681 fn trim_right(&mut self) {
682 while self.path.len() > self.len_before_body() {
683 let (size, comp) = self.parse_next_component_back();
687 self.path = &self.path[.. self.path.len() - size];
692 /// Examine the next component without consuming it.
693 #[unstable(feature = "path_components_peek")]
694 pub fn peek(&self) -> Option<Component<'a>> {
700 /// Extract a slice corresponding to the portion of the path remaining for iteration.
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn as_path(&self) -> &'a Path {
707 #[stable(feature = "rust1", since = "1.0.0")]
708 impl<'a> Iterator for Iter<'a> {
709 type Item = &'a OsStr;
711 fn next(&mut self) -> Option<&'a OsStr> {
712 self.inner.next().map(Component::as_os_str)
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl<'a> DoubleEndedIterator for Iter<'a> {
718 fn next_back(&mut self) -> Option<&'a OsStr> {
719 self.inner.next_back().map(Component::as_os_str)
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl<'a> Iterator for Components<'a> {
725 type Item = Component<'a>;
727 fn next(&mut self) -> Option<Component<'a>> {
728 while !self.finished() {
730 State::Prefix if self.prefix_len() > 0 => {
731 self.front = State::StartDir;
732 debug_assert!(self.prefix_len() <= self.path.len());
733 let raw = &self.path[.. self.prefix_len()];
734 self.path = &self.path[self.prefix_len() .. ];
735 return Some(Component::Prefix(PrefixComponent {
736 raw: unsafe { u8_slice_as_os_str(raw) },
737 parsed: self.prefix.unwrap()
741 self.front = State::StartDir;
744 self.front = State::Body;
745 if self.has_physical_root {
746 debug_assert!(self.path.len() > 0);
747 self.path = &self.path[1..];
748 return Some(Component::RootDir)
749 } else if let Some(p) = self.prefix {
750 if p.has_implicit_root() && !p.is_verbatim() {
751 return Some(Component::RootDir)
753 } else if self.include_cur_dir() {
754 debug_assert!(self.path.len() > 0);
755 self.path = &self.path[1..];
756 return Some(Component::CurDir)
759 State::Body if !self.path.is_empty() => {
760 let (size, comp) = self.parse_next_component();
761 self.path = &self.path[size ..];
762 if comp.is_some() { return comp }
765 self.front = State::Done;
767 State::Done => unreachable!()
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl<'a> DoubleEndedIterator for Components<'a> {
776 fn next_back(&mut self) -> Option<Component<'a>> {
777 while !self.finished() {
779 State::Body if self.path.len() > self.len_before_body() => {
780 let (size, comp) = self.parse_next_component_back();
781 self.path = &self.path[.. self.path.len() - size];
782 if comp.is_some() { return comp }
785 self.back = State::StartDir;
788 self.back = State::Prefix;
789 if self.has_physical_root {
790 self.path = &self.path[.. self.path.len() - 1];
791 return Some(Component::RootDir)
792 } else if let Some(p) = self.prefix {
793 if p.has_implicit_root() && !p.is_verbatim() {
794 return Some(Component::RootDir)
796 } else if self.include_cur_dir() {
797 self.path = &self.path[.. self.path.len() - 1];
798 return Some(Component::CurDir)
801 State::Prefix if self.prefix_len() > 0 => {
802 self.back = State::Done;
803 return Some(Component::Prefix(PrefixComponent {
804 raw: unsafe { u8_slice_as_os_str(self.path) },
805 parsed: self.prefix.unwrap()
809 self.back = State::Done;
812 State::Done => unreachable!()
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<'a> cmp::PartialEq for Components<'a> {
821 fn eq(&self, other: &Components<'a>) -> bool {
822 iter::order::eq(self.clone(), other.clone())
826 #[stable(feature = "rust1", since = "1.0.0")]
827 impl<'a> cmp::Eq for Components<'a> {}
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl<'a> cmp::PartialOrd for Components<'a> {
831 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
832 iter::order::partial_cmp(self.clone(), other.clone())
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<'a> cmp::Ord for Components<'a> {
838 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
839 iter::order::cmp(self.clone(), other.clone())
843 ////////////////////////////////////////////////////////////////////////////////
844 // Basic types and traits
845 ////////////////////////////////////////////////////////////////////////////////
847 /// An owned, mutable path (akin to `String`).
849 /// This type provides methods like `push` and `set_extension` that mutate the
850 /// path in place. It also implements `Deref` to `Path`, meaning that all
851 /// methods on `Path` slices are available on `PathBuf` values as well.
853 /// More details about the overall approach can be found in
854 /// the module documentation.
859 /// use std::path::PathBuf;
861 /// let mut path = PathBuf::new("c:\\");
862 /// path.push("windows");
863 /// path.push("system32");
864 /// path.set_extension("dll");
866 #[derive(Clone, Hash)]
867 #[stable(feature = "rust1", since = "1.0.0")]
873 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
874 unsafe { mem::transmute(self) }
877 /// Allocate a `PathBuf` with initial contents given by the
879 #[stable(feature = "rust1", since = "1.0.0")]
880 pub fn new<S: AsOsStr>(s: S) -> PathBuf {
881 PathBuf { inner: s.as_os_str().to_os_string() }
884 /// Extend `self` with `path`.
886 /// If `path` is absolute, it replaces the current path.
890 /// * if `path` has a root but no prefix (e.g. `\windows`), it
891 /// replaces everything except for the prefix (if any) of `self`.
892 /// * if `path` has a prefix but no root, it replaces `self.
893 #[stable(feature = "rust1", since = "1.0.0")]
894 pub fn push<P: AsPath>(&mut self, path: P) {
895 let path = path.as_path();
897 // in general, a separator is needed if the rightmost byte is not a separator
898 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
900 // in the special case of `C:` on Windows, do *not* add a separator
902 let comps = self.components();
903 if comps.prefix_len() > 0 &&
904 comps.prefix_len() == comps.path.len() &&
905 comps.prefix.unwrap().is_drive()
911 // absolute `path` replaces `self`
912 if path.is_absolute() || path.prefix().is_some() {
913 self.as_mut_vec().truncate(0);
915 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
916 } else if path.has_root() {
917 let prefix_len = self.components().prefix_remaining();
918 self.as_mut_vec().truncate(prefix_len);
920 // `path` is a pure relative path
922 self.inner.push(MAIN_SEP_STR);
925 self.inner.push(path);
928 /// Truncate `self` to `self.parent()`.
930 /// Returns false and does nothing if `self.file_name()` is `None`.
931 /// Otherwise, returns `true`.
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn pop(&mut self) -> bool {
934 match self.parent().map(|p| p.as_u8_slice().len()) {
936 self.as_mut_vec().truncate(len);
943 /// Updates `self.file_name()` to `file_name`.
945 /// If `self.file_name()` was `None`, this is equivalent to pushing
951 /// use std::path::PathBuf;
953 /// let mut buf = PathBuf::new("/");
954 /// assert!(buf.file_name() == None);
955 /// buf.set_file_name("bar");
956 /// assert!(buf == PathBuf::new("/bar"));
957 /// assert!(buf.file_name().is_some());
958 /// buf.set_file_name("baz.txt");
959 /// assert!(buf == PathBuf::new("/baz.txt"));
961 #[stable(feature = "rust1", since = "1.0.0")]
962 pub fn set_file_name<S: AsOsStr>(&mut self, file_name: S) {
963 if self.file_name().is_some() {
964 let popped = self.pop();
965 debug_assert!(popped);
967 self.push(file_name.as_os_str());
970 /// Updates `self.extension()` to `extension`.
972 /// If `self.file_name()` is `None`, does nothing and returns `false`.
974 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
975 /// is added; otherwise it is replaced.
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn set_extension<S: AsOsStr>(&mut self, extension: S) -> bool {
978 if self.file_name().is_none() { return false; }
980 let mut stem = match self.file_stem() {
981 Some(stem) => stem.to_os_string(),
982 None => OsString::from_str(""),
985 let extension = extension.as_os_str();
986 if os_str_as_u8_slice(extension).len() > 0 {
988 stem.push(extension);
990 self.set_file_name(&stem);
995 /// Consume the `PathBuf`, yielding its internal `OsString` storage
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn into_os_string(self) -> OsString {
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl<P: AsPath> iter::FromIterator<P> for PathBuf {
1004 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
1005 let mut buf = PathBuf::new("");
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl<P: AsPath> iter::Extend<P> for PathBuf {
1013 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl fmt::Debug for PathBuf {
1022 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1023 fmt::Debug::fmt(&**self, formatter)
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl ops::Deref for PathBuf {
1031 fn deref(&self) -> &Path {
1032 unsafe { mem::transmute(&self.inner[..]) }
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 impl Borrow<Path> for PathBuf {
1038 fn borrow(&self) -> &Path {
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 impl IntoCow<'static, Path> for PathBuf {
1045 fn into_cow(self) -> Cow<'static, Path> {
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 impl<'a> IntoCow<'a, Path> for &'a Path {
1052 fn into_cow(self) -> Cow<'a, Path> {
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 impl ToOwned for Path {
1059 type Owned = PathBuf;
1060 fn to_owned(&self) -> PathBuf { self.to_path_buf() }
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 impl cmp::PartialEq for PathBuf {
1065 fn eq(&self, other: &PathBuf) -> bool {
1066 self.components() == other.components()
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl cmp::Eq for PathBuf {}
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl cmp::PartialOrd for PathBuf {
1075 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1076 self.components().partial_cmp(&other.components())
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl cmp::Ord for PathBuf {
1082 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1083 self.components().cmp(&other.components())
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl AsOsStr for PathBuf {
1089 fn as_os_str(&self) -> &OsStr {
1094 /// A slice of a path (akin to `str`).
1096 /// This type supports a number of operations for inspecting a path, including
1097 /// breaking the path into its components (separated by `/` or `\`, depending on
1098 /// the platform), extracting the file name, determining whether the path is
1099 /// absolute, and so on. More details about the overall approach can be found in
1100 /// the module documentation.
1102 /// This is an *unsized* type, meaning that it must always be used with behind a
1103 /// pointer like `&` or `Box`.
1108 /// use std::path::Path;
1110 /// let path = Path::new("/tmp/foo/bar.txt");
1111 /// let file = path.file_name();
1112 /// let extension = path.extension();
1113 /// let parent_dir = path.parent();
1117 #[stable(feature = "rust1", since = "1.0.0")]
1123 // The following (private!) function allows construction of a path from a u8
1124 // slice, which is only safe when it is known to follow the OsStr encoding.
1125 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1128 // The following (private!) function reveals the byte encoding used for OsStr.
1129 fn as_u8_slice(&self) -> &[u8] {
1130 unsafe { mem::transmute(self) }
1133 /// Directly wrap a string slice as a `Path` slice.
1135 /// This is a cost-free conversion.
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn new<S: ?Sized + AsOsStr>(s: &S) -> &Path {
1138 unsafe { mem::transmute(s.as_os_str()) }
1141 /// Yield a `&str` slice if the `Path` is valid unicode.
1143 /// This conversion may entail doing a check for UTF-8 validity.
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn to_str(&self) -> Option<&str> {
1149 /// Convert a `Path` to a `Cow<str>`.
1151 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 pub fn to_string_lossy(&self) -> Cow<str> {
1154 self.inner.to_string_lossy()
1157 /// Convert a `Path` to an owned `PathBuf`.
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn to_path_buf(&self) -> PathBuf {
1163 /// A path is *absolute* if it is independent of the current directory.
1165 /// * On Unix, a path is absolute if it starts with the root, so
1166 /// `is_absolute` and `has_root` are equivalent.
1168 /// * On Windows, a path is absolute if it has a prefix and starts with the
1169 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1170 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub fn is_absolute(&self) -> bool {
1174 (cfg!(unix) || self.prefix().is_some())
1177 /// A path is *relative* if it is not absolute.
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub fn is_relative(&self) -> bool {
1183 /// Returns the *prefix* of a path, if any.
1185 /// Prefixes are relevant only for Windows paths, and consist of volumes
1186 /// like `C:`, UNC prefixes like `\\server`, and others described in more
1187 /// detail in `std::os::windows::PathExt`.
1188 #[unstable(feature = "path_prefix", reason = "uncertain whether to expose this convenience")]
1189 pub fn prefix(&self) -> Option<Prefix> {
1190 self.components().prefix
1193 /// A path has a root if the body of the path begins with the directory separator.
1195 /// * On Unix, a path has a root if it begins with `/`.
1197 /// * On Windows, a path has a root if it:
1198 /// * has no prefix and begins with a separator, e.g. `\\windows`
1199 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1200 /// * has any non-disk prefix, e.g. `\\server\share`
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 pub fn has_root(&self) -> bool {
1203 self.components().has_root()
1206 /// The path without its final component, if any.
1208 /// Returns `None` if the path terminates in a root or prefix.
1213 /// use std::path::Path;
1215 /// let path = Path::new("/foo/bar");
1216 /// let foo = path.parent().unwrap();
1217 /// assert!(foo == Path::new("/foo"));
1218 /// let root = foo.parent().unwrap();
1219 /// assert!(root == Path::new("/"));
1220 /// assert!(root.parent() == None);
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn parent(&self) -> Option<&Path> {
1224 let mut comps = self.components();
1225 let comp = comps.next_back();
1226 comp.and_then(|p| match p {
1227 Component::Normal(_) |
1229 Component::ParentDir => Some(comps.as_path()),
1234 /// The final component of the path, if it is a normal file.
1236 /// If the path terminates in `.`, `..`, or consists solely or a root of
1237 /// prefix, `file_name` will return `None`.
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 pub fn file_name(&self) -> Option<&OsStr> {
1240 self.components().next_back().and_then(|p| match p {
1241 Component::Normal(p) => Some(p.as_os_str()),
1246 /// Returns a path that, when joined onto `base`, yields `self`.
1247 #[unstable(feature = "path_relative_from", reason = "see #23284")]
1248 pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where
1251 iter_after(self.components(), base.as_path().components()).map(|c| c.as_path())
1254 /// Determines whether `base` is a prefix of `self`.
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 pub fn starts_with<P: AsPath>(&self, base: P) -> bool {
1257 iter_after(self.components(), base.as_path().components()).is_some()
1260 /// Determines whether `child` is a suffix of `self`.
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 pub fn ends_with<P: AsPath>(&self, child: P) -> bool {
1263 iter_after(self.components().rev(), child.as_path().components().rev()).is_some()
1266 /// Extract the stem (non-extension) portion of `self.file()`.
1270 /// * None, if there is no file name;
1271 /// * The entire file name if there is no embedded `.`;
1272 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1273 /// * Otherwise, the portion of the file name before the final `.`
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 pub fn file_stem(&self) -> Option<&OsStr> {
1276 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1279 /// Extract the extension of `self.file()`, if possible.
1281 /// The extension is:
1283 /// * None, if there is no file name;
1284 /// * None, if there is no embedded `.`;
1285 /// * None, if the file name begins with `.` and has no other `.`s within;
1286 /// * Otherwise, the portion of the file name after the final `.`
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 pub fn extension(&self) -> Option<&OsStr> {
1289 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1292 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1294 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 pub fn join<P: AsPath>(&self, path: P) -> PathBuf {
1297 let mut buf = self.to_path_buf();
1302 /// Creates an owned `PathBuf` like `self` but with the given file name.
1304 /// See `PathBuf::set_file_name` for more details.
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn with_file_name<S: AsOsStr>(&self, file_name: S) -> PathBuf {
1307 let mut buf = self.to_path_buf();
1308 buf.set_file_name(file_name);
1312 /// Creates an owned `PathBuf` like `self` but with the given extension.
1314 /// See `PathBuf::set_extension` for more details.
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn with_extension<S: AsOsStr>(&self, extension: S) -> PathBuf {
1317 let mut buf = self.to_path_buf();
1318 buf.set_extension(extension);
1322 /// Produce an iterator over the components of the path.
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 pub fn components(&self) -> Components {
1325 let prefix = parse_prefix(self.as_os_str());
1327 path: self.as_u8_slice(),
1329 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1330 front: State::Prefix,
1335 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 pub fn iter(&self) -> Iter {
1338 Iter { inner: self.components() }
1341 /// Returns an object that implements `Display` for safely printing paths
1342 /// that may contain non-Unicode data.
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 pub fn display(&self) -> Display {
1345 Display { path: self }
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 impl AsOsStr for Path {
1351 fn as_os_str(&self) -> &OsStr {
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl fmt::Debug for Path {
1358 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1359 self.inner.fmt(formatter)
1363 /// Helper struct for safely printing paths with `format!()` and `{}`
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub struct Display<'a> {
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<'a> fmt::Debug for Display<'a> {
1371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1372 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 impl<'a> fmt::Display for Display<'a> {
1378 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1379 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl cmp::PartialEq for Path {
1385 fn eq(&self, other: &Path) -> bool {
1386 iter::order::eq(self.components(), other.components())
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl cmp::Eq for Path {}
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl cmp::PartialOrd for Path {
1395 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1396 self.components().partial_cmp(&other.components())
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl cmp::Ord for Path {
1402 fn cmp(&self, other: &Path) -> cmp::Ordering {
1403 self.components().cmp(&other.components())
1407 /// Freely convertible to a `Path`.
1408 #[unstable(feature = "std_misc")]
1410 /// Convert to a `Path`.
1411 #[unstable(feature = "std_misc")]
1412 fn as_path(&self) -> &Path;
1415 #[unstable(feature = "std_misc")]
1416 impl<T: AsOsStr + ?Sized> AsPath for T {
1417 fn as_path(&self) -> &Path { Path::new(self.as_os_str()) }
1423 use core::prelude::*;
1424 use string::{ToString, String};
1428 ($path:expr, iter: $iter:expr) => (
1430 let path = Path::new($path);
1432 // Forward iteration
1433 let comps = path.iter()
1434 .map(|p| p.to_string_lossy().into_owned())
1435 .collect::<Vec<String>>();
1436 let exp: &[&str] = &$iter;
1437 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
1438 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
1441 // Reverse iteration
1442 let comps = Path::new($path).iter().rev()
1443 .map(|p| p.to_string_lossy().into_owned())
1444 .collect::<Vec<String>>();
1445 let exps = exps.into_iter().rev().collect::<Vec<String>>();
1446 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
1451 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
1453 let path = Path::new($path);
1455 let act_root = path.has_root();
1456 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
1457 $has_root, act_root);
1459 let act_abs = path.is_absolute();
1460 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
1461 $is_absolute, act_abs);
1465 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
1467 let path = Path::new($path);
1469 let parent = path.parent().map(|p| p.to_str().unwrap());
1470 let exp_parent: Option<&str> = $parent;
1471 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
1472 exp_parent, parent);
1474 let file = path.file_name().map(|p| p.to_str().unwrap());
1475 let exp_file: Option<&str> = $file;
1476 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
1481 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
1483 let path = Path::new($path);
1485 let stem = path.file_stem().map(|p| p.to_str().unwrap());
1486 let exp_stem: Option<&str> = $file_stem;
1487 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
1490 let ext = path.extension().map(|p| p.to_str().unwrap());
1491 let exp_ext: Option<&str> = $extension;
1492 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
1497 ($path:expr, iter: $iter:expr,
1498 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
1499 parent: $parent:expr, file_name: $file:expr,
1500 file_stem: $file_stem:expr, extension: $extension:expr) => (
1502 t!($path, iter: $iter);
1503 t!($path, has_root: $has_root, is_absolute: $is_absolute);
1504 t!($path, parent: $parent, file_name: $file);
1505 t!($path, file_stem: $file_stem, extension: $extension);
1512 use borrow::{Cow, IntoCow};
1514 let static_path = Path::new("/home/foo");
1515 let static_cow_path: Cow<'static, Path> = static_path.into_cow();
1516 let pathbuf = PathBuf::new("/home/foo");
1519 let path: &Path = &pathbuf;
1520 let borrowed_cow_path: Cow<Path> = path.into_cow();
1522 assert_eq!(static_cow_path, borrowed_cow_path);
1525 let owned_cow_path: Cow<'static, Path> = pathbuf.into_cow();
1527 assert_eq!(static_cow_path, owned_cow_path);
1532 pub fn test_decompositions_unix() {
1548 file_name: Some("foo"),
1549 file_stem: Some("foo"),
1568 file_name: Some("foo"),
1569 file_stem: Some("foo"),
1578 file_name: Some("foo"),
1579 file_stem: Some("foo"),
1588 file_name: Some("foo"),
1589 file_stem: Some("foo"),
1594 iter: ["foo", "bar"],
1597 parent: Some("foo"),
1598 file_name: Some("bar"),
1599 file_stem: Some("bar"),
1604 iter: ["/", "foo", "bar"],
1607 parent: Some("/foo"),
1608 file_name: Some("bar"),
1609 file_stem: Some("bar"),
1618 file_name: Some("foo"),
1619 file_stem: Some("foo"),
1624 iter: ["/", "foo", "bar"],
1627 parent: Some("///foo"),
1628 file_name: Some("bar"),
1629 file_stem: Some("bar"),
1668 file_name: Some("foo"),
1669 file_stem: Some("foo"),
1674 iter: ["foo", ".."],
1677 parent: Some("foo"),
1688 file_name: Some("foo"),
1689 file_stem: Some("foo"),
1694 iter: ["foo", "bar"],
1697 parent: Some("foo"),
1698 file_name: Some("bar"),
1699 file_stem: Some("bar"),
1704 iter: ["foo", ".."],
1707 parent: Some("foo"),
1714 iter: ["foo", "..", "bar"],
1717 parent: Some("foo/.."),
1718 file_name: Some("bar"),
1719 file_stem: Some("bar"),
1728 file_name: Some("a"),
1729 file_stem: Some("a"),
1758 file_name: Some("b"),
1759 file_stem: Some("b"),
1768 file_name: Some("b"),
1769 file_stem: Some("b"),
1778 file_name: Some("b"),
1779 file_stem: Some("b"),
1784 iter: ["a", "b", "c"],
1787 parent: Some("a/b"),
1788 file_name: Some("c"),
1789 file_stem: Some("c"),
1798 file_name: Some(".foo"),
1799 file_stem: Some(".foo"),
1806 pub fn test_decompositions_windows() {
1822 file_name: Some("foo"),
1823 file_stem: Some("foo"),
1878 iter: ["\\", "foo"],
1882 file_name: Some("foo"),
1883 file_stem: Some("foo"),
1892 file_name: Some("foo"),
1893 file_stem: Some("foo"),
1898 iter: ["\\", "foo"],
1902 file_name: Some("foo"),
1903 file_stem: Some("foo"),
1908 iter: ["foo", "bar"],
1911 parent: Some("foo"),
1912 file_name: Some("bar"),
1913 file_stem: Some("bar"),
1918 iter: ["\\", "foo", "bar"],
1921 parent: Some("/foo"),
1922 file_name: Some("bar"),
1923 file_stem: Some("bar"),
1928 iter: ["\\", "foo"],
1932 file_name: Some("foo"),
1933 file_stem: Some("foo"),
1938 iter: ["\\", "foo", "bar"],
1941 parent: Some("///foo"),
1942 file_name: Some("bar"),
1943 file_stem: Some("bar"),
1982 file_name: Some("foo"),
1983 file_stem: Some("foo"),
1988 iter: ["foo", ".."],
1991 parent: Some("foo"),
2002 file_name: Some("foo"),
2003 file_stem: Some("foo"),
2008 iter: ["foo", "bar"],
2011 parent: Some("foo"),
2012 file_name: Some("bar"),
2013 file_stem: Some("bar"),
2018 iter: ["foo", ".."],
2021 parent: Some("foo"),
2028 iter: ["foo", "..", "bar"],
2031 parent: Some("foo/.."),
2032 file_name: Some("bar"),
2033 file_stem: Some("bar"),
2042 file_name: Some("a"),
2043 file_stem: Some("a"),
2072 file_name: Some("b"),
2073 file_stem: Some("b"),
2082 file_name: Some("b"),
2083 file_stem: Some("b"),
2092 file_name: Some("b"),
2093 file_stem: Some("b"),
2098 iter: ["a", "b", "c"],
2101 parent: Some("a/b"),
2102 file_name: Some("c"),
2103 file_stem: Some("c"),
2107 iter: ["a", "b", "c"],
2110 parent: Some("a\\b"),
2111 file_name: Some("c"),
2112 file_stem: Some("c"),
2121 file_name: Some("a"),
2122 file_stem: Some("a"),
2127 iter: ["c:", "\\", "foo.txt"],
2130 parent: Some("c:\\"),
2131 file_name: Some("foo.txt"),
2132 file_stem: Some("foo"),
2133 extension: Some("txt")
2136 t!("\\\\server\\share\\foo.txt",
2137 iter: ["\\\\server\\share", "\\", "foo.txt"],
2140 parent: Some("\\\\server\\share\\"),
2141 file_name: Some("foo.txt"),
2142 file_stem: Some("foo"),
2143 extension: Some("txt")
2146 t!("\\\\server\\share",
2147 iter: ["\\\\server\\share", "\\"],
2157 iter: ["\\", "server"],
2161 file_name: Some("server"),
2162 file_stem: Some("server"),
2166 t!("\\\\?\\bar\\foo.txt",
2167 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2170 parent: Some("\\\\?\\bar\\"),
2171 file_name: Some("foo.txt"),
2172 file_stem: Some("foo"),
2173 extension: Some("txt")
2177 iter: ["\\\\?\\bar"],
2196 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2197 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2200 parent: Some("\\\\?\\UNC\\server\\share\\"),
2201 file_name: Some("foo.txt"),
2202 file_stem: Some("foo"),
2203 extension: Some("txt")
2206 t!("\\\\?\\UNC\\server",
2207 iter: ["\\\\?\\UNC\\server"],
2217 iter: ["\\\\?\\UNC\\"],
2226 t!("\\\\?\\C:\\foo.txt",
2227 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2230 parent: Some("\\\\?\\C:\\"),
2231 file_name: Some("foo.txt"),
2232 file_stem: Some("foo"),
2233 extension: Some("txt")
2238 iter: ["\\\\?\\C:", "\\"],
2249 iter: ["\\\\?\\C:"],
2259 t!("\\\\?\\foo/bar",
2260 iter: ["\\\\?\\foo/bar"],
2271 iter: ["\\\\?\\C:/foo"],
2281 t!("\\\\.\\foo\\bar",
2282 iter: ["\\\\.\\foo", "\\", "bar"],
2285 parent: Some("\\\\.\\foo\\"),
2286 file_name: Some("bar"),
2287 file_stem: Some("bar"),
2293 iter: ["\\\\.\\foo", "\\"],
2303 t!("\\\\.\\foo/bar",
2304 iter: ["\\\\.\\foo/bar", "\\"],
2314 t!("\\\\.\\foo\\bar/baz",
2315 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
2318 parent: Some("\\\\.\\foo\\bar"),
2319 file_name: Some("baz"),
2320 file_stem: Some("baz"),
2326 iter: ["\\\\.\\", "\\"],
2336 iter: ["\\\\?\\a", "\\", "b"],
2339 parent: Some("\\\\?\\a\\"),
2340 file_name: Some("b"),
2341 file_stem: Some("b"),
2347 pub fn test_stem_ext() {
2349 file_stem: Some("foo"),
2354 file_stem: Some("foo"),
2359 file_stem: Some(".foo"),
2364 file_stem: Some("foo"),
2365 extension: Some("txt")
2369 file_stem: Some("foo.bar"),
2370 extension: Some("txt")
2374 file_stem: Some("foo.bar"),
2395 pub fn test_push() {
2397 ($path:expr, $push:expr, $expected:expr) => ( {
2398 let mut actual = PathBuf::new($path);
2400 assert!(actual.to_str() == Some($expected),
2401 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
2402 $push, $path, $expected, actual.to_str().unwrap());
2407 tp!("", "foo", "foo");
2408 tp!("foo", "bar", "foo/bar");
2409 tp!("foo/", "bar", "foo/bar");
2410 tp!("foo//", "bar", "foo//bar");
2411 tp!("foo/.", "bar", "foo/./bar");
2412 tp!("foo./.", "bar", "foo././bar");
2413 tp!("foo", "", "foo/");
2414 tp!("foo", ".", "foo/.");
2415 tp!("foo", "..", "foo/..");
2416 tp!("foo", "/", "/");
2417 tp!("/foo/bar", "/", "/");
2418 tp!("/foo/bar", "/baz", "/baz");
2419 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
2421 tp!("", "foo", "foo");
2422 tp!("foo", "bar", r"foo\bar");
2423 tp!("foo/", "bar", r"foo/bar");
2424 tp!(r"foo\", "bar", r"foo\bar");
2425 tp!("foo//", "bar", r"foo//bar");
2426 tp!(r"foo\\", "bar", r"foo\\bar");
2427 tp!("foo/.", "bar", r"foo/.\bar");
2428 tp!("foo./.", "bar", r"foo./.\bar");
2429 tp!(r"foo\.", "bar", r"foo\.\bar");
2430 tp!(r"foo.\.", "bar", r"foo.\.\bar");
2431 tp!("foo", "", "foo\\");
2432 tp!("foo", ".", r"foo\.");
2433 tp!("foo", "..", r"foo\..");
2434 tp!("foo", "/", "/");
2435 tp!("foo", r"\", r"\");
2436 tp!("/foo/bar", "/", "/");
2437 tp!(r"\foo\bar", r"\", r"\");
2438 tp!("/foo/bar", "/baz", "/baz");
2439 tp!("/foo/bar", r"\baz", r"\baz");
2440 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
2441 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
2443 tp!("c:\\", "windows", "c:\\windows");
2444 tp!("c:", "windows", "c:windows");
2446 tp!("a\\b\\c", "d", "a\\b\\c\\d");
2447 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
2448 tp!("a\\b", "c\\d", "a\\b\\c\\d");
2449 tp!("a\\b", "\\c\\d", "\\c\\d");
2450 tp!("a\\b", ".", "a\\b\\.");
2451 tp!("a\\b", "..\\c", "a\\b\\..\\c");
2452 tp!("a\\b", "C:a.txt", "C:a.txt");
2453 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
2454 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
2455 tp!("C:\\a\\b\\c", "C:d", "C:d");
2456 tp!("C:a\\b\\c", "C:d", "C:d");
2457 tp!("C:", r"a\b\c", r"C:a\b\c");
2458 tp!("C:", r"..\a", r"C:..\a");
2459 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
2460 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
2461 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
2462 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
2463 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
2464 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
2465 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
2466 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
2467 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
2469 // Note: modified from old path API
2470 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
2472 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
2473 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
2474 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
2475 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
2476 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
2478 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
2485 ($path:expr, $expected:expr, $output:expr) => ( {
2486 let mut actual = PathBuf::new($path);
2487 let output = actual.pop();
2488 assert!(actual.to_str() == Some($expected) && output == $output,
2489 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2490 $path, $expected, $output,
2491 actual.to_str().unwrap(), output);
2496 tp!("/", "/", false);
2497 tp!("foo", "", true);
2499 tp!("/foo", "/", true);
2500 tp!("/foo/bar", "/foo", true);
2501 tp!("foo/bar", "foo", true);
2502 tp!("foo/.", "", true);
2503 tp!("foo//bar", "foo", true);
2506 tp!("a\\b\\c", "a\\b", true);
2507 tp!("\\a", "\\", true);
2508 tp!("\\", "\\", false);
2510 tp!("C:\\a\\b", "C:\\a", true);
2511 tp!("C:\\a", "C:\\", true);
2512 tp!("C:\\", "C:\\", false);
2513 tp!("C:a\\b", "C:a", true);
2514 tp!("C:a", "C:", true);
2515 tp!("C:", "C:", false);
2516 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
2517 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
2518 tp!("\\\\server\\share", "\\\\server\\share", false);
2519 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
2520 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
2521 tp!("\\\\?\\a", "\\\\?\\a", false);
2522 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
2523 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
2524 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
2525 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
2526 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
2527 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
2528 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
2529 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
2530 tp!("\\\\.\\a", "\\\\.\\a", false);
2532 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true);
2537 pub fn test_set_file_name() {
2539 ($path:expr, $file:expr, $expected:expr) => ( {
2540 let mut p = PathBuf::new($path);
2541 p.set_file_name($file);
2542 assert!(p.to_str() == Some($expected),
2543 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
2544 $path, $file, $expected,
2545 p.to_str().unwrap());
2549 tfn!("foo", "foo", "foo");
2550 tfn!("foo", "bar", "bar");
2551 tfn!("foo", "", "");
2552 tfn!("", "foo", "foo");
2554 tfn!(".", "foo", "./foo");
2555 tfn!("foo/", "bar", "bar");
2556 tfn!("foo/.", "bar", "bar");
2557 tfn!("..", "foo", "../foo");
2558 tfn!("foo/..", "bar", "foo/../bar");
2559 tfn!("/", "foo", "/foo");
2561 tfn!(".", "foo", r".\foo");
2562 tfn!(r"foo\", "bar", r"bar");
2563 tfn!(r"foo\.", "bar", r"bar");
2564 tfn!("..", "foo", r"..\foo");
2565 tfn!(r"foo\..", "bar", r"foo\..\bar");
2566 tfn!(r"\", "foo", r"\foo");
2571 pub fn test_set_extension() {
2573 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
2574 let mut p = PathBuf::new($path);
2575 let output = p.set_extension($ext);
2576 assert!(p.to_str() == Some($expected) && output == $output,
2577 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2578 $path, $ext, $expected, $output,
2579 p.to_str().unwrap(), output);
2583 tfe!("foo", "txt", "foo.txt", true);
2584 tfe!("foo.bar", "txt", "foo.txt", true);
2585 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
2586 tfe!(".test", "txt", ".test.txt", true);
2587 tfe!("foo.txt", "", "foo", true);
2588 tfe!("foo", "", "foo", true);
2589 tfe!("", "foo", "", false);
2590 tfe!(".", "foo", ".", false);
2591 tfe!("foo/", "bar", "foo.bar", true);
2592 tfe!("foo/.", "bar", "foo.bar", true);
2593 tfe!("..", "foo", "..", false);
2594 tfe!("foo/..", "bar", "foo/..", false);
2595 tfe!("/", "foo", "/", false);
2599 pub fn test_compare() {
2601 ($path1:expr, $path2:expr, eq: $eq:expr,
2602 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
2603 relative_from: $relative_from:expr) => ({
2604 let path1 = Path::new($path1);
2605 let path2 = Path::new($path2);
2607 let eq = path1 == path2;
2608 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
2609 $path1, $path2, $eq, eq);
2611 let starts_with = path1.starts_with(path2);
2612 assert!(starts_with == $starts_with,
2613 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2614 $starts_with, starts_with);
2616 let ends_with = path1.ends_with(path2);
2617 assert!(ends_with == $ends_with,
2618 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2619 $ends_with, ends_with);
2621 let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
2622 let exp: Option<&str> = $relative_from;
2623 assert!(relative_from == exp,
2624 "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
2625 exp, relative_from);
2633 relative_from: Some("")
2640 relative_from: Some("foo")
2654 relative_from: Some("")
2661 relative_from: Some("")
2664 tc!("foo/bar", "foo",
2668 relative_from: Some("bar")
2671 tc!("foo/bar/baz", "foo/bar",
2675 relative_from: Some("baz")
2678 tc!("foo/bar", "foo/bar/baz",
2685 tc!("./foo/bar/", ".",
2689 relative_from: Some("foo/bar")
2693 tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
2694 r"c:\src\rust\cargo-test\test",
2698 relative_from: Some("Cargo.toml")
2701 tc!(r"c:\foo", r"C:\foo",
2705 relative_from: Some("")