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 involves 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 putting
54 //! together its components via `push`. Syntactically, the paths may differ by
55 //! 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 normal component `a` and a current directory component.
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, two additional component types come 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
79 //! * Empty components, a special case for so-called "verbatim" paths where very
80 //! little normalization is allowed. For example, `\\?\C:\` has a "verbatim"
81 //! prefix `\\?\C:`, a root component, and an empty component (as a way of
82 //! representing the trailing `\`. Such a trailing `\` is in fact the only
83 //! situation in which an empty component is produced.
87 //! Aside from splitting on the separator(s), there is a small amount of
90 //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a`
93 //! * Paths ending in a separator are treated as if they has a current directory
94 //! component at the end (or, in verbatim paths, an empty component). For
95 //! example, while `a/b` has components `a` and `b`, the paths `a/b/` and
96 //! `a/b/.` both have components `a`, `b`, and `.` (current directory). The
97 //! reason for this normalization is that `a/b` and `a/b/` are treated
98 //! differently in some contexts, but `a/b/` and `a/b/.` are always treated
101 //! No other normalization takes place by default. In particular, `a/./b/` and
102 //! `a/b` are treated distinctly in terms of components, as are `a/c` and
103 //! `a/b/../c`. Further normalization is possible to build on top of the
104 //! components APIs, and will be included in this library very soon.
106 #![unstable(feature = "path")]
108 use core::prelude::*;
111 use borrow::{Borrow, ToOwned, Cow};
113 use iter::{self, IntoIterator};
115 use ops::{self, Deref};
119 use ffi::{OsStr, OsString, AsOsStr};
121 use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
123 ////////////////////////////////////////////////////////////////////////////////
125 ////////////////////////////////////////////////////////////////////////////////
127 // Parsing in this module is done by directly transmuting OsStr to [u8] slices,
128 // taking advantage of the fact that OsStr always encodes ASCII characters
129 // as-is. Eventually, this transmutation should be replaced by direct uses of
130 // OsStr APIs for parsing, but it will take a while for those to become
133 ////////////////////////////////////////////////////////////////////////////////
134 // Platform-specific definitions
135 ////////////////////////////////////////////////////////////////////////////////
137 // The following modules give the most basic tools for parsing paths on various
138 // platforms. The bulk of the code is devoted to parsing prefixes on Windows.
143 use core::prelude::*;
147 pub fn is_sep_byte(b: u8) -> bool {
152 pub fn is_verbatim_sep(b: u8) -> bool {
156 pub fn parse_prefix(_: &OsStr) -> Option<Prefix> {
160 pub const MAIN_SEP_STR: &'static str = "/";
161 pub const MAIN_SEP: char = '/';
166 use core::prelude::*;
169 use char::CharExt as UnicodeCharExt;
170 use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
174 pub fn is_sep_byte(b: u8) -> bool {
175 b == b'/' || b == b'\\'
179 pub fn is_verbatim_sep(b: u8) -> bool {
183 pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> {
184 use super::Prefix::*;
186 // The unsafety here stems from converting between &OsStr and &[u8]
187 // and back. This is safe to do because (1) we only look at ASCII
188 // contents of the encoding and (2) new &OsStr values are produced
189 // only from ASCII-bounded slices of existing &OsStr values.
190 let mut path = os_str_as_u8_slice(path);
192 if path.starts_with(br"\\") {
195 if path.starts_with(br"?\") {
198 if path.starts_with(br"UNC\") {
199 // \\?\UNC\server\share
201 let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
202 Some((server, share)) => (u8_slice_as_os_str(server),
203 u8_slice_as_os_str(share)),
204 None => (u8_slice_as_os_str(path),
205 u8_slice_as_os_str(&[])),
207 return Some(VerbatimUNC(server, share));
210 let idx = path.position_elem(&b'\\');
211 if idx == Some(2) && path[1] == b':' {
213 if c.is_ascii() && (c as char).is_alphabetic() {
215 return Some(VerbatimDisk(c.to_ascii_uppercase()));
218 let slice = &path[.. idx.unwrap_or(path.len())];
219 return Some(Verbatim(u8_slice_as_os_str(slice)));
221 } else if path.starts_with(b".\\") {
224 let slice = &path[.. path.position_elem(&b'\\').unwrap_or(path.len())];
225 return Some(DeviceNS(u8_slice_as_os_str(slice)));
227 match parse_two_comps(path, is_sep_byte) {
228 Some((server, share)) if server.len() > 0 && share.len() > 0 => {
230 return Some(UNC(u8_slice_as_os_str(server),
231 u8_slice_as_os_str(share)));
235 } else if path.len() > 1 && path[1] == b':' {
238 if c.is_ascii() && (c as char).is_alphabetic() {
239 return Some(Disk(c.to_ascii_uppercase()));
245 fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> {
246 let first = match path.iter().position(|x| f(*x)) {
248 Some(x) => &path[.. x]
250 path = &path[(first.len()+1)..];
251 let idx = path.iter().position(|x| f(*x));
252 let second = &path[.. idx.unwrap_or(path.len())];
253 Some((first, second))
257 pub const MAIN_SEP_STR: &'static str = "\\";
258 pub const MAIN_SEP: char = '\\';
261 ////////////////////////////////////////////////////////////////////////////////
263 ////////////////////////////////////////////////////////////////////////////////
265 /// Path prefixes (Windows only).
267 /// Windows uses a variety of path styles, including references to drive
268 /// volumes (like `C:`), network shared (like `\\server\share`) and
269 /// others. In addition, some path prefixes are "verbatim", in which case
270 /// `/` is *not* treated as a separator and essentially no normalization is
272 #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
273 pub enum Prefix<'a> {
274 /// Prefix `\\?\`, together with the given component immediately following it.
277 /// Prefix `\\?\UNC\`, with the "server" and "share" components following it.
278 VerbatimUNC(&'a OsStr, &'a OsStr),
280 /// Prefix like `\\?\C:\`, for the given drive letter
283 /// Prefix `\\.\`, together with the given component immediately following it.
286 /// Prefix `\\server\share`, with the given "server" and "share" components.
287 UNC(&'a OsStr, &'a OsStr),
289 /// Prefix `C:` for the given disk drive.
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 pub fn is_verbatim(&self) -> bool {
320 Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true,
326 fn is_drive(&self) -> bool {
328 Prefix::Disk(_) => true,
334 fn has_implicit_root(&self) -> bool {
339 ////////////////////////////////////////////////////////////////////////////////
340 // Exposed parsing helpers
341 ////////////////////////////////////////////////////////////////////////////////
343 /// Determine whether the character is one of the permitted path
344 /// separators for the current platform.
345 pub fn is_separator(c: char) -> bool {
347 c.is_ascii() && is_sep_byte(c as u8)
350 /// The primary sperator for the current platform
351 pub const MAIN_SEPARATOR: char = platform::MAIN_SEP;
353 ////////////////////////////////////////////////////////////////////////////////
355 ////////////////////////////////////////////////////////////////////////////////
357 // Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
358 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
359 // `iter` after having exhausted `prefix`.
360 fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where
361 I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq
364 let mut iter_next = iter.clone();
365 match (iter_next.next(), prefix.next()) {
366 (Some(x), Some(y)) => {
367 if x != y { return None }
369 (Some(_), None) => return Some(iter),
370 (None, None) => return Some(iter),
371 (None, Some(_)) => return None,
377 // See note at the top of this module to understand why these are used:
378 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
379 unsafe { mem::transmute(s) }
381 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
385 ////////////////////////////////////////////////////////////////////////////////
386 // Cross-platform parsing
387 ////////////////////////////////////////////////////////////////////////////////
389 /// Says whether the path ends in a separator character and therefore needs to
390 /// be treated as if it ended with an additional `.`
391 fn has_suffix(s: &[u8], prefix: Option<Prefix>) -> bool {
392 let (prefix_len, verbatim) = if let Some(p) = prefix {
393 (p.len(), p.is_verbatim())
394 } else { (0, false) };
395 if prefix_len > 0 && prefix_len == s.len() && !verbatim { return true; }
396 let mut splits = s[prefix_len..].split(|b| is_sep_byte(*b));
397 let last = splits.next_back().unwrap();
398 let more = splits.next_back().is_some();
402 /// Says whether the first byte after the prefix is a separator.
403 fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
404 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
405 path.len() > 0 && is_sep_byte(path[0])
408 fn parse_single_component(comp: &[u8]) -> Option<Component> {
410 b"." => Some(Component::CurDir),
411 b".." => Some(Component::ParentDir),
413 _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) }))
417 // basic workhorse for splitting stem and extension
418 #[allow(unused_unsafe)] // FIXME
419 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
421 if os_str_as_u8_slice(file) == b".." { return (Some(file), None) }
423 // The unsafety here stems from converting between &OsStr and &[u8]
424 // and back. This is safe to do because (1) we only look at ASCII
425 // contents of the encoding and (2) new &OsStr values are produced
426 // only from ASCII-bounded slices of existing &OsStr values.
428 let mut iter = os_str_as_u8_slice(file).rsplitn(1, |b| *b == b'.');
429 let after = iter.next();
430 let before = iter.next();
431 if before == Some(b"") {
434 (before.map(|s| u8_slice_as_os_str(s)),
435 after.map(|s| u8_slice_as_os_str(s)))
440 ////////////////////////////////////////////////////////////////////////////////
441 // The core iterators
442 ////////////////////////////////////////////////////////////////////////////////
444 /// Component parsing works by a double-ended state machine; the cursors at the
445 /// front and back of the path each keep track of what parts of the path have
446 /// been consumed so far.
448 /// Going front to back, a path is made up of a prefix, a root component, a body
449 /// (of normal components), and a suffix/emptycomponent (normalized `.` or ``
450 /// for a path ending with the separator)
451 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
455 Body = 2, // foo/bar/baz
460 /// A single component of a path.
462 /// See the module documentation for an in-depth explanation of components and
463 /// their role in the API.
464 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
465 pub enum Component<'a> {
466 /// A Windows path prefix, e.g. `C:` or `\server\share`.
468 /// Does not occur on Unix.
470 /// The prefix as an unparsed `OsStr` slice.
473 /// The parsed prefix data.
477 /// An empty component. Only used on Windows for the last component of
478 /// verbatim paths ending with a separator (e.g. the last component of
479 /// `\\?\C:\windows\` but not `\\?\C:\windows` or `C:\windows`).
482 /// The root directory component, appears after any prefix and before anything else
485 /// A reference to the current directory, i.e. `.`
488 /// A reference to the parent directory, i.e. `..`
491 /// A normal component, i.e. `a` and `b` in `a/b`
495 impl<'a> Component<'a> {
496 /// Extract the underlying `OsStr` slice
497 pub fn as_os_str(self) -> &'a OsStr {
499 Component::Prefix { raw, .. } => &raw,
500 Component::Empty => OsStr::from_str(""),
501 Component::RootDir => OsStr::from_str(MAIN_SEP_STR),
502 Component::CurDir => OsStr::from_str("."),
503 Component::ParentDir => OsStr::from_str(".."),
504 Component::Normal(path) => path,
509 /// The core iterator giving the components of a path.
511 /// See the module documentation for an in-depth explanation of components and
512 /// their role in the API.
514 pub struct Components<'a> {
515 // The path left to parse components from
518 // The prefix as it was originally parsed, if any
519 prefix: Option<Prefix<'a>>,
521 // true if path *physically* has a root separator; for most Windows
522 // prefixes, it may have a "logical" rootseparator for the purposes of
523 // normalization, e.g. \\server\share == \\server\share\.
524 has_physical_root: bool,
526 // The iterator is double-ended, and these two states keep track of what has
527 // been produced from either end
532 /// An iterator over the components of a path, as `OsStr` slices.
534 pub struct Iter<'a> {
535 inner: Components<'a>
538 impl<'a> Components<'a> {
539 // how long is the prefix, if any?
541 fn prefix_len(&self) -> usize {
542 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
546 fn prefix_verbatim(&self) -> bool {
547 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
550 /// how much of the prefix is left from the point of view of iteration?
552 fn prefix_remaining(&self) -> usize {
553 if self.front == State::Prefix { self.prefix_len() }
557 fn prefix_and_root(&self) -> usize {
558 let root = if self.front <= State::Root && self.has_physical_root { 1 } else { 0 };
559 self.prefix_remaining() + root
562 // is the iteration complete?
564 fn finished(&self) -> bool {
565 self.front == State::Done || self.back == State::Done || self.front > self.back
569 fn is_sep_byte(&self, b: u8) -> bool {
570 if self.prefix_verbatim() {
577 /// Extract a slice corresponding to the portion of the path remaining for iteration.
578 pub fn as_path(&self) -> &'a Path {
579 let mut comps = self.clone();
580 if comps.front == State::Body { comps.trim_left(); }
581 if comps.back == State::Body { comps.trim_right(); }
582 if comps.path.is_empty() && comps.front < comps.back && comps.back == State::Suffix {
585 unsafe { Path::from_u8_slice(comps.path) }
589 /// Is the *original* path rooted?
590 fn has_root(&self) -> bool {
591 if self.has_physical_root { return true }
592 if let Some(p) = self.prefix {
593 if p.has_implicit_root() { return true }
598 // parse a component from the left, saying how many bytes to consume to
599 // remove the component
600 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
601 debug_assert!(self.front == State::Body);
602 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
603 None => (0, self.path),
604 Some(i) => (1, &self.path[.. i]),
606 (comp.len() + extra, parse_single_component(comp))
609 // parse a component from the right, saying how many bytes to consume to
610 // remove the component
611 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
612 debug_assert!(self.back == State::Body);
613 let start = self.prefix_and_root();
614 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
615 None => (0, &self.path[start ..]),
616 Some(i) => (1, &self.path[start + i + 1 ..]),
618 (comp.len() + extra, parse_single_component(comp))
621 // trim away repeated separators (i.e. emtpy components) on the left
622 fn trim_left(&mut self) {
623 while !self.path.is_empty() {
624 let (size, comp) = self.parse_next_component();
628 self.path = &self.path[size ..];
633 // trim away repeated separators (i.e. emtpy components) on the right
634 fn trim_right(&mut self) {
635 while self.path.len() > self.prefix_and_root() {
636 let (size, comp) = self.parse_next_component_back();
640 self.path = &self.path[.. self.path.len() - size];
645 /// Examine the next component without consuming it.
646 pub fn peek(&self) -> Option<Component<'a>> {
652 /// Extract a slice corresponding to the portion of the path remaining for iteration.
653 pub fn as_path(&self) -> &'a Path {
658 impl<'a> Iterator for Iter<'a> {
659 type Item = &'a OsStr;
661 fn next(&mut self) -> Option<&'a OsStr> {
662 self.inner.next().map(Component::as_os_str)
666 impl<'a> DoubleEndedIterator for Iter<'a> {
667 fn next_back(&mut self) -> Option<&'a OsStr> {
668 self.inner.next_back().map(Component::as_os_str)
672 impl<'a> Iterator for Components<'a> {
673 type Item = Component<'a>;
675 fn next(&mut self) -> Option<Component<'a>> {
676 while !self.finished() {
678 State::Prefix if self.prefix_len() > 0 => {
679 self.front = State::Root;
680 debug_assert!(self.prefix_len() <= self.path.len());
681 let raw = &self.path[.. self.prefix_len()];
682 self.path = &self.path[self.prefix_len() .. ];
683 return Some(Component::Prefix {
684 raw: unsafe { u8_slice_as_os_str(raw) },
685 parsed: self.prefix.unwrap()
689 self.front = State::Root;
692 self.front = State::Body;
693 if self.has_physical_root {
694 debug_assert!(self.path.len() > 0);
695 self.path = &self.path[1..];
696 return Some(Component::RootDir)
697 } else if let Some(p) = self.prefix {
698 if p.has_implicit_root() && !p.is_verbatim() {
699 return Some(Component::RootDir)
703 State::Body if !self.path.is_empty() => {
704 let (size, comp) = self.parse_next_component();
705 self.path = &self.path[size ..];
706 if comp.is_some() { return comp }
709 self.front = State::Suffix;
712 self.front = State::Done;
713 if self.prefix_verbatim() {
714 return Some(Component::Empty)
716 return Some(Component::CurDir)
719 State::Done => unreachable!()
726 impl<'a> DoubleEndedIterator for Components<'a> {
727 fn next_back(&mut self) -> Option<Component<'a>> {
728 while !self.finished() {
731 self.back = State::Body;
732 if self.prefix_verbatim() {
733 return Some(Component::Empty)
735 return Some(Component::CurDir)
738 State::Body if self.path.len() > self.prefix_and_root() => {
739 let (size, comp) = self.parse_next_component_back();
740 self.path = &self.path[.. self.path.len() - size];
741 if comp.is_some() { return comp }
744 self.back = State::Root;
747 self.back = State::Prefix;
748 if self.has_physical_root {
749 self.path = &self.path[.. self.path.len() - 1];
750 return Some(Component::RootDir)
751 } else if let Some(p) = self.prefix {
752 if p.has_implicit_root() && !p.is_verbatim() {
753 return Some(Component::RootDir)
757 State::Prefix if self.prefix_len() > 0 => {
758 self.back = State::Done;
759 return Some(Component::Prefix {
760 raw: unsafe { u8_slice_as_os_str(self.path) },
761 parsed: self.prefix.unwrap()
765 self.back = State::Done;
768 State::Done => unreachable!()
775 fn optional_path(path: &Path) -> Option<&Path> {
776 if path.as_u8_slice().is_empty() { None } else { Some(path) }
779 impl<'a> cmp::PartialEq for Components<'a> {
780 fn eq(&self, other: &Components<'a>) -> bool {
781 iter::order::eq(self.clone(), other.clone())
785 impl<'a> cmp::Eq for Components<'a> {}
787 impl<'a> cmp::PartialOrd for Components<'a> {
788 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
789 iter::order::partial_cmp(self.clone(), other.clone())
793 impl<'a> cmp::Ord for Components<'a> {
794 fn cmp(&self, other: &Components<'a>) -> cmp::Ordering {
795 iter::order::cmp(self.clone(), other.clone())
799 ////////////////////////////////////////////////////////////////////////////////
800 // Basic types and traits
801 ////////////////////////////////////////////////////////////////////////////////
803 /// An owned, mutable path (akin to `String`).
805 /// This type provides methods like `push` and `set_extension` that mutate the
806 /// path in place. It also implements `Deref` to `Path`, meaning that all
807 /// methods on `Path` slices are available on `PathBuf` values as well.
809 /// More details about the overall approach can be found in
810 /// the module documentation.
815 /// use std::path::PathBuf;
817 /// let mut path = PathBuf::new("c:\\");
818 /// path.push("windows");
819 /// path.push("system32");
820 /// path.set_extension("dll");
822 #[derive(Clone, Hash)]
828 fn as_mut_vec(&mut self) -> &mut Vec<u8> {
829 unsafe { mem::transmute(self) }
832 /// Allocate a `PathBuf` with initial contents given by the
834 pub fn new<S: ?Sized + AsOsStr>(s: &S) -> PathBuf {
835 PathBuf { inner: s.as_os_str().to_os_string() }
838 /// Extend `self` with `path`.
840 /// If `path` is absolute, it replaces the current path.
844 /// * if `path` has a root but no prefix (e.g. `\windows`), it
845 /// replaces everything except for the prefix (if any) of `self`.
846 /// * if `path` has a prefix but no root, it replaces `self.
847 pub fn push<P: ?Sized>(&mut self, path: &P) where P: AsPath {
848 // in general, a separator is needed if the rightmost byte is not a separator
849 let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
851 // in the special case of `C:` on Windows, do *not* add a separator
853 let comps = self.components();
854 if comps.prefix_len() > 0 &&
855 comps.prefix_len() == comps.path.len() &&
856 comps.prefix.unwrap().is_drive()
862 let path = path.as_path();
864 // absolute `path` replaces `self`
865 if path.is_absolute() || path.prefix().is_some() {
866 self.as_mut_vec().truncate(0);
868 // `path` has a root but no prefix, e.g. `\windows` (Windows only)
869 } else if path.has_root() {
870 let prefix_len = self.components().prefix_remaining();
871 self.as_mut_vec().truncate(prefix_len);
873 // `path` is a pure relative path
875 self.inner.push_os_str(OsStr::from_str(MAIN_SEP_STR));
878 self.inner.push_os_str(path.as_os_str());
881 /// Truncate `self` to `self.parent()`.
883 /// Returns `false` and does nothing if `self.parent()` is `None`.
884 /// Otherwise, returns `true`.
885 pub fn pop(&mut self) -> bool {
886 match self.parent().map(|p| p.as_u8_slice().len()) {
888 self.as_mut_vec().truncate(len);
895 /// Updates `self.file_name()` to `file_name`.
897 /// If `self.file_name()` was `None`, this is equivalent to pushing
903 /// use std::path::{Path, PathBuf};
905 /// let mut buf = PathBuf::new("/foo/");
906 /// assert!(buf.file_name() == None);
907 /// buf.set_file_name("bar");
908 /// assert!(buf == PathBuf::new("/foo/bar"));
909 /// assert!(buf.file_name().is_some());
910 /// buf.set_file_name("baz.txt");
911 /// assert!(buf == PathBuf::new("/foo/baz.txt"));
913 pub fn set_file_name<S: ?Sized>(&mut self, file_name: &S) where S: AsOsStr {
914 if self.file_name().is_some() && !self.pop() {
915 // Given that there is a file name, this is reachable only for
916 // Windows paths like c:file or paths like `foo`, but not `c:\` or
918 let prefix_len = self.components().prefix_remaining();
919 self.as_mut_vec().truncate(prefix_len);
921 self.push(file_name.as_os_str());
924 /// Updates `self.extension()` to `extension`.
926 /// If `self.file_name()` is `None`, does nothing and returns `false`.
928 /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
929 /// is added; otherwise it is replaced.
930 pub fn set_extension<S: ?Sized + AsOsStr>(&mut self, extension: &S) -> bool {
931 if self.file_name().is_none() { return false; }
933 let mut stem = match self.file_stem() {
934 Some(stem) => stem.to_os_string(),
935 None => OsString::from_str(""),
938 let extension = extension.as_os_str();
939 if os_str_as_u8_slice(extension).len() > 0 {
940 stem.push_os_str(OsStr::from_str("."));
941 stem.push_os_str(extension.as_os_str());
943 self.set_file_name(&stem);
948 /// Consume the `PathBuf`, yielding its internal `OsString` storage
949 pub fn into_os_string(self) -> OsString {
954 impl<'a, P: ?Sized + 'a> iter::FromIterator<&'a P> for PathBuf where P: AsPath {
955 fn from_iter<I: IntoIterator<Item = &'a P>>(iter: I) -> PathBuf {
956 let mut buf = PathBuf::new("");
962 impl<'a, P: ?Sized + 'a> iter::Extend<&'a P> for PathBuf where P: AsPath {
963 fn extend<I: IntoIterator<Item = &'a P>>(&mut self, iter: I) {
970 impl fmt::Debug for PathBuf {
971 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
972 fmt::Debug::fmt(&**self, formatter)
976 impl ops::Deref for PathBuf {
979 fn deref(&self) -> &Path {
980 unsafe { mem::transmute(&self.inner[..]) }
984 impl Borrow<Path> for PathBuf {
985 fn borrow(&self) -> &Path {
990 impl ToOwned for Path {
991 type Owned = PathBuf;
992 fn to_owned(&self) -> PathBuf { self.to_path_buf() }
995 impl cmp::PartialEq for PathBuf {
996 fn eq(&self, other: &PathBuf) -> bool {
997 self.components() == other.components()
1001 impl cmp::Eq for PathBuf {}
1003 impl cmp::PartialOrd for PathBuf {
1004 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
1005 self.components().partial_cmp(&other.components())
1009 impl cmp::Ord for PathBuf {
1010 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
1011 self.components().cmp(&other.components())
1015 impl AsOsStr for PathBuf {
1016 fn as_os_str(&self) -> &OsStr {
1021 /// A slice of a path (akin to `str`).
1023 /// This type supports a number of operations for inspecting a path, including
1024 /// breaking the path into its components (separated by `/` or `\`, depending on
1025 /// the platform), extracting the file name, determining whether the path is
1026 /// absolute, and so on. More details about the overall approach can be found in
1027 /// the module documentation.
1029 /// This is an *unsized* type, meaning that it must always be used with behind a
1030 /// pointer like `&` or `Box`.
1035 /// use std::path::Path;
1037 /// let path = Path::new("/tmp/foo/bar.txt");
1038 /// let file = path.file_name();
1039 /// let extension = path.extension();
1040 /// let parent_dir = path.parent();
1049 // The following (private!) function allows construction of a path from a u8
1050 // slice, which is only safe when it is known to follow the OsStr encoding.
1051 unsafe fn from_u8_slice(s: &[u8]) -> &Path {
1054 // The following (private!) function reveals the byte encoding used for OsStr.
1055 fn as_u8_slice(&self) -> &[u8] {
1056 unsafe { mem::transmute(self) }
1059 /// Directly wrap a string slice as a `Path` slice.
1061 /// This is a cost-free conversion.
1062 pub fn new<S: ?Sized + AsOsStr>(s: &S) -> &Path {
1063 unsafe { mem::transmute(s.as_os_str()) }
1066 /// Yield a `&str` slice if the `Path` is valid unicode.
1068 /// This conversion may entail doing a check for UTF-8 validity.
1069 pub fn to_str(&self) -> Option<&str> {
1073 /// Convert a `Path` to a `Cow<str>`.
1075 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
1076 pub fn to_string_lossy(&self) -> Cow<str> {
1077 self.inner.to_string_lossy()
1080 /// Convert a `Path` to an owned `PathBuf`.
1081 pub fn to_path_buf(&self) -> PathBuf {
1085 /// A path is *absolute* if it is independent of the current directory.
1087 /// * On Unix, a path is absolute if it starts with the root, so
1088 /// `is_absolute` and `has_root` are equivalent.
1090 /// * On Windows, a path is absolute if it has a prefix and starts with the
1091 /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In
1092 /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`.
1093 pub fn is_absolute(&self) -> bool {
1095 (cfg!(unix) || self.prefix().is_some())
1098 /// A path is *relative* if it is not absolute.
1099 pub fn is_relative(&self) -> bool {
1103 /// Returns the *prefix* of a path, if any.
1105 /// Prefixes are relevant only for Windows paths, and consist of volumes
1106 /// like `C:`, UNC prefixes like `\\server`, and others described in more
1107 /// detail in `std::os::windows::PathExt`.
1108 pub fn prefix(&self) -> Option<&Path> {
1109 let iter = self.components();
1110 optional_path(unsafe {
1111 Path::from_u8_slice(
1112 &self.as_u8_slice()[.. iter.prefix_remaining()])
1116 /// A path has a root if the body of the path begins with the directory separator.
1118 /// * On Unix, a path has a root if it begins with `/`.
1120 /// * On Windows, a path has a root if it:
1121 /// * has no prefix and begins with a separator, e.g. `\\windows`
1122 /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows`
1123 /// * has any non-disk prefix, e.g. `\\server\share`
1124 pub fn has_root(&self) -> bool {
1125 self.components().has_root()
1128 /// The path without its final component.
1130 /// Does nothing, returning `None` if the path consists of just a prefix
1131 /// and/or root directory reference.
1136 /// use std::path::Path;
1138 /// let path = Path::new("/foo/bar");
1139 /// let foo = path.parent().unwrap();
1140 /// assert!(foo == Path::new("/foo"));
1141 /// let root = foo.parent().unwrap();
1142 /// assert!(root == Path::new("/"));
1143 /// assert!(root.parent() == None);
1145 pub fn parent(&self) -> Option<&Path> {
1146 let mut comps = self.components();
1147 let comp = comps.next_back();
1148 let rest = optional_path(comps.as_path());
1150 match (comp, comps.next_back()) {
1151 (Some(Component::CurDir), Some(Component::RootDir)) => None,
1152 (Some(Component::CurDir), Some(Component::Prefix { .. })) => None,
1153 (Some(Component::Empty), Some(Component::RootDir)) => None,
1154 (Some(Component::Empty), Some(Component::Prefix { .. })) => None,
1155 (Some(Component::Prefix { .. }), None) => None,
1156 (Some(Component::RootDir), Some(Component::Prefix { .. })) => None,
1161 /// The final component of the path, if it is a normal file.
1163 /// If the path terminates in `.`, `..`, or consists solely or a root of
1164 /// prefix, `file` will return `None`.
1165 pub fn file_name(&self) -> Option<&OsStr> {
1166 self.components().next_back().and_then(|p| match p {
1167 Component::Normal(p) => Some(p.as_os_str()),
1172 /// Returns a path that, when joined onto `base`, yields `self`.
1173 pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where
1176 iter_after(self.components(), base.as_path().components()).map(|c| c.as_path())
1179 /// Determines whether `base` is a prefix of `self`.
1180 pub fn starts_with<P: ?Sized>(&self, base: &P) -> bool where P: AsPath {
1181 iter_after(self.components(), base.as_path().components()).is_some()
1184 /// Determines whether `base` is a suffix of `self`.
1185 pub fn ends_with<P: ?Sized>(&self, child: &P) -> bool where P: AsPath {
1186 iter_after(self.components().rev(), child.as_path().components().rev()).is_some()
1189 /// Extract the stem (non-extension) portion of `self.file()`.
1193 /// * None, if there is no file name;
1194 /// * The entire file name if there is no embedded `.`;
1195 /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1196 /// * Otherwise, the portion of the file name before the final `.`
1197 pub fn file_stem(&self) -> Option<&OsStr> {
1198 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after))
1201 /// Extract the extension of `self.file()`, if possible.
1203 /// The extension is:
1205 /// * None, if there is no file name;
1206 /// * None, if there is no embedded `.`;
1207 /// * None, if the file name begins with `.` and has no other `.`s within;
1208 /// * Otherwise, the portion of the file name after the final `.`
1209 pub fn extension(&self) -> Option<&OsStr> {
1210 self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after))
1213 /// Creates an owned `PathBuf` with `path` adjoined to `self`.
1215 /// See `PathBuf::push` for more details on what it means to adjoin a path.
1216 pub fn join<P: ?Sized>(&self, path: &P) -> PathBuf where P: AsPath {
1217 let mut buf = self.to_path_buf();
1222 /// Creates an owned `PathBuf` like `self` but with the given file name.
1224 /// See `PathBuf::set_file_name` for more details.
1225 pub fn with_file_name<S: ?Sized>(&self, file_name: &S) -> PathBuf where S: AsOsStr {
1226 let mut buf = self.to_path_buf();
1227 buf.set_file_name(file_name);
1231 /// Creates an owned `PathBuf` like `self` but with the given extension.
1233 /// See `PathBuf::set_extension` for more details.
1234 pub fn with_extension<S: ?Sized>(&self, extension: &S) -> PathBuf where S: AsOsStr {
1235 let mut buf = self.to_path_buf();
1236 buf.set_extension(extension);
1240 /// Produce an iterator over the components of the path.
1241 pub fn components(&self) -> Components {
1242 let prefix = parse_prefix(self.as_os_str());
1244 path: self.as_u8_slice(),
1246 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
1247 front: State::Prefix,
1248 back: if has_suffix(self.as_u8_slice(), prefix) { State::Suffix }
1249 else { State::Body },
1253 /// Produce an iterator over the path's components viewed as `OsStr` slices.
1254 pub fn iter(&self) -> Iter {
1255 Iter { inner: self.components() }
1258 /// Returns an object that implements `Display` for safely printing paths
1259 /// that may contain non-Unicode data.
1260 pub fn display(&self) -> Display {
1261 Display { path: self }
1265 impl AsOsStr for Path {
1266 fn as_os_str(&self) -> &OsStr {
1271 impl fmt::Debug for Path {
1272 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1273 self.inner.fmt(formatter)
1277 /// Helper struct for safely printing paths with `format!()` and `{}`
1278 pub struct Display<'a> {
1282 impl<'a> fmt::Debug for Display<'a> {
1283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1284 fmt::Debug::fmt(&self.path.to_string_lossy(), f)
1288 impl<'a> fmt::Display for Display<'a> {
1289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1290 fmt::Display::fmt(&self.path.to_string_lossy(), f)
1294 impl cmp::PartialEq for Path {
1295 fn eq(&self, other: &Path) -> bool {
1296 iter::order::eq(self.components(), other.components())
1300 impl cmp::Eq for Path {}
1302 impl cmp::PartialOrd for Path {
1303 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
1304 self.components().partial_cmp(&other.components())
1308 impl cmp::Ord for Path {
1309 fn cmp(&self, other: &Path) -> cmp::Ordering {
1310 self.components().cmp(&other.components())
1314 /// Freely convertible to a `Path`.
1316 /// Convert to a `Path`.
1317 fn as_path(&self) -> &Path;
1320 impl<T: AsOsStr + ?Sized> AsPath for T {
1321 fn as_path(&self) -> &Path { Path::new(self.as_os_str()) }
1328 use core::prelude::*;
1329 use string::{ToString, String};
1333 ($path:expr, iter: $iter:expr) => (
1335 let path = Path::new($path);
1337 // Forward iteration
1338 let comps = path.iter()
1339 .map(|p| p.to_string_lossy().into_owned())
1340 .collect::<Vec<String>>();
1341 let exp: &[&str] = &$iter;
1342 let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
1343 assert!(comps == exps, "iter: Expected {:?}, found {:?}",
1346 // Reverse iteration
1347 let comps = Path::new($path).iter().rev()
1348 .map(|p| p.to_string_lossy().into_owned())
1349 .collect::<Vec<String>>();
1350 let exps = exps.into_iter().rev().collect::<Vec<String>>();
1351 assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
1356 ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => (
1358 let path = Path::new($path);
1360 let act_root = path.has_root();
1361 assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}",
1362 $has_root, act_root);
1364 let act_abs = path.is_absolute();
1365 assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}",
1366 $is_absolute, act_abs);
1370 ($path:expr, parent: $parent:expr, file_name: $file:expr) => (
1372 let path = Path::new($path);
1374 let parent = path.parent().map(|p| p.to_str().unwrap());
1375 let exp_parent: Option<&str> = $parent;
1376 assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
1377 exp_parent, parent);
1379 let file = path.file_name().map(|p| p.to_str().unwrap());
1380 let exp_file: Option<&str> = $file;
1381 assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
1386 ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
1388 let path = Path::new($path);
1390 let stem = path.file_stem().map(|p| p.to_str().unwrap());
1391 let exp_stem: Option<&str> = $file_stem;
1392 assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
1395 let ext = path.extension().map(|p| p.to_str().unwrap());
1396 let exp_ext: Option<&str> = $extension;
1397 assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
1402 ($path:expr, iter: $iter:expr,
1403 has_root: $has_root:expr, is_absolute: $is_absolute:expr,
1404 parent: $parent:expr, file_name: $file:expr,
1405 file_stem: $file_stem:expr, extension: $extension:expr) => (
1407 t!($path, iter: $iter);
1408 t!($path, has_root: $has_root, is_absolute: $is_absolute);
1409 t!($path, parent: $parent, file_name: $file);
1410 t!($path, file_stem: $file_stem, extension: $extension);
1417 pub fn test_decompositions_unix() {
1433 file_name: Some("foo"),
1434 file_stem: Some("foo"),
1453 file_name: Some("foo"),
1454 file_stem: Some("foo"),
1462 parent: Some("foo"),
1469 iter: ["/", "foo", "."],
1472 parent: Some("/foo"),
1479 iter: ["foo", "bar"],
1482 parent: Some("foo"),
1483 file_name: Some("bar"),
1484 file_stem: Some("bar"),
1489 iter: ["/", "foo", "bar"],
1492 parent: Some("/foo"),
1493 file_name: Some("bar"),
1494 file_stem: Some("bar"),
1499 iter: ["/", "foo", "."],
1502 parent: Some("///foo"),
1509 iter: ["/", "foo", "bar"],
1512 parent: Some("///foo"),
1513 file_name: Some("bar"),
1514 file_stem: Some("bar"),
1562 parent: Some("foo"),
1569 iter: ["foo", ".."],
1572 parent: Some("foo"),
1579 iter: ["foo", ".", "."],
1582 parent: Some("foo/."),
1589 iter: ["foo", ".", "bar"],
1592 parent: Some("foo/."),
1593 file_name: Some("bar"),
1594 file_stem: Some("bar"),
1599 iter: ["foo", "..", "."],
1602 parent: Some("foo/.."),
1609 iter: ["foo", "..", "bar"],
1612 parent: Some("foo/.."),
1613 file_name: Some("bar"),
1614 file_stem: Some("bar"),
1623 file_name: Some("a"),
1624 file_stem: Some("a"),
1653 file_name: Some("b"),
1654 file_stem: Some("b"),
1663 file_name: Some("b"),
1664 file_stem: Some("b"),
1669 iter: ["a", ".", "b"],
1672 parent: Some("a/."),
1673 file_name: Some("b"),
1674 file_stem: Some("b"),
1679 iter: ["a", "b", "c"],
1682 parent: Some("a/b"),
1683 file_name: Some("c"),
1684 file_stem: Some("c"),
1691 pub fn test_decompositions_windows() {
1707 file_name: Some("foo"),
1708 file_stem: Some("foo"),
1743 iter: ["c:", "\\", "."],
1753 iter: ["c:", "\\", "."],
1763 iter: ["c:", "\\", "."],
1773 iter: ["\\", "foo"],
1777 file_name: Some("foo"),
1778 file_stem: Some("foo"),
1786 parent: Some("foo"),
1793 iter: ["\\", "foo", "."],
1796 parent: Some("/foo"),
1803 iter: ["foo", "bar"],
1806 parent: Some("foo"),
1807 file_name: Some("bar"),
1808 file_stem: Some("bar"),
1813 iter: ["\\", "foo", "bar"],
1816 parent: Some("/foo"),
1817 file_name: Some("bar"),
1818 file_stem: Some("bar"),
1823 iter: ["\\", "foo", "."],
1826 parent: Some("///foo"),
1833 iter: ["\\", "foo", "bar"],
1836 parent: Some("///foo"),
1837 file_name: Some("bar"),
1838 file_stem: Some("bar"),
1886 parent: Some("foo"),
1893 iter: ["foo", ".."],
1896 parent: Some("foo"),
1903 iter: ["foo", ".", "."],
1906 parent: Some("foo/."),
1913 iter: ["foo", ".", "bar"],
1916 parent: Some("foo/."),
1917 file_name: Some("bar"),
1918 file_stem: Some("bar"),
1923 iter: ["foo", "..", "."],
1926 parent: Some("foo/.."),
1933 iter: ["foo", "..", "bar"],
1936 parent: Some("foo/.."),
1937 file_name: Some("bar"),
1938 file_stem: Some("bar"),
1947 file_name: Some("a"),
1948 file_stem: Some("a"),
1977 file_name: Some("b"),
1978 file_stem: Some("b"),
1987 file_name: Some("b"),
1988 file_stem: Some("b"),
1993 iter: ["a", ".", "b"],
1996 parent: Some("a/."),
1997 file_name: Some("b"),
1998 file_stem: Some("b"),
2003 iter: ["a", "b", "c"],
2006 parent: Some("a/b"),
2007 file_name: Some("c"),
2008 file_stem: Some("c"),
2012 iter: ["a", "b", "c"],
2015 parent: Some("a\\b"),
2016 file_name: Some("c"),
2017 file_stem: Some("c"),
2026 file_name: Some("a"),
2027 file_stem: Some("a"),
2032 iter: ["c:", "\\", "foo.txt"],
2035 parent: Some("c:\\"),
2036 file_name: Some("foo.txt"),
2037 file_stem: Some("foo"),
2038 extension: Some("txt")
2041 t!("\\\\server\\share\\foo.txt",
2042 iter: ["\\\\server\\share", "\\", "foo.txt"],
2045 parent: Some("\\\\server\\share\\"),
2046 file_name: Some("foo.txt"),
2047 file_stem: Some("foo"),
2048 extension: Some("txt")
2051 t!("\\\\server\\share",
2052 iter: ["\\\\server\\share", "\\", "."],
2062 iter: ["\\", "server"],
2066 file_name: Some("server"),
2067 file_stem: Some("server"),
2071 t!("\\\\?\\bar\\foo.txt",
2072 iter: ["\\\\?\\bar", "\\", "foo.txt"],
2075 parent: Some("\\\\?\\bar\\"),
2076 file_name: Some("foo.txt"),
2077 file_stem: Some("foo"),
2078 extension: Some("txt")
2082 iter: ["\\\\?\\bar"],
2101 t!("\\\\?\\UNC\\server\\share\\foo.txt",
2102 iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
2105 parent: Some("\\\\?\\UNC\\server\\share\\"),
2106 file_name: Some("foo.txt"),
2107 file_stem: Some("foo"),
2108 extension: Some("txt")
2111 t!("\\\\?\\UNC\\server",
2112 iter: ["\\\\?\\UNC\\server"],
2122 iter: ["\\\\?\\UNC\\"],
2131 t!("\\\\?\\C:\\foo.txt",
2132 iter: ["\\\\?\\C:", "\\", "foo.txt"],
2135 parent: Some("\\\\?\\C:\\"),
2136 file_name: Some("foo.txt"),
2137 file_stem: Some("foo"),
2138 extension: Some("txt")
2143 iter: ["\\\\?\\C:", "\\", ""],
2154 iter: ["\\\\?\\C:"],
2164 t!("\\\\?\\foo/bar",
2165 iter: ["\\\\?\\foo/bar"],
2176 iter: ["\\\\?\\C:/foo"],
2186 t!("\\\\.\\foo\\bar",
2187 iter: ["\\\\.\\foo", "\\", "bar"],
2190 parent: Some("\\\\.\\foo\\"),
2191 file_name: Some("bar"),
2192 file_stem: Some("bar"),
2198 iter: ["\\\\.\\foo", "\\", "."],
2208 t!("\\\\.\\foo/bar",
2209 iter: ["\\\\.\\foo/bar", "\\", "."],
2219 t!("\\\\.\\foo\\bar/baz",
2220 iter: ["\\\\.\\foo", "\\", "bar", "baz"],
2223 parent: Some("\\\\.\\foo\\bar"),
2224 file_name: Some("baz"),
2225 file_stem: Some("baz"),
2231 iter: ["\\\\.\\", "\\", "."],
2241 iter: ["\\\\?\\a", "\\", "b", ""],
2244 parent: Some("\\\\?\\a\\b"),
2252 pub fn test_stem_ext() {
2254 file_stem: Some("foo"),
2259 file_stem: Some("foo"),
2264 file_stem: Some(".foo"),
2269 file_stem: Some("foo"),
2270 extension: Some("txt")
2274 file_stem: Some("foo.bar"),
2275 extension: Some("txt")
2279 file_stem: Some("foo.bar"),
2300 pub fn test_push() {
2302 ($path:expr, $push:expr, $expected:expr) => ( {
2303 let mut actual = PathBuf::new($path);
2305 assert!(actual.to_str() == Some($expected),
2306 "pushing {:?} onto {:?}: Expected {:?}, got {:?}",
2307 $push, $path, $expected, actual.to_str().unwrap());
2312 tp!("", "foo", "foo");
2313 tp!("foo", "bar", "foo/bar");
2314 tp!("foo/", "bar", "foo/bar");
2315 tp!("foo//", "bar", "foo//bar");
2316 tp!("foo/.", "bar", "foo/./bar");
2317 tp!("foo./.", "bar", "foo././bar");
2318 tp!("foo", "", "foo/");
2319 tp!("foo", ".", "foo/.");
2320 tp!("foo", "..", "foo/..");
2321 tp!("foo", "/", "/");
2322 tp!("/foo/bar", "/", "/");
2323 tp!("/foo/bar", "/baz", "/baz");
2324 tp!("/foo/bar", "./baz", "/foo/bar/./baz");
2326 tp!("", "foo", "foo");
2327 tp!("foo", "bar", r"foo\bar");
2328 tp!("foo/", "bar", r"foo/bar");
2329 tp!(r"foo\", "bar", r"foo\bar");
2330 tp!("foo//", "bar", r"foo//bar");
2331 tp!(r"foo\\", "bar", r"foo\\bar");
2332 tp!("foo/.", "bar", r"foo/.\bar");
2333 tp!("foo./.", "bar", r"foo./.\bar");
2334 tp!(r"foo\.", "bar", r"foo\.\bar");
2335 tp!(r"foo.\.", "bar", r"foo.\.\bar");
2336 tp!("foo", "", "foo\\");
2337 tp!("foo", ".", r"foo\.");
2338 tp!("foo", "..", r"foo\..");
2339 tp!("foo", "/", "/");
2340 tp!("foo", r"\", r"\");
2341 tp!("/foo/bar", "/", "/");
2342 tp!(r"\foo\bar", r"\", r"\");
2343 tp!("/foo/bar", "/baz", "/baz");
2344 tp!("/foo/bar", r"\baz", r"\baz");
2345 tp!("/foo/bar", "./baz", r"/foo/bar\./baz");
2346 tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz");
2348 tp!("c:\\", "windows", "c:\\windows");
2349 tp!("c:", "windows", "c:windows");
2351 tp!("a\\b\\c", "d", "a\\b\\c\\d");
2352 tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d");
2353 tp!("a\\b", "c\\d", "a\\b\\c\\d");
2354 tp!("a\\b", "\\c\\d", "\\c\\d");
2355 tp!("a\\b", ".", "a\\b\\.");
2356 tp!("a\\b", "..\\c", "a\\b\\..\\c");
2357 tp!("a\\b", "C:a.txt", "C:a.txt");
2358 tp!("a\\b", "C:\\a.txt", "C:\\a.txt");
2359 tp!("C:\\a", "C:\\b.txt", "C:\\b.txt");
2360 tp!("C:\\a\\b\\c", "C:d", "C:d");
2361 tp!("C:a\\b\\c", "C:d", "C:d");
2362 tp!("C:", r"a\b\c", r"C:a\b\c");
2363 tp!("C:", r"..\a", r"C:..\a");
2364 tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
2365 tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
2366 tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
2367 tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
2368 tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
2369 tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
2370 tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
2371 tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
2372 tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
2374 // Note: modified from old path API
2375 tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
2377 tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
2378 tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
2379 tp!("\\\\.\\foo\\bar", "C:a", "C:a");
2380 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
2381 tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
2383 tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
2390 ($path:expr, $expected:expr, $output:expr) => ( {
2391 let mut actual = PathBuf::new($path);
2392 let output = actual.pop();
2393 assert!(actual.to_str() == Some($expected) && output == $output,
2394 "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2395 $path, $expected, $output,
2396 actual.to_str().unwrap(), output);
2401 tp!("/", "/", false);
2402 tp!("foo", "foo", false);
2403 tp!(".", ".", false);
2404 tp!("/foo", "/", true);
2405 tp!("/foo/bar", "/foo", true);
2406 tp!("foo/bar", "foo", true);
2407 tp!("foo/.", "foo", true);
2408 tp!("foo//bar", "foo", true);
2411 tp!("a\\b\\c", "a\\b", true);
2412 tp!("\\a", "\\", true);
2413 tp!("\\", "\\", false);
2415 tp!("C:\\a\\b", "C:\\a", true);
2416 tp!("C:\\a", "C:\\", true);
2417 tp!("C:\\", "C:\\", false);
2418 tp!("C:a\\b", "C:a", true);
2419 tp!("C:a", "C:", true);
2420 tp!("C:", "C:", false);
2421 tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
2422 tp!("\\\\server\\share\\a", "\\\\server\\share\\", true);
2423 tp!("\\\\server\\share", "\\\\server\\share", false);
2424 tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
2425 tp!("\\\\?\\a\\b", "\\\\?\\a\\", true);
2426 tp!("\\\\?\\a", "\\\\?\\a", false);
2427 tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
2428 tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
2429 tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
2430 tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
2431 tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
2432 tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
2433 tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
2434 tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
2435 tp!("\\\\.\\a", "\\\\.\\a", false);
2437 tp!("\\\\?\\a\\b\\", "\\\\?\\a\\b", true);
2442 pub fn test_set_file_name() {
2444 ($path:expr, $file:expr, $expected:expr) => ( {
2445 let mut p = PathBuf::new($path);
2446 p.set_file_name($file);
2447 assert!(p.to_str() == Some($expected),
2448 "setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
2449 $path, $file, $expected,
2450 p.to_str().unwrap());
2454 tfn!("foo", "foo", "foo");
2455 tfn!("foo", "bar", "bar");
2456 tfn!("foo", "", "");
2457 tfn!("", "foo", "foo");
2459 tfn!(".", "foo", "./foo");
2460 tfn!("foo/", "bar", "foo/bar");
2461 tfn!("foo/.", "bar", "foo/./bar");
2462 tfn!("..", "foo", "../foo");
2463 tfn!("foo/..", "bar", "foo/../bar");
2464 tfn!("/", "foo", "/foo");
2466 tfn!(".", "foo", r".\foo");
2467 tfn!(r"foo\", "bar", r"foo\bar");
2468 tfn!(r"foo\.", "bar", r"foo\.\bar");
2469 tfn!("..", "foo", r"..\foo");
2470 tfn!(r"foo\..", "bar", r"foo\..\bar");
2471 tfn!(r"\", "foo", r"\foo");
2476 pub fn test_set_extension() {
2478 ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
2479 let mut p = PathBuf::new($path);
2480 let output = p.set_extension($ext);
2481 assert!(p.to_str() == Some($expected) && output == $output,
2482 "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
2483 $path, $ext, $expected, $output,
2484 p.to_str().unwrap(), output);
2488 tfe!("foo", "txt", "foo.txt", true);
2489 tfe!("foo.bar", "txt", "foo.txt", true);
2490 tfe!("foo.bar.baz", "txt", "foo.bar.txt", true);
2491 tfe!(".test", "txt", ".test.txt", true);
2492 tfe!("foo.txt", "", "foo", true);
2493 tfe!("foo", "", "foo", true);
2494 tfe!("", "foo", "", false);
2495 tfe!(".", "foo", ".", false);
2496 tfe!("foo/", "bar", "foo/", false);
2497 tfe!("foo/.", "bar", "foo/.", false);
2498 tfe!("..", "foo", "..", false);
2499 tfe!("foo/..", "bar", "foo/..", false);
2500 tfe!("/", "foo", "/", false);
2504 pub fn test_compare() {
2506 ($path1:expr, $path2:expr, eq: $eq:expr,
2507 starts_with: $starts_with:expr, ends_with: $ends_with:expr,
2508 relative_from: $relative_from:expr) => ({
2509 let path1 = Path::new($path1);
2510 let path2 = Path::new($path2);
2512 let eq = path1 == path2;
2513 assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
2514 $path1, $path2, $eq, eq);
2516 let starts_with = path1.starts_with(path2);
2517 assert!(starts_with == $starts_with,
2518 "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2519 $starts_with, starts_with);
2521 let ends_with = path1.ends_with(path2);
2522 assert!(ends_with == $ends_with,
2523 "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
2524 $ends_with, ends_with);
2526 let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap());
2527 let exp: Option<&str> = $relative_from;
2528 assert!(relative_from == exp,
2529 "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2,
2530 exp, relative_from);
2538 relative_from: Some("")
2545 relative_from: Some("foo")
2559 relative_from: Some("")
2566 relative_from: Some(".")
2569 tc!("foo/bar", "foo",
2573 relative_from: Some("bar")
2576 tc!("foo/bar/baz", "foo/bar",
2580 relative_from: Some("baz")
2583 tc!("foo/bar", "foo/bar/baz",
2590 tc!("./foo/bar/", ".",
2594 relative_from: Some("foo/bar/")